Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge branch 'main' into release/2.5
AkitaOnRails8f55486e5fb9
diff --cc CHANGELOG.mdindex 0f416f19,4bfd236d..004741f5--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -8,95 -8,15 +8,104 @@@ and this project adheres to [Semantic V## [Unreleased]### Added+- Native `ai-memory upgrade` for GitHub-release installs (Linux/macOS+ tarballs and Windows x86_64 zip): downloads the matching release archive,+ verifies the `.sha256` sidecar, replaces the on-disk binary (and a sibling+ `hooks/` tree when present), then re-runs `install-hooks --apply` for staged+ agents. Windows uses rename-aside self-replace (running `.exe` → `.old`,+ promote `.new`) because the mapped image cannot be overwritten in place.+ Refuses package-managed paths (Homebrew/AUR/`/usr`), containers, and+ unwritable prefixes; the Docker wrapper's `upgrade` path is unchanged. Pin+ with `--version` / force a re-download with `--force`. Optional+ `AI_MEMORY_RELEASE_BASE_URL` / `release_base_url` overrides the Releases+ base for mirrors and hermetic tests (loaded via `Config`, not ad-hoc env).+ Downloads refuse bodies over 128 MiB (Content-Length and streamed cap).+ (#801, #802)+- `ai-memory run` accepts a repeatable `--env KEY=VALUE` and an `--env-file+ <path>` (blank lines and `#` comments skipped) to pass extra environment+ into the spawned harness — e.g. a per-account `CLAUDE_CONFIG_DIR` for+ callers who previously had to wrap the launch in `env KEY=VAL harness`.+ Both flags are wrapper-owned like `--yolo`/`--executable` and must precede+ the harness name; a `--env` entry overrides a same-key `--env-file` line.+ The resolved environment reaches both the spawned process and ai-memory's+ own native-session resolution, so the two agree on where a+ `CLAUDE_CONFIG_DIR`-style override points the session store. See+ `docs/managed-workstreams.md`. (#820)+- `contradiction_band_min` / `contradiction_band_max` config keys (env:+ `AI_MEMORY_CONTRADICTION_BAND_MIN` / `AI_MEMORY_CONTRADICTION_BAND_MAX`)+ make `memory_lint`'s A5 zero-LLM contradiction-detection cosine-similarity+ band configurable, defaulting to the historical fixed `0.4`–`0.75`. The+ band is a fixed absolute cosine value, but background similarity is+ corpus-dependent: on a single-language or single-domain store, unrelated+ pages already sit above the general-purpose floor, so the default band+ measures domain proximity more than conflict and produces noisy findings.+ Raising `contradiction_band_min` trims that noise. Rejected at config load+ unless `0.0 <= contradiction_band_min < contradiction_band_max <= 1.0` and+ both are finite. (#853)+- Fedora users can install prebuilt x86_64 and aarch64 RPMs from GitHub+ Releases, with the existing native systemd service assets. (#858)+- `embedding_query_prefix` / `embedding_document_prefix` config keys (env:+ `AI_MEMORY_EMBEDDING_QUERY_PREFIX` / `AI_MEMORY_EMBEDDING_DOCUMENT_PREFIX`)+ for the `openai` and `openai-compat` embedders: an optional string+ prepended to query / document text before the existing truncation, so+ truncation still bounds the whole input. Asymmetric embedding models need+ a query-side instruction their publisher specifies; the OpenAI-compatible+ `/v1/embeddings` wire format has no field for it.+ `nvidia/Nemotron-3-Embed-1B-BF16` and base E5 models use a simple+ `"query: "` / `"passage: "` pair; instruction-tuned E5 variants and+ Qwen3-Embedding instead need a task-instruction string on the query side+ only (documents stay plain). Empty by default — no behaviour change when+ unset, and not trimmed (nor is a present-but-empty env-var override, which+ now clears a `config.toml` value), so a publisher's trailing space is+ preserved. A non-empty `embedding_document_prefix` is folded into the+ stored embedding identity (`Embedder::model_identity`), so a document+ prefix change makes retrieval, backfill, and cleanup treat existing pages+ as stale and re-embed them automatically — an empty prefix keeps the+ pre-existing identity, so upgrading installs need no migration, and a+ query-only prefix change never needs a rebuild. See+ `docs/llm-providers.md`. (#859)+- Added the optional `ai-memory-relay` companion for external lifecycle events.+ It queues events locally and sends ordered batches through the public hook API,+ using stable event identities for retries. The package has its own workspace+ and does not change the server's capture or storage defaults. (#823)+- `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)+- Builtin `/web` login and change-password pages for human password sessions:+ unauthenticated browser GETs to the wiki redirect to `{web_slug}/login`+ (not bare JSON 401), forms call existing `POST /auth/login` /+ `/auth/password` / `/auth/logout`, and `--web-ui-dir` custom SPAs stay+ unchanged. (#811)+ - `[consolidation] input_token_safety_margin` (float, default `0.8`, validated+ to `(0.0, 1.0]`) scales the approximate char-count input budget. The+ `max_input_tokens` budget uses a flat chars-per-token heuristic that+ under-budgets denser corpora — pt-BR text and source code tokenize at fewer+ chars per token than English and could overshoot a provider's real input+ limit by ~40%. The default tightens the common case modestly while leaving+ such corpora headroom; lower it further for a mostly non-English or code+ corpus. `max_input_tokens` is now documented as an approximate heuristic in+ the config reference. (#884)- `docs/jev-reranker-adapter.md` documents a stdlib-only adapter(`docs/examples/jev-reranker-adapter/jev_rerank_shim.py`) that serves the`AI_MEMORY_RERANKER=llm` request leg from a Jev `/v1/systemone` judge@@@ -107,79 -27,81 +116,152 @@@mean latency instead of 20.2 s — in that run the hosted mean sat on theserver's 20 s completion timeout, which made the reranker stall everyquery before falling back. (#873)+- MCP tool calls from OpenCode 2 (2.0.4+) are routed by the native session id+ the client sends in `params._meta["ai.opencode/sessionID"]`, ahead of the+ `Mcp-Session-Id` transport header, which OpenCode shares across every+ session in a directory. Concurrent OpenCode sessions in different projects+ no longer read each other's active project; explicit `workspace`/`project`+ arguments still win and `X-Memory-Actor-Session-Id` keeps precedence. (#864)+- OpenCode 2 turn checkpoints: every completed root turn+ (`session.execution.succeeded`, `.failed` or `.interrupted`, OpenCode+ 2.0.10+) now refreshes `sessions/<id>.md` and the session's automatic+ handoff without ending the native session, because OpenCode 2's shared+ service outlives the CLI and closing a terminal is not a session end. The+ checkpoint is deterministic (no LLM call), is written in the session's own+ scope, keeps one open baton per live session (refreshed in place, audited as+ `refresh_handoff`), and never touches a session that already ended. Child+ sessions neither claim startup context nor publish batons. (#865)+- `install-hooks --agent opencode2 --capture-assistant` extends the+ assistant/Stop capture double opt-in to OpenCode 2: the plugin forwards the+ last completed assistant text through the native hook's sanitizer before it+ reaches the spool or the wire. The captured excerpt continues the work in+ the next session's automatic handoff; it is not rendered into the+ git-tracked session page. (#865)++### 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+ (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 for+ agents that reuse their session id across a restart (Grok); for every other+ agent an ended session stays final, so a lifecycle-only receiver still cannot+ reclaim after it released and ended. The reopen also only happens 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)+- The generated OpenCode 2 plugin binds to the OpenCode 2.0.10+ event and hook+ API (`session.execution.*`, `session.text.ended`, `session.moved`, the+ `context` hook). Startup context is claimed once per root session and+ retained on every later model request; content-only tool results are+ captured; each location instance owns its own queue, spool state and+ cleanup; an explicit `session.moved` rebinds the live session to its new+ directory so its later end lands there. Checked against OpenCode 2.0.14. (#865)+ ### Changed+ - Quieted the default server log: the reconciliation-pass summary that fired+ every 30 s regardless of activity dropped from `info` to `debug`, and the+ default log filter now pins the external `rmcp` MCP SDK to `warn` (its+ per-request lifecycle logging at `info` was the other half of a near-empty+ server's log). Both are restorable through `log_level` (e.g.+ `"info,rmcp=info"` or `"debug"`) or `RUST_LOG`; the `tracing_appender=warn`+ feedback-loop guard stays non-overridable. (#894)+### Fixed+- Native `ai-memory upgrade` no longer refuses every Linux install by probing+ the running executable for write (Linux `ETXTBSY`); it only requires the+ parent directory to be writable for rename-based replace. (#802)+- Native `ai-memory upgrade` accepts release archives whose entries are+ `./`-prefixed (`tar -C … -czf … .` as in `release.yml`), instead of+ rejecting `Component::CurDir` as an unsafe path. (#802)+- Native `ai-memory upgrade` treats Linuxbrew (`/home/linuxbrew/.linuxbrew/`)+ as package-managed and refuses self-replace there. (#802)+- Native `ai-memory upgrade` container refusal now uses the shared+ `running_in_container` helper (`AI_MEMORY_IN_CONTAINER`, `/.dockerenv`,+ `/run/.containerenv` / Podman), matching staged-hooks detection. (#802)+- Parallel OpenCode 2 sessions in one directory no longer receive each+ other's context. Each completed turn's checkpoint retired the automatic+ handoffs of every other live session there, and the next session to start+ was handed the handoff of a session still in use (mid-turn, or seconds after+ its last turn). A checkpoint now spares other live sessions' handoffs; a+ starting session receives a live session's handoff only once that session+ has captured nothing for ten minutes, re-checked inside the claim; and the+ claim retires older handoffs of quiet sessions but not of one in use.+ (#883)+- `memory_query`'s vector stream called the generic `Embedder::embed`+ instead of `embed_query` on the configured embedder, so a+ query/document-asymmetric embedder (Google's task-typed embeddings, or+ the new query/document prefixes above) embedded the search query on the+ document side instead of the query side. Indexed writes are unchanged;+ only the query-side helper moves onto the query task. (#859, #861)+ - A manual `memory_consolidate` now reconciles the session's durable+ consolidation job row. The MCP handler wrote the page directly through the+ consolidator without touching `session_consolidation_jobs`, so a session+ whose automatic SessionEnd job had reached the terminal `failed` state (that+ the worker never re-claims) kept showing `failed` even though the operator+ had just consolidated it. After a successful, non-dry consolidate the handler+ flips a `failed`/`pending`/`superseded` row for the session to `completed`; a+ live `running` lease is never touched, so a concurrent automatic worker+ attempt is left to settle its own row. (#890)+ - Tool-family labels no longer leak into automatic handoffs and session-page+ titles, and the file-activity handoff warning fires again. Every closed-tool+ agent stores a call's title as `tool file` / `tool non-file` / … (a partition+ of the calls, not a tool name); these were surfacing verbatim as `Tools used:+ tool file, tool non-file` in handoffs and, for a session whose only non-prompt+ observation was such a call, as the page title. The same spelling meant the+ "session ended without a normal stop while working with files" heuristic —+ which only matched the bare `file` spelling of the minority reserved-protocol+ path — never fired for a real session. A shared recognizer now maps both+ spellings, drops the labels from the handoff tool list and the title fallback,+ and drives the file-activity warning from either. (#895)+ - Generated rule slugs (`_rules/<slug>.md`) now fold Latin diacritics to ASCII+ instead of turning each accented letter into a hyphen: `estável` slugs as+ `estavel` (was `est-vel`) and `retenção` as `retencao` (was `reten-o`). Long+ titles are also truncated at a word boundary (the last hyphen inside the+ 60-char budget) rather than mid-word. Uses the icu_normalizer NFD+ decomposition ai-memory-core already depends on; no new dependency. (#886)+ - Multi-page consolidation now stores page paths with a `.md` extension.+ The LLM returns a bare path for a non-rule page (`decisions/smart-model-luna`),+ and the shared path sanitizer passed it through verbatim, so the page landed+ extensionless and read back as a non-portable wiki path. The sanitizer now+ appends `.md` to the filename component when it is missing (idempotent,+ case-insensitive), fixing the non-rule consolidation, bootstrap, and+ auto-improve front doors at once. (#885)+ - `ai-memory run`'s auto-wire no longer overwrites an installed session-aware+ Claude Code MCP bridge with the static HTTP registration. The auto-wire+ sentinel is keyed by client version, so the MCP step re-ran on every upgrade+ and replaced the `ai-memory` entry wholesale; a user who had run `install-mcp+ --client claude-code --session-aware` lost the bridge on the next `ai-memory+ run` after an upgrade, silently disabling `[auto_scope] per_session` for their+ MCP calls. Auto-wire now detects an existing session-aware bridge and keeps+ it. (#888)+ - After a managed launch, `ai-memory run` imported the newest native session+ in the checkout even when a hook in the launched harness had linked the+ run's own session, so a concurrent launch in the same checkout could hand it+ another transcript. The server now records when a session is linked during+ a run (schema migration V67, adding `managed_runs.native_session_linked_at`)+ and reports it in the run status, and the launcher imports that session+ when this checkout's store holds it (a process the child starts inherits+ the run id; OpenCode is checked by the session's recorded directory). An+ older server reports no link and keeps the previous behavior. (#820)+ - On Windows, OpenCode 1 and 2 sessions are found again from their checkout:+ OpenCode records a session's directory with forward slashes+ (`C:/Users/me/repo`), so matching only the backslash checkout path found+ none. `ai-memory doctor` reported `0 local` for OpenCode while it captured+ sessions there, and `ai-memory run` / `show` could neither discover nor list+ a native OpenCode session to resume. (#882)+ - Grok Build CLI hooks capture on Windows again. Grok evaluates+ `~/.grok/hooks/*.json` commands with PowerShell, as Codex does (#515), so+ the double-quoted executable path in command position parsed as a string+ expression and every hook exited 1 with a ParserError: sessions ran with+ the hook installed and nothing was captured. The Windows command now+ carries PowerShell's `&` call operator for Grok too; re-run+ `ai-memory install-hooks --agent grok --apply` to rewrite an existing+ install. (#887)- The Linux/macOS Docker wrapper now keeps its native host client in`${XDG_DATA_HOME:-~/.local/share}/ai-memory/native-runner` instead of`~/.cache/ai-memory/native-runner`. `ai-memory run` auto-wires hooks whose@@@ -311,15 -241,12 +393,21 @@@event: their `git` lookups set `windowsHide`. The repo-root project lookupbehind those spawns is memoized per cwd instead of running two synchronous`git` processes on every event. (#863)+- A `SessionEnd` whose resolved scope drifted from its session (a+ `.ai-memory.toml` appeared under the running session) was refused as a+ foreign-scope end and stranded the session open forever. It now ends the+ session when owner and agent match and the event comes from the session's+ own (normalized) cwd; a different cwd, operator or agent is still refused. (#865)+- Generated TypeScript integrations no longer overwrite each other's spooled+ events written in the same millisecond, and a host that tears its capture+ state down cancels still-pending deliveries after the drain budget instead+ of waiting out each request's timeout. (#865)+ - Shell hooks on macOS no longer corrupt non-ASCII characters in the query+ string. `/bin/sh` there is bash 3.2, which sign-extends bytes >= 0x80, so+ `ai_memory_url_encode` sent `é` as `%FFFFFFFFFFFFFFC3%FFFFFFFFFFFFFFA9`+ instead of `%C3%A9`. An accented cwd reached the server as a different+ path, and Cursor events and the session-start handoff lookup both use the+ query `cwd`. (#877)## [2.4.0] - 2026-09-21diff --cc crates/ai-memory-cli/src/commands/run.rsindex 34cd1b9c,360ecd87..7e53ceca--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@@ -13,11 -13,11 +13,12 @@@ use ai_memory_core::};use ai_memory_workstream::{ExportedTranscript, LaunchMode, LaunchPlan, ManagedHarness, NativeSessionCandidate,- allows_native_session_adoption, apply_yolo, build_launch_plan, discover_native_session,- export_transcript, has_native_session_selector, inspect_repository, kiro_explicit_session_id,- kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,- kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,- native_session_exists, native_session_in_checkout, wait_for_transcript_flush,+ allows_native_session_adoption, apply_yolo, build_launch_plan, build_launch_plan_with_env,+ discover_native_session, export_transcript, has_native_session_selector, inspect_repository,+ kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,+ kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,- list_native_sessions, native_session_exists, wait_for_transcript_flush,++ list_native_sessions, native_session_exists, native_session_in_checkout,++ wait_for_transcript_flush,};use anyhow::{Context as _, Result, anyhow};use tokio::process::Command;diff --cc crates/ai-memory-store/tests/suite/multi_session.rsindex 05c35306,87a9fddb..3e4f798b--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@@ -17,11 -17,10 +17,11 @@@//! core capability rather than a detail.use ai_memory_core::{- ActorContext, AgentKind, HandoffAcceptance, IdentityKey, NewHandoff, NewPage, NewSession,- NewUser, OwnerFilter, PagePath, ProjectId, SessionId, Tier, UserRole, WorkspaceId, owner_stamp,+ ActorContext, AgentKind, HandoffAcceptance, HandoffState, IdentityKey, NewHandoff, NewPage,+ NewSession, NewUser, OwnerFilter, PagePath, ProjectId, SessionId, Tier, UserRole, WorkspaceId,+ owner_stamp,};- use ai_memory_store::Store;+ use ai_memory_store::{PrepareWorkstreamRun, Store, WorkstreamSelection};fn operator(name: &str) -> String {IdentityKey::User(name.into()).storage_key()@@@ -428,307 -427,70 +428,375 @@@ async fn an_owned_handoff_stays_with_it);}+/// 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"+ );+}++/// Parallel live sessions in one directory each own a turn-checkpoint baton.+/// One session's checkpoint, and a receiver claiming it, must leave the other+/// live session's baton open: before this held, every completed turn retired+/// the other sessions' batons and the survivor went to whoever started next.+#[tokio::test]+async fn parallel_live_sessions_keep_their_own_checkpoint_batons() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let baton = |session: SessionId, summary: &str| NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(session),+ from_agent: AgentKind::OpenCode,+ to_agent: None,+ cwd: Some("/repo".into()),+ summary: summary.into(),+ open_questions: Vec::new(),+ next_steps: Vec::new(),+ files_touched: Vec::new(),+ owner_user: None,+ };+ let alpha = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ let beta = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ let alpha_baton = store+ .writer+ .checkpoint_session_handoff(baton(alpha, "alpha"))+ .await+ .unwrap()+ .unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let beta_baton = store+ .writer+ .checkpoint_session_handoff(baton(beta, "beta"))+ .await+ .unwrap()+ .unwrap();+ let state = |id| {+ let reader = store.reader.clone();+ async move {+ reader+ .handoff_by_id(id)+ .await+ .unwrap()+ .unwrap()+ .lifecycle+ .state+ }+ };+ assert_eq!(state(alpha_baton).await, HandoffState::Open);++ let receiver = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ let claimed = store+ .writer+ .accept_handoff(HandoffAcceptance {+ handoff_id: beta_baton,+ workspace_id: ws,+ project_id: proj,+ accepting_agent: AgentKind::OpenCode,+ accepting_session: Some(receiver),+ accepting_user: None,+ owner_filter: OwnerFilter::Any,+ receiving_cwd: Some("/repo".into()),+ })+ .await+ .unwrap();+ assert!(claimed);+ assert_eq!(+ state(alpha_baton).await,+ HandoffState::Open,+ "claiming one live session's baton must not sweep another's"+ );++ // Once alpha ends, its baton is an ordinary SessionEnd baton again and the+ // same-cwd supersession applies to it.+ store.writer.end_session(alpha, None).await.unwrap();+ let gamma = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ store+ .writer+ .checkpoint_session_handoff(baton(gamma, "gamma"))+ .await+ .unwrap()+ .unwrap();+ assert_eq!(state(alpha_baton).await, HandoffState::Expired);+}++/// Automatic delivery re-checks the source inside the claim, and the claim's+/// sweep retires batons of quiet (abandoned) open sessions while sparing one+/// still in use. The selection runs on a reader before the writer claims, so+/// a source can resume in between; and OpenCode sessions that never end would+/// otherwise leave one open baton each, surfacing older conversations one by+/// one to later sessions.+#[tokio::test]+async fn startup_claim_rechecks_the_source_and_sweeps_only_quiet_open_batons() {+ use ai_memory_core::{NewObservation, ObservationKind, Sanitized, Sanitizer};++ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let mut batons = Vec::new();+ // Checkpoint order, oldest first: busy, abandoned, quiet.+ for summary in ["busy", "abandoned", "quiet"] {+ let session = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id: session,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: summary.into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ let id = store+ .writer+ .checkpoint_session_handoff(NewHandoff {+ workspace_id: ws,+ project_id: proj,+ from_session_id: Some(session),+ from_agent: AgentKind::OpenCode,+ to_agent: None,+ cwd: Some("/repo".into()),+ summary: summary.into(),+ open_questions: Vec::new(),+ next_steps: Vec::new(),+ files_touched: Vec::new(),+ owner_user: None,+ })+ .await+ .unwrap()+ .unwrap();+ batons.push((session, id));+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ }+ let [+ (_, busy),+ (abandoned_session, abandoned),+ (quiet_session, quiet),+ ] = batons[..]+ else {+ unreachable!()+ };+ // Only "busy" captured anything in the last hour.+ let hour_ago = (jiff::Timestamp::now() - jiff::SignedDuration::from_hours(1)).as_microsecond();+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();+ for session in [abandoned_session, quiet_session] {+ conn.execute(+ "UPDATE observations SET created_at = ?1 WHERE session_id = ?2",+ rusqlite::params![hour_ago, session.as_bytes()],+ )+ .unwrap();+ }+ drop(conn);+ let cutoff = jiff::Timestamp::now() - jiff::SignedDuration::from_mins(10);+ let claim = |handoff_id, receiver| HandoffAcceptance {+ handoff_id,+ workspace_id: ws,+ project_id: proj,+ accepting_agent: AgentKind::OpenCode,+ accepting_session: Some(receiver),+ accepting_user: None,+ owner_filter: OwnerFilter::Any,+ receiving_cwd: Some("/repo".into()),+ };+ let state = |id| {+ let reader = store.reader.clone();+ async move {+ reader+ .handoff_by_id(id)+ .await+ .unwrap()+ .unwrap()+ .lifecycle+ .state+ }+ };++ // Selected earlier, but its source is in use by the time of the claim.+ let receiver = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ let raced = store+ .writer+ .accept_startup_context(Some(claim(busy, receiver)), None, None, cutoff)+ .await+ .unwrap();+ assert!(!raced.handoff_accepted, "a source in use keeps its baton");+ assert_eq!(state(busy).await, HandoffState::Open);++ let receiver = open_session(&store, ws, proj, AgentKind::OpenCode).await;+ let delivered = store+ .writer+ .accept_startup_context(Some(claim(quiet, receiver)), None, None, cutoff)+ .await+ .unwrap();+ assert!(delivered.handoff_accepted);+ assert_eq!(+ state(abandoned).await,+ HandoffState::Expired,+ "an older baton of a quiet open session is superseded"+ );+ assert_eq!(+ state(busy).await,+ HandoffState::Open,+ "a session in use keeps its baton even when it is older"+ );+}+++ /// Two workstreams launched at once in one checkout each get a managed run.+ /// A session one run's child links marks that run only: the other run's+ /// status must neither report it nor count as linked, or its launcher would+ /// import the other launch's transcript.+ #[tokio::test]+ async fn a_session_linked_by_one_managed_run_is_not_another_runs() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let prepare = |name: &str| PrepareWorkstreamRun {+ workspace_id: ws,+ project_id: proj,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::New(name.into()),+ lease_owner: format!("launcher-{name}"),+ };+ let alpha = store+ .writer+ .prepare_workstream_run(prepare("alpha"))+ .await+ .unwrap();+ let beta = store+ .writer+ .prepare_workstream_run(prepare("beta"))+ .await+ .unwrap();+ assert_ne!(alpha.workstream_id, beta.workstream_id);+ let status = async |run| {+ let status = store.reader.managed_run_status(run).await.unwrap().unwrap();+ (status.native_session_id, status.native_session_linked)+ };++ assert!(+ store+ .writer+ .link_managed_run_session(beta.run_id, AgentKind::Codex, "native-beta")+ .await+ .unwrap()+ );+ assert_eq!(status(alpha.run_id).await, (None, false));+ assert_eq!(+ status(beta.run_id).await,+ (Some("native-beta".into()), true)+ );++ // Control: alpha's own link marks alpha, and leaves beta as it was.+ assert!(+ store+ .writer+ .link_managed_run_session(alpha.run_id, AgentKind::Codex, "native-alpha")+ .await+ .unwrap()+ );+ assert_eq!(+ status(alpha.run_id).await,+ (Some("native-alpha".into()), true)+ );+ assert_eq!(+ status(beta.run_id).await,+ (Some("native-beta".into()), true)+ );+ }