Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge branch 'pr-840' into release/2.5
AkitaOnRails25e92e26337a
diff --cc CHANGELOG.mdindex dd164839,f3418aed..3be92ccb--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,64 -7,13 +7,78 @@@ and this project adheres to [Semantic V## [Unreleased]+### Added+- `auto_improve.patchable_page_prefixes` makes the folders whose page bodies the+ reviewer reads configurable, defaulting to the historical `_rules/` and+ `procedures/`. Only those two folders' contents were ever sent; every other+ page reached the model as a single title line, so a project keeping its+ durable knowledge in `decisions/` or `gotchas/` — with no `_rules/` pages at+ all — sent no page bodies, and the reviewer re-proposed invariants that were+ already written down, at high confidence, indefinitely. Existing configs are+ unchanged. (#834)+- `ai-memory finalize-session --reopen --session-id <uuid>` re-finalizes a+ session that already ended, for agents without a true session-end event+ (Antigravity CLI, Kiro, ZCode, Pool) whose conversation continued after a+ first manual finalize: the discovery step now accepts `include_ended=true`+ on `GET /admin/open-sessions` for an exact session id (rejected without+ one, so reopening stays exact-id-only and never a bulk operation), and the+ server's normal session-end path re-runs over the new observations+ (updated summary page via supersession, new handoff, opt-in+ consolidation). Re-running with nothing new since the first end remains a+ harmless no-op. The default finalize behavior is unchanged: ended sessions+ stay invisible unless `--reopen` is passed. (#836)+- Added per-execution `AI_MEMORY_CAPTURE_OWNER` context for external lifecycle+ producers. Updated native hooks, script bundles and generated integrations+ suppress capture while preserving supported handoff delivery and MCP recall.+ Documented producer provenance and stable retries through the existing hook+ ingestion API, without changing its schema or standalone defaults. (#821)++ ### Changed-- Grok Build CLI shows a pending handoff, and an opted-in `[briefing]`,- as `PostToolUse` `additionalContext` on the first tool of a session.- `SessionStart` and `UserPromptSubmit` still do not accept the handoff:- Grok discards that stdout. A session that never calls a tool leaves the- handoff open for `memory_handoff_accept`. The note is clipped to 10,000- characters, which is Grok's own cap.++- Grok Build CLI shows a pending handoff, and an opted-in `[briefing]`, as++ `PostToolUse` `additionalContext` on the first tool of a session.++ `SessionStart` and `UserPromptSubmit` still do not accept the handoff (Grok++ discards that stdout); a session that never calls a tool leaves the handoff++ open for `memory_handoff_accept`. The note is clipped to 10,000 characters++ (Grok's own cap). Because Grok reuses one session id across a++ SessionEnd→restart, `memory_handoff_accept` now reopens an already-ended++ receiver session (clears `ended_at`) instead of rejecting it — but only after++ the exactly-once claim guard, so a session that already took a baton still++ cannot take another (the multi-session claim-once invariant is preserved).++ Delivery of this PostToolUse handoff is exempt from `AI_MEMORY_CAPTURE_OWNER`++ capture suppression, like the other context-delivery events. (#840)+++### Fixed+- `ai-memory serve` no longer leaked file descriptors from half-open HTTP+ connections until `EMFILE`, breaking the healthcheck (an unauthenticated+ availability/DoS). A hook or MCP client whose peer died without sending FIN+ (laptop sleep, a VPN/Tailscale flap, an abrupt kill) left its accepted+ socket `ESTABLISHED` forever, since the OS default has TCP keepalive off —+ each dead peer leaked one fd, exhausting the 1024-fd default in roughly 2-3+ days of normal churn. Accepted connections now get TCP keepalive via+ `socket2`, tunable with the new `tcp_keepalive_secs` config key (default+ 60s; `AI_MEMORY_TCP_KEEPALIVE_SECS=0` disables keepalive). This closes the+ half-open-socket half of the fd leak; the rmcp session-table half was+ already fixed in 2.4.0 by the rmcp 2.x bump. (#792)+- `ai-memory bootstrap` no longer returns a 500 when the LLM emits a page+ path containing a Windows-illegal character (e.g. a `:` copied verbatim+ from a conventional-commit subject like `build(sandbox): orchestrate`).+ Such a path passed the deliberately tolerant `PagePath::new` and only+ failed later at `ensure_portable` inside the atomic wiki write batch,+ which aborted every page in the run, not just the offending one. Bad+ paths are now sanitized (illegal characters replaced with `-`, directory+ shape preserved) before validation, so the run and its other pages+ survive; a path `ensure_portable` still rejects after sanitizing is+ skipped with a warning instead of failing the batch. (#847)+- The Windows release checksum (`ai-memory-windows-x86_64.zip.sha256`) is now+ written with a LF terminator instead of CRLF. `Out-File`'s Windows line+ ending made `sha256sum -c` fail with `No such file or directory` — the CR+ is read as part of the filename — on the WSL2 and Git Bash paths where that+ is the natural command, and placed a stray byte in the release body's+ checksum block, which concatenates every platform's file. The zip's smoke+ test now requires LF rather than tolerating either, so the format the+ release claims is the format it ships. (#838)++## [2.4.0] - 2026-09-21### Security- Bumped `rmcp` to 2.x (2.2.0), resolving three MCP transport advisories:diff --cc crates/ai-memory-cli/src/commands/hook.rsindex f559e120,53cd0e4c..25ec720e--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@@ -509,21 -557,6 +558,25 @@@ wher{let agent_kind = AgentKind::from_wire(&args.agent);let hook_event = HookEvent::parse(&args.event);+ // This is inherited execution context, like AI_MEMORY_RUN_ID, rather+ // than server configuration. Hooks deliberately bypass Config::load.+ let external_capture = env_lookup(CAPTURE_OWNER_ENV).is_some_and(|v| !v.trim().is_empty());+ let delivers_context = (hook_event == HookEvent::SessionStart+ && agent_kind.session_start_injects_handoff())- || (hook_event == HookEvent::UserPrompt && agent_kind.user_prompt_injects_handoff());++ || (hook_event == HookEvent::UserPrompt && agent_kind.user_prompt_injects_handoff())++ // Grok delivers the handoff on the first PostToolUse (its SessionStart /++ // UserPromptSubmit stdout is discarded); that path is context delivery++ // too, so external capture must not suppress it.++ || (hook_event == HookEvent::PostToolUse && agent_kind.post_tool_injects_handoff());+ if external_capture && !args.check_capture && !delivers_context {+ // Retiring the fallback session ID is lifecycle housekeeping, not+ // capture. Preserve it even when no event is enqueued.+ if agent_kind == AgentKind::Devin && hook_event == HookEvent::SessionEnd {+ clear_session_id(&resolve_data_dir(data_dir.as_deref()), agent_kind);+ }+ write_success_response(stdout, agent_kind, hook_event)?;+ return Ok(());+ }let (mut payload, mut json) = match parse_hook_payload(payload) {Ok(parsed) => parsed,Err(_) => {diff --cc crates/ai-memory-store/tests/suite/multi_session.rsindex fce7ff76,fce7ff76..36b4d8b8--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@@ -358,3 -358,3 +358,94 @@@ async fn an_owned_handoff_stays_with_itoperator("alice"));}++++/// Grok reuses one session id across a SessionEnd→restart, so++/// `accept_handoff` must reopen an already-ended receiver session instead of++/// rejecting it (#840) — but only *after* the exactly-once claim guard, so the++/// resurrection can never become a way to steal an already-taken baton.++#[tokio::test]++async fn accept_reopens_an_ended_receiver_session_but_keeps_claim_once() {++ let tmp = tempfile::tempdir().unwrap();++ let store = Store::open(tmp.path()).unwrap();++ let (ws, proj) = scope(&store).await;++++ let id = store++ .writer++ .insert_handoff(NewHandoff {++ workspace_id: ws,++ project_id: proj,++ from_agent: AgentKind::Grok,++ to_agent: None,++ from_session_id: None,++ summary: "resume after restart".into(),++ next_steps: Vec::new(),++ open_questions: Vec::new(),++ files_touched: Vec::new(),++ cwd: None,++ owner_user: None,++ })++ .await++ .unwrap();++++ let accept = |session: SessionId| HandoffAcceptance {++ handoff_id: id,++ workspace_id: ws,++ project_id: proj,++ accepting_agent: AgentKind::Grok,++ accepting_session: Some(session),++ accepting_user: None,++ owner_filter: OwnerFilter::Any,++ receiving_cwd: None,++ };++++ // The same Grok session id: opened, then ended (SessionEnd), then reused++ // when the conversation restarts and calls its first tool.++ let grok = open_session(&store, ws, proj, AgentKind::Grok).await;++ store.writer.end_session(grok, None).await.unwrap();++++ let claimed = store.writer.accept_handoff(accept(grok)).await.unwrap();++ assert!(++ claimed,++ "an ended session that reuses its id must be able to accept the handoff"++ );++++ // The receiver row was reopened (ended_at cleared), not left a corpse.++ let grok_bytes = grok.as_bytes().to_vec();++ let ended_at: Option<i64> = store++ .reader++ .with_conn(move |conn| {++ Ok(conn.query_row(++ "SELECT ended_at FROM sessions WHERE id = ?1",++ rusqlite::params![grok_bytes],++ |r| r.get(0),++ )?)++ })++ .await++ .unwrap();++ assert!(++ ended_at.is_none(),++ "accepting a handoff must reopen the ended receiver session"++ );++++ // Claim-once still holds: a *different* session cannot steal the baton the++ // reopened session already took, even though the loser is wide open.++ let loser = open_session(&store, ws, proj, AgentKind::Codex).await;++ let stolen = store++ .writer++ .accept_handoff(HandoffAcceptance {++ handoff_id: id,++ workspace_id: ws,++ project_id: proj,++ accepting_agent: AgentKind::Codex,++ accepting_session: Some(loser),++ accepting_user: None,++ owner_filter: OwnerFilter::Any,++ receiving_cwd: None,++ })++ .await++ .unwrap();++ assert!(++ !stolen,++ "the resurrection path must not let a second session steal an accepted baton"++ );++}