Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(codex): add manual session finalizer
AkitaOnRailsde1cef2fcfe2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1e65a707..61421852 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added `ai-memory finalize-session`, a supported manual Codex finalization+ flow. It defaults to the latest open Codex session in the current+ workspace/project and posts a synthetic `session-end` hook so summaries,+ handoffs, and auto-improvement eligibility use the canonical SessionEnd path.+### Fixed- Native hook spool delivery no longer relies only on the cancellation-prone`session-end` hook to start the detached drainer. `stop` and `pre-compact`diff --git a/README.md b/README.mdindex 0ba5c6bb..4e90679b 100644--- a/README.md+++ b/README.md@@ -23,7 +23,7 @@| Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. || Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Claude Code uses Claude exec form with a real native `ai-memory.exe` by default; other script-hook agents use the current PowerShell defaults pending harness feedback. See [`docs/windows.md`](docs/windows.md). || Claude Code | Supported | MCP config + lifecycle hooks. |-| Codex | Supported | MCP config + lifecycle hooks. |+| Codex | Supported | MCP config + lifecycle hooks; no automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. || OpenCode | Supported | Remote MCP config + generated TypeScript plugin. || Cursor | Supported | MCP config + lifecycle hooks. || Gemini CLI | Supported | MCP config + lifecycle hooks. |@@ -73,7 +73,8 @@ priors are at the [bottom](#influences-and-prior-art).Same page path can exist in two projects without collision; arename is one column update; a purge is one `rm -rf`.- **Karpathy-style LLM wiki.** Pages are compiled from observations- at session-end (or PreCompact), not retrieved over raw logs.+ at session-end (or PreCompact; Codex can use `ai-memory finalize-session`+ for a manual final close), not retrieved over raw logs.Supersession chain + git-versioned markdown means you cantime-travel with `ai-memory checkpoints`, `restore-page`, or raw `git log`.- **Built-in `/web` browser.** Read-only HTML UI for the wiki -@@ -96,7 +97,9 @@ priors are at the [bottom](#influences-and-prior-art).all HTTP clients of the running server - never touch SQLite orwiki files directly. `status` also reports passive LLM/embeddingprovider health from the last real provider call. Server is the- single source of truth.+ single source of truth. `finalize-session` is the exception: it reads the+ local SQLite index only to find matching open sessions, then posts synthetic+ `session-end` hooks back to the server.- **LLM is opt-in.** Zero-LLM mode still gives you FTS5 search +rule-based summarisation. Add a provider when you want consolidatedpages, lint contradictions, or staged auto-improvement proposals.diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex da9c39ef..10e0babd 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -92,6 +92,8 @@ pub enum Command {AutoImproveReport(AutoImproveReportArgs),/// Run auto-improvement for one completed session.AutoImprove(AutoImproveArgs),+ /// Manually finalize the latest open Codex session for this project.+ FinalizeSession(FinalizeSessionArgs),/// Review, approve, or reject staged auto-improvement proposals.PendingWrites(PendingWritesArgs),/// Compute + store embeddings for every latest page (M9).@@ -818,6 +820,27 @@ pub enum AgentChoice {Grok,}+/// Arguments for `finalize-session`.+#[derive(Debug, Args)]+pub struct FinalizeSessionArgs {+ /// Agent kind to finalize. Defaults to Codex because Codex has no reliable+ /// true SessionEnd hook.+ #[arg(long, value_enum, default_value_t = AgentChoice::Codex)]+ pub agent: AgentChoice,+ /// Workspace name. Defaults to `default`.+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]+ pub workspace: String,+ /// Project name. When omitted, auto-derived from the current project.+ #[arg(long)]+ pub project: Option<String>,+ /// Finalize every matching open session instead of just the latest one.+ #[arg(long)]+ pub all: bool,+ /// Emit a JSON summary.+ #[arg(long)]+ pub json: bool,+}+/// MCP client to render configuration for. Includes both the/// hook-capable agents (Claude Code / Codex / OpenCode — same MCP/// surface, also covered by `install-hooks`) and the MCP-onlydiff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rsnew file mode 100644index 00000000..36ca67c7--- /dev/null+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs@@ -0,0 +1,268 @@+//! `ai-memory finalize-session` — manually synthesize SessionEnd for Codex.++use ai_memory_core::AgentKind;+use ai_memory_store::{DB_FILENAME, OpenSession, ReaderPool};+use anyhow::{Context, Result, bail};+use serde::{Deserialize, Serialize};++use crate::cli::{AgentChoice, FinalizeSessionArgs};+use crate::config::Config;+use crate::http_client::ServerEndpoint;++#[derive(Debug, Serialize)]+struct SessionEndPayload<'a> {+ session_id: String,+ cwd: &'a str,+}++#[derive(Debug, Serialize)]+struct HookBatchItem<'a> {+ url: String,+ body: SessionEndPayload<'a>,+}++#[derive(Debug, Deserialize)]+struct HookBatchAck {+ accepted: usize,+}++#[derive(Debug, Serialize, Deserialize)]+struct FinalizeSessionReport {+ workspace: String,+ project: String,+ agent: String,+ finalized: Vec<String>,+}++/// Run the `finalize-session` subcommand.+///+/// # Errors+/// Returns an error if the local store cannot be read or the configured server+/// rejects a synthetic `session-end` hook.+pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {+ let agent = agent_choice_to_kind(args.agent);+ let project = super::resolve_project_name(config, args.project.as_deref())?;+ let db_path = config.data_dir.join("db").join(DB_FILENAME);+ if !db_path.exists() {+ return print_report(args, project, agent, Vec::new());+ }+ let reader = ReaderPool::new(&db_path, 1).context("opening local store reader")?;+ let workspace_id = match reader.find_workspace(args.workspace.clone()).await? {+ Some(id) => id,+ None => return print_report(args, project, agent, Vec::new()),+ };+ let project_id = match reader.find_project(workspace_id, project.clone()).await? {+ Some(id) => id,+ None => return print_report(args, project, agent, Vec::new()),+ };++ let limit = if args.all { None } else { Some(1) };+ let sessions = reader+ .open_sessions_for_scope_agent(workspace_id, project_id, agent, limit)+ .await?;+ if sessions.is_empty() {+ return print_report(args, project, agent, Vec::new());+ }++ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let client = reqwest::Client::new();+ let fallback_cwd = effective_cwd(config)?;+ let mut finalized = Vec::with_capacity(sessions.len());+ for session in &sessions {+ post_session_end_batch(+ &client,+ &endpoint,+ session,+ fallback_cwd.as_str(),+ &args.workspace,+ &project,+ agent,+ )+ .await?;+ finalized.push(session.session_id.to_string());+ }++ print_report(args, project, agent, finalized)+}++fn print_report(+ args: FinalizeSessionArgs,+ project: String,+ agent: AgentKind,+ finalized: Vec<String>,+) -> Result<()> {+ let report = FinalizeSessionReport {+ workspace: args.workspace,+ project,+ agent: agent.as_str().to_string(),+ finalized,+ };+ if args.json {+ println!("{}", serde_json::to_string_pretty(&report)?);+ } else if report.finalized.is_empty() {+ println!(+ "No open {} sessions matched {}/{}",+ report.agent, report.workspace, report.project+ );+ } else {+ println!(+ "Finalized {} {} session(s) for {}/{}",+ report.finalized.len(),+ report.agent,+ report.workspace,+ report.project+ );+ for session_id in &report.finalized {+ println!(" - {session_id}");+ }+ }+ Ok(())+}++async fn post_session_end_batch(+ client: &reqwest::Client,+ endpoint: &ServerEndpoint,+ session: &OpenSession,+ fallback_cwd: &str,+ workspace: &str,+ project: &str,+ agent: AgentKind,+) -> Result<()> {+ let cwd = session.cwd.as_deref().unwrap_or(fallback_cwd);+ let hook_url = session_end_hook_url(endpoint, cwd, workspace, project, agent)?;+ let batch_url = endpoint.build_url("/hook/batch");+ let items = [HookBatchItem {+ url: hook_url,+ body: SessionEndPayload {+ session_id: session.session_id.to_string(),+ cwd,+ },+ }];+ let request = client.post(&batch_url).json(&items);+ let request = endpoint.authenticate(request);+ let response = request+ .send()+ .await+ .with_context(|| format!("posting synthetic session-end batch to {batch_url}"))?;+ let status = response.status();+ if !status.is_success() {+ let body = response.text().await.unwrap_or_default();+ bail!("server returned {status}: {body}");+ }+ let ack: HookBatchAck = response+ .json()+ .await+ .with_context(|| format!("parsing hook batch ack from {batch_url}"))?;+ if ack.accepted != 1 {+ bail!(+ "server accepted {} of 1 synthetic session-end events",+ ack.accepted+ );+ }+ Ok(())+}++fn session_end_hook_url(+ endpoint: &ServerEndpoint,+ cwd: &str,+ workspace: &str,+ project: &str,+ agent: AgentKind,+) -> Result<String> {+ let mut url = reqwest::Url::parse(&endpoint.build_url("/hook"))+ .context("building synthetic session-end hook URL")?;+ url.query_pairs_mut()+ .append_pair("event", "session-end")+ .append_pair("agent", agent.as_str())+ .append_pair("cwd", cwd)+ .append_pair("workspace", workspace)+ .append_pair("project", project);+ Ok(url.into())+}++fn effective_cwd(config: &Config) -> Result<String> {+ if let Some(host_cwd) = config.runtime_env.host_cwd()+ && !host_cwd.trim().is_empty()+ {+ return Ok(host_cwd.to_string());+ }+ Ok(std::env::current_dir()+ .context("getting CWD for synthetic session-end")?+ .to_string_lossy()+ .into_owned())+}++fn agent_choice_to_kind(choice: AgentChoice) -> AgentKind {+ match choice {+ AgentChoice::ClaudeCode => AgentKind::ClaudeCode,+ AgentChoice::Codex => AgentKind::Codex,+ AgentChoice::OpenCode => AgentKind::OpenCode,+ AgentChoice::Cursor => AgentKind::Cursor,+ AgentChoice::GeminiCli => AgentKind::GeminiCli,+ AgentChoice::Openclaw => AgentKind::OpenClaw,+ AgentChoice::AntigravityCli => AgentKind::AntigravityCli,+ AgentChoice::Omp => AgentKind::Omp,+ AgentChoice::Pi => AgentKind::Pi,+ AgentChoice::Grok => AgentKind::Grok,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ai_memory_core::{NewSession, SessionId};+ use ai_memory_store::Store;+ use tempfile::TempDir;++ #[tokio::test]+ async fn selects_latest_scoped_codex_session_only_by_default() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let target = store+ .writer+ .get_or_create_project(ws, "target".to_string(), None)+ .await+ .unwrap();+ let other_project = store+ .writer+ .get_or_create_project(ws, "other".to_string(), None)+ .await+ .unwrap();+ let older = SessionId::new();+ let latest = SessionId::new();+ let other_agent = SessionId::new();+ let other_scope = SessionId::new();+ for (id, project_id, agent) in [+ (older, target, AgentKind::Codex),+ (other_agent, target, AgentKind::ClaudeCode),+ (other_scope, other_project, AgentKind::Codex),+ (latest, target, AgentKind::Codex),+ ] {+ store+ .writer+ .begin_session(NewSession {+ id,+ workspace_id: ws,+ project_id,+ agent_kind: agent,+ cwd: Some(std::path::PathBuf::from("/tmp/target")),+ })+ .await+ .unwrap();+ }++ let selected = store+ .reader+ .open_sessions_for_scope_agent(ws, target, AgentKind::Codex, Some(1))+ .await+ .unwrap();++ assert_eq!(selected.len(), 1);+ assert_eq!(selected[0].session_id, latest);+ }+}diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 66d995ad..ed34d999 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -3760,6 +3760,10 @@ model = "gpt-5"parsed["hooks"]["SessionStart"].is_array(),"SessionStart hook should be present");+ assert!(+ parsed["hooks"].get("SessionEnd").is_none(),+ "Codex has no reliable true SessionEnd hook; install must omit it"+ );}#[test]diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex f14b1df0..09a6ad0c 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -17,6 +17,7 @@ pub mod curator;pub mod data_purge;pub mod delete_page;pub mod embed;+pub mod finalize_session;pub mod forget_sweep;pub mod generate_auth_token;pub mod hook;diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 14116b57..c23b0d3d 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -85,6 +85,7 @@ async fn main() -> Result<()> {Command::Curator(args) => commands::curator::run(&config, args).await,Command::AutoImproveReport(args) => commands::auto_improve_report::run(&config, args).await,Command::AutoImprove(args) => commands::auto_improve::run(&config, args).await,+ Command::FinalizeSession(args) => commands::finalize_session::run(&config, args).await,Command::PendingWrites(args) => commands::pending_writes::run(&config, args).await,Command::Embed(args) => commands::embed::run(&config, args).await,Command::GenerateAuthToken(args) => commands::generate_auth_token::run(&config, args),diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex a120ffda..6bb66a29 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -919,6 +919,20 @@ async fn process().await?;+ if matches!(env.event, HookEvent::SessionEnd)+ && !state+ .reader+ .session_is_open_for_scope_agent(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(());+ }+// Hooks are fire-and-forget and may arrive out of order. Begin the// session idempotently before every observation so a resumed agent// session, or a prompt racing ahead of SessionStart, cannot trip the@@ -3037,6 +3051,245 @@ mod tests {);}+ #[tokio::test]+ async fn stop_does_not_end_session() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let sid = "22222222-2222-2222-2222-222222222222";++ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "stop".into(),+ agent: Some("codex".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": sid }),+ );+ process(&state, env, None).await.unwrap();++ let completed = state+ .reader+ .latest_completed_session_for_project(state.workspace_id, state.project_id)+ .await+ .unwrap();+ assert!(+ completed.is_none(),+ "Stop must not be treated as SessionEnd"+ );+ }++ #[tokio::test]+ async fn session_end_closes_only_matching_scoped_session() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let target = state+ .writer+ .get_or_create_project(state.workspace_id, "target", None)+ .await+ .unwrap();+ let other = state+ .writer+ .get_or_create_project(state.workspace_id, "other", None)+ .await+ .unwrap();+ let target_sid = SessionId::new();+ let other_project_sid = SessionId::new();+ let other_agent_sid = SessionId::new();+ for (id, project_id, agent) in [+ (target_sid, target, AgentKind::Codex),+ (other_project_sid, other, AgentKind::Codex),+ (other_agent_sid, target, AgentKind::ClaudeCode),+ ] {+ state+ .writer+ .begin_session(NewSession {+ id,+ workspace_id: state.workspace_id,+ project_id,+ agent_kind: agent,+ cwd: Some(std::path::PathBuf::from("/tmp/target")),+ })+ .await+ .unwrap();+ }++ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-end".into(),+ agent: Some("codex".into()),+ cwd: Some("/tmp/target".into()),+ workspace: Some("default".into()),+ project: Some("target".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": target_sid.to_string(), "cwd": "/tmp/target" }),+ );+ process(&state, env, None).await.unwrap();++ assert_eq!(+ state+ .reader+ .latest_completed_session_for_project(state.workspace_id, target)+ .await+ .unwrap(),+ Some(target_sid)+ );+ assert_eq!(+ state+ .reader+ .open_sessions_for_scope_agent(state.workspace_id, other, AgentKind::Codex, None)+ .await+ .unwrap()+ .len(),+ 1,+ "other project Codex session must remain open"+ );+ assert_eq!(+ state+ .reader+ .open_sessions_for_scope_agent(+ state.workspace_id,+ target,+ AgentKind::ClaudeCode,+ None+ )+ .await+ .unwrap()+ .len(),+ 1,+ "other agent session in same project must remain open"+ );+ }++ #[tokio::test]+ async fn mismatched_session_end_does_not_create_summary_or_handoff() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let target = state+ .writer+ .get_or_create_project(state.workspace_id, "target", None)+ .await+ .unwrap();+ let other = state+ .writer+ .get_or_create_project(state.workspace_id, "other", None)+ .await+ .unwrap();+ let wrong_project_sid = SessionId::new();+ let wrong_agent_sid = SessionId::new();+ for (id, project_id, agent) in [+ (wrong_project_sid, other, AgentKind::Codex),+ (wrong_agent_sid, target, AgentKind::ClaudeCode),+ ] {+ state+ .writer+ .begin_session(NewSession {+ id,+ workspace_id: state.workspace_id,+ project_id,+ agent_kind: agent,+ cwd: Some(std::path::PathBuf::from("/tmp/target")),+ })+ .await+ .unwrap();+ }++ for sid in [wrong_project_sid, wrong_agent_sid] {+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-end".into(),+ agent: Some("codex".into()),+ cwd: Some("/tmp/target".into()),+ workspace: Some("default".into()),+ project: Some("target".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": sid.to_string(), "cwd": "/tmp/target" }),+ );+ process(&state, env, None).await.unwrap();+ }++ let pages = state+ .reader+ .recent_pages_for_project(state.workspace_id, target, 20)+ .await+ .unwrap();+ assert!(+ pages+ .iter()+ .all(|p| !p.path.as_str().starts_with("sessions/")),+ "mismatched SessionEnd must not write target summary pages: {:?}",+ pages.iter().map(|p| p.path.as_str()).collect::<Vec<_>>()+ );+ assert!(+ state+ .reader+ .latest_open_handoff(state.workspace_id, target, None)+ .await+ .unwrap()+ .is_none(),+ "mismatched SessionEnd must not create a target handoff"+ );+ }++ #[tokio::test]+ async fn already_ended_session_end_does_not_create_summary_or_handoff() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let target = state+ .writer+ .get_or_create_project(state.workspace_id, "target", None)+ .await+ .unwrap();+ let sid = SessionId::new();+ state+ .writer+ .begin_session(NewSession {+ id: sid,+ workspace_id: state.workspace_id,+ project_id: target,+ agent_kind: AgentKind::Codex,+ cwd: Some(std::path::PathBuf::from("/tmp/target")),+ })+ .await+ .unwrap();+ state.writer.end_session(sid, None).await.unwrap();++ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "session-end".into(),+ agent: Some("codex".into()),+ cwd: Some("/tmp/target".into()),+ workspace: Some("default".into()),+ project: Some("target".into()),+ ..Default::default()+ },+ serde_json::json!({ "session_id": sid.to_string(), "cwd": "/tmp/target" }),+ );+ process(&state, env, None).await.unwrap();++ let pages = state+ .reader+ .recent_pages_for_project(state.workspace_id, target, 20)+ .await+ .unwrap();+ assert!(+ pages+ .iter()+ .all(|p| !p.path.as_str().starts_with("sessions/")),+ "already-ended synthetic SessionEnd must not write summary pages"+ );+ assert!(+ state+ .reader+ .latest_open_handoff(state.workspace_id, target, None)+ .await+ .unwrap()+ .is_none(),+ "already-ended synthetic SessionEnd must not create a handoff"+ );+ }+#[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.rsindex 922e3660..86bd0a59 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -38,10 +38,10 @@ pub use ops::{EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary};pub use reader::{ActivityWindow, AutoImproveCandidateSession, BriefingPage, BriefingSnapshot,ContaminationFinding, ContaminationReport, ContaminationSummary, DecayCandidate,- DerivedIndexStatus, EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageAuthor,- PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,- ReindexTargetStatus, RelatedPage, ScopeRow, StatusCounts, StoredEmbedding, StoredPageBody,- WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,+ 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,};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.rsindex 931f9fc1..03e2f913 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -58,6 +58,15 @@ pub struct AutoImproveCandidateSession {pub ended_at: i64,}+/// Open session selected for manual finalization.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct OpenSession {+ /// Session id.+ pub session_id: SessionId,+ /// Captured session cwd, if available.+ pub cwd: Option<String>,+}+/// 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@@ -1013,6 +1022,83 @@ impl ReaderPool {.await}+ /// Return open sessions matching one scoped project and agent.+ ///+ /// Results are newest-first so callers can default to finalizing only the+ /// latest open session while offering an explicit all-sessions mode.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn open_sessions_for_scope_agent(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ agent_kind: AgentKind,+ limit: Option<usize>,+ ) -> StoreResult<Vec<OpenSession>> {+ let agent = agent_kind.as_str().to_string();+ self.with_conn(move |conn| {+ let limit_clause = limit.map_or(String::new(), |n| format!(" LIMIT {}", n.max(1)));+ let sql = format!(+ "SELECT id, cwd FROM sessions \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND agent_kind = ?3 AND ended_at IS NULL \+ ORDER BY started_at DESC, id DESC{limit_clause}"+ );+ let mut stmt = conn.prepare_cached(&sql)?;+ let rows = stmt.query_map(+ params![workspace_id.as_bytes(), project_id.as_bytes(), agent],+ |row| {+ let id_bytes: Vec<u8> = row.get(0)?;+ let cwd: Option<String> = row.get(1)?;+ Ok((id_bytes, cwd))+ },+ )?;+ let mut out = Vec::new();+ for row in rows {+ let (id_bytes, cwd) = row?;+ out.push(OpenSession {+ session_id: SessionId::from_slice(&id_bytes)?,+ cwd,+ });+ }+ Ok(out)+ })+ .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.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn session_is_open_for_scope_agent(+ &self,+ session_id: SessionId,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ agent_kind: AgentKind,+ ) -> StoreResult<bool> {+ 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,+ ],+ |row| row.get(0),+ )?;+ Ok(count > 0)+ })+ .await+ }+/// Return completed sessions eligible for scheduled auto-improvement.////// The scheduler uses a persisted first-run watermark so an upgrade with andiff --git a/docs/install.md b/docs/install.mdindex d1ed9a80..5ae11d87 100644--- a/docs/install.md+++ b/docs/install.md@@ -515,6 +515,16 @@ docker run --rm akitaonrails/ai-memory:latest \--auth-token "$TOKEN"```+Codex still does not expose a reliable true session-end hook. Its `Stop` hook is+captured as a turn/stop observation only; ai-memory does **not** treat it as+SessionEnd. When you need the final session summary, handoff, and+auto-improvement eligibility for the current project, run:++```bash+ai-memory finalize-session+# add --all to close every matching open Codex session in this workspace/project+```+### OpenCode```bashdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 2927ff30..3c14e21f 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -553,7 +553,7 @@ that *starts* the next one - to play nicely with ai-memory:| Side | What's needed | Covered by ||---|---|---|-| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Cursor, Gemini CLI, Grok Build CLI, OpenClaw, OpenCode, and OMP. Codex and Antigravity CLI have no true session-end event in the current integration, so ask them to call `memory_handoff_begin` before quitting when you need a handoff. |+| **Ending side** | The agent must create a handoff, either through a true session-end hook, the supported Codex manual finalizer, or by calling `memory_handoff_begin`. | Built-in automatically for Claude Code, Cursor, Gemini CLI, Grok Build CLI, OpenClaw, OpenCode, and OMP. Codex has no reliable true session-end event, so run `ai-memory finalize-session` when you need the final summary/handoff/auto-improve eligibility. Antigravity CLI has no true session-end event in the current integration, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. || **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. Grok is explicitly excluded because it ignores SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |OpenCode uses its official `session.deleted` plugin event for true session-end@@ -562,6 +562,12 @@ still-active sessions from `dispose` during normal plugin teardown; abruptprocess exits can still lose that fallback, so `session.deleted` remains theprimary close path.+Codex `Stop` is not a session end. The Codex hook install intentionally omits+`SessionEnd`; `ai-memory finalize-session` finds the latest open Codex session+for the current workspace/project and posts a synthetic `session-end` event+through the same server path as real hook clients. Use `--all` only when you+want to close every matching open Codex session in that scope.+So a typical mixed workflow looks like:- **Claude Code → Cursor.** Claude Code's `SessionEnd` creates thediff --git a/docs/research-karpathy-llm-wiki.md b/docs/research-karpathy-llm-wiki.mdindex b64337b4..f754ca72 100644--- a/docs/research-karpathy-llm-wiki.md+++ b/docs/research-karpathy-llm-wiki.md@@ -76,7 +76,7 @@ Translating Karpathy faithfully - a "Karpathy-style" backend looks very differen- **Ingest must be a *write fan-out*, an insert.** A new observation should *touch ~10–15 existing pages* - updating an entity page, a concept page, a decisions log, a gotchas page. This is the single biggest deviation from vector RAG, which only ever appends.- **`index.md` and `log.md` as first-class files.** The log is the audit trail and the consolidation trigger source. Use the prefix convention (`## [YYYY-MM-DD] action | title`) so it's grep-able.- **Retrieval is hierarchical, nearest-neighbor.** Read `index.md` → narrow to candidate pages → read them → optionally fall back to hybrid search (BM25 + vector, RRF-fused) for novel queries. The index *is* the synthesis; the embeddings are a backstop.-- **Consolidation is an explicit, scheduled MCP operation**, not a side-effect. `memory_consolidate` is invoked on session-end (Claude Code's stop hook, Codex's session-end), on compaction events, or on a timer. It is LLM-driven (needs a provider key); if absent, it runs no-op as agentmemory does.+- **Consolidation is an explicit, scheduled MCP operation**, not a side-effect. `memory_consolidate` is invoked on true session-end hooks where the client exposes them, on Codex's manual `ai-memory finalize-session` flow, on compaction events, or on a timer. It is LLM-driven (needs a provider key); if absent, it runs no-op as agentmemory does.- **Cross-agent shared state.** Because the wiki is plain text, Claude Code, Codex, and OpenCode all read/write the *same* artifact. The MCP server is the gatekeeper; the markdown is the contract. No vendor lock.- **Coding-specific page types**: library gotchas, architectural decisions (ADR-style), failed approaches, repo conventions, environment quirks. Karpathy's example domains were personal/research; for coding agents the high-value pages are *failure modes* and *decisions*, because those are exactly what gets dropped on context compaction.