Skip to content

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

Rust

fix: keep managed utility runs sessionless

AkitaOnRails382291ed80ad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a56b290c..8a9eb505 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
sessions from contaminating later cross-harness switches.
### Fixed
+- Managed utility invocations such as `ai-memory run codex --version` no longer
+ discover and import a different process's recently updated native session.
+ Passthrough commands also do not fetch or acknowledge managed startup context.
- Managed runs now verify the host harness executable before opening a server
lease and report how to refresh a stale Docker wrapper. The wrapper path is
regression-tested to preserve a remote `AI_MEMORY_SERVER_URL`, auth, and the
diff --git a/README.md b/README.md
index 0d293066..697d640e 100644
--- a/README.md
+++ b/README.md
@@ -132,6 +132,27 @@ priors are at the [bottom](#influences-and-prior-art).
## Use cases
+- **"Quit Claude Code and continue the same work in Codex."** Use the optional
+ managed launcher when you want native session resume plus the portable visible
+ history, not only a summary handoff:
+
+ ```bash
+ cd /path/to/project
+ ai-memory run claude
+
+ # Quit Claude Code, then continue the same workstream in Codex.
+ ai-memory run codex --yolo
+
+ # Later, omit the name to resume the newest usable managed session here.
+ ai-memory run
+ ```
+
+ The first explicit run can offer an existing session from this exact checkout
+ or start a new one. Switching harnesses starts or resumes the native session
+ linked to the shared workstream, so an obsolete local session cannot replace
+ newer cross-harness history. Managed mode currently covers Claude Code,
+ Codex, OpenCode, Pi, Crush, and OMP; direct harness launches remain unchanged.
+ See [Managed cross-harness workstreams](docs/managed-workstreams.md).
- **"Quit at 4 PM, pick up at 9 AM in a different agent."** The
classic. SessionStart hook in the next supported hook client prepends a
typed handoff with open questions, next steps, and a session summary. Grok
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 62751b44..d238df97 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -12,9 +12,9 @@ use ai_memory_core::{
PrepareManagedRunResponse,
};
use ai_memory_workstream::{
- ExportedTranscript, ManagedHarness, NativeSessionCandidate, allows_native_session_adoption,
- apply_yolo, build_launch_plan, discover_native_session, export_transcript, inspect_repository,
- list_native_sessions, wait_for_transcript_flush,
+ ExportedTranscript, LaunchMode, LaunchPlan, ManagedHarness, NativeSessionCandidate,
+ allows_native_session_adoption, apply_yolo, build_launch_plan, discover_native_session,
+ export_transcript, inspect_repository, list_native_sessions, wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -195,7 +195,9 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
if args.yolo || trailing_yolo {
apply_yolo(harness, &mut plan.args);
}
- if let Some(native_session_id) = &plan.expected_session_id {
+ if plan.mode == LaunchMode::Session
+ && let Some(native_session_id) = &plan.expected_session_id
+ {
post_json_no_content(
&endpoint,
&format!("{run_path}/link"),
@@ -207,7 +209,7 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
.context("linking the managed native session; the agent was not started")?;
}
- let crush_context = if harness == ManagedHarness::Crush {
+ let crush_context = if harness == ManagedHarness::Crush && plan.mode == LaunchMode::Session {
prepare_crush_context(&endpoint, &run_path, &home).await?
} else {
None
@@ -281,44 +283,41 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
};
let exit_code = status.code().unwrap_or(1);
- let server_status = get_json::<ManagedRunStatus>(&endpoint, &run_path, &[])
- .await
- .ok();
- let discovered_session = if plan.expected_session_id.is_none() {
- discover_native_session(
- harness,
- &home,
- &repository.cwd,
- plan.session_dir.as_deref(),
- started_at,
- )
- .await?
- } else {
- None
- };
- let native_session_id = plan
- .expected_session_id
- .clone()
- .or(discovered_session)
- .or_else(|| {
- server_status
- .as_ref()
- .and_then(|status| status.native_session_id.clone())
- });
- let source_cursor = if native_session_id.as_deref() == prepared.native_session_id.as_deref() {
- prepared.source_cursor.as_deref()
+ let server_status = if plan.mode == LaunchMode::Session {
+ get_json::<ManagedRunStatus>(&endpoint, &run_path, &[])
+ .await
+ .ok()
} else {
None
};
- let transcript = export_after_flush(
+ let native_session_id = resolve_native_session_after_run(
+ &plan,
harness,
&home,
&repository.cwd,
- plan.session_dir.as_deref(),
- native_session_id.as_deref(),
- source_cursor,
+ started_at,
+ server_status.as_ref(),
)
- .await;
+ .await?;
+ let transcript = if plan.mode == LaunchMode::Session {
+ let source_cursor = if native_session_id.as_deref() == prepared.native_session_id.as_deref()
+ {
+ prepared.source_cursor.as_deref()
+ } else {
+ None
+ };
+ export_after_flush(
+ harness,
+ &home,
+ &repository.cwd,
+ plan.session_dir.as_deref(),
+ native_session_id.as_deref(),
+ source_cursor,
+ )
+ .await
+ } else {
+ ExportedTranscript::default()
+ };
let checkpoint = inspect_repository(&repository.cwd)
.map(|identity| identity.checkpoint)
.unwrap_or(repository.checkpoint);
@@ -331,7 +330,8 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
)
.await?;
- if prepared.sync_through > prepared.sync_after
+ if plan.mode == LaunchMode::Session
+ && prepared.sync_through > prepared.sync_after
&& !server_status.is_some_and(|status| status.context_delivered)
{
eprintln!(
@@ -345,6 +345,26 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {
Ok(exit_code)
}
+async fn resolve_native_session_after_run(
+ plan: &LaunchPlan,
+ harness: ManagedHarness,
+ home: &Path,
+ cwd: &Path,
+ started_at: SystemTime,
+ server_status: Option<&ManagedRunStatus>,
+) -> Result<Option<String>> {
+ if plan.mode == LaunchMode::Passthrough {
+ return Ok(None);
+ }
+ if let Some(native_session_id) = &plan.expected_session_id {
+ return Ok(Some(native_session_id.clone()));
+ }
+ let discovered =
+ discover_native_session(harness, home, cwd, plan.session_dir.as_deref(), started_at)
+ .await?;
+ Ok(discovered.or_else(|| server_status.and_then(|status| status.native_session_id.clone())))
+}
+
async fn list_auto_sessions(home: &Path, cwd: &Path) -> Result<Vec<AutoSessionCandidate>> {
let mut found = Vec::new();
let mut failures = Vec::new();
@@ -1022,6 +1042,65 @@ mod tests {
assert_eq!(args, ["resume", "native-id"].map(OsString::from));
}
+ #[tokio::test]
+ async fn utility_launch_does_not_adopt_a_recent_unrelated_session() {
+ let temp = tempfile::tempdir().unwrap();
+ let cwd = temp.path().join("repo");
+ let session_root = temp.path().join(".codex/sessions/2026/01/01");
+ std::fs::create_dir_all(&cwd).unwrap();
+ std::fs::create_dir_all(&session_root).unwrap();
+ let started_at = SystemTime::now();
+ std::fs::write(
+ session_root.join("rollout-current.jsonl"),
+ format!(
+ "{}\n",
+ serde_json::json!({
+ "type": "session_meta",
+ "payload": {"id": "unrelated-current", "cwd": cwd}
+ })
+ ),
+ )
+ .unwrap();
+
+ let utility = build_launch_plan(
+ ManagedHarness::Codex,
+ None,
+ vec![OsString::from("--version")],
+ None,
+ )
+ .unwrap();
+ assert_eq!(utility.mode, LaunchMode::Passthrough);
+ assert!(
+ resolve_native_session_after_run(
+ &utility,
+ ManagedHarness::Codex,
+ temp.path(),
+ &cwd,
+ started_at,
+ None,
+ )
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ let session = build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();
+ assert_eq!(
+ resolve_native_session_after_run(
+ &session,
+ ManagedHarness::Codex,
+ temp.path(),
+ &cwd,
+ started_at,
+ None,
+ )
+ .await
+ .unwrap()
+ .as_deref(),
+ Some("unrelated-current")
+ );
+ }
+
#[test]
fn crush_context_config_preserves_user_settings_and_adds_packet() {
let source_dir = tempfile::tempdir().unwrap();
diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.sh
index 406c47fb..1fceee21 100755
--- a/scripts/managed-workstream-acceptance.sh
+++ b/scripts/managed-workstream-acceptance.sh
@@ -112,6 +112,28 @@ EOF
chmod +x "$FAKE"
printf 'running deterministic wrapper edge checks\n'
+
+# Utility invocations must not discover and import another process's recent
+# session merely because it is active in the same checkout.
+UTILITY_CODEX_HOME="$CONFIG/utility-codex"
+mkdir -p "$UTILITY_CODEX_HOME/sessions/2026/01/01"
+printf '%s\n%s\n' \
+ "{\"type\":\"session_meta\",\"payload\":{\"id\":\"utility-unrelated\",\"cwd\":\"$REPO\"}}" \
+ '{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"must not import"}]}}' \
+ >"$UTILITY_CODEX_HOME/sessions/2026/01/01/rollout-utility.jsonl"
+(
+ cd "$REPO"
+ CODEX_HOME="$UTILITY_CODEX_HOME" \
+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \
+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/utility-argv.log" \
+ "$BIN" --data-dir "$DATA" run --new edge-utility --executable "$FAKE" \
+ codex --version >"$LOGS/edge-utility.log" 2>&1
+)
+diff -u <(printf '%s\n' --version) "$TMP/utility-argv.log"
+# The repository checkpoint is still recorded; the unrelated user message is
+# not. A buggy post-exit discovery path reports two imported events here.
+grep -q "workstream 'edge-utility' saved 1 new event(s)" "$LOGS/edge-utility.log"
+
(
cd "$REPO"
AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \