Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: improve managed workstream handoffs
AkitaOnRailsdc494a2086b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9b3b3145..a56b290c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- `ai-memory run` without a harness now selects among checkout-local Claude+ Code, Codex, OpenCode, Pi, and Crush sessions. Empty workstreams adopt the+ newest session automatically; established workstreams prefer their most+ recently linked available harness. A directory with no matching session+ exits with explicit start commands instead of creating an empty workstream.+- Managed workstreams now support Crush through its project-local read-only+ SQLite transcript and supported `options.global_context_paths` configuration.+ ai-memory never writes the original Crush config or session database; the+ launched Crush process retains normal ownership of its native session writes.+- Wrapper-owned `run --yolo` translates to each harness's native dangerous-mode+ option for Claude Code, Codex, OpenCode, Pi, and Crush.+- A managed-harness contribution protocol documents the native-session,+ read-only import, context-delivery, migration, privacy, and acceptance-test+ requirements for adding agents beyond the currently supported set.++### Changed+- The first interactive `ai-memory run` on an otherwise-empty workstream now+ offers recent native sessions recorded for the same checkout, with the newest+ as the default or an explicit fresh-session choice. Adoption is disabled for+ `--new`, explicit selectors, scripted/noninteractive launches, and any+ workstream already established by another harness, preventing obsolete local+ sessions from contaminating later cross-harness switches.++### Fixed+- 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+ host `PATH` without entering Docker, and now retains the `run` subcommand when+ it hands control to the native ai-memory client.+- Corrected stale project-move flags in the marker guide and documented the+ distinction between a server-side project rename and a physical checkout or+ native-session relocation.+## [1.16.0] - 2026-07-20### Addeddiff --git a/README.md b/README.mdindex b7256d4b..0d293066 100644--- a/README.md+++ b/README.md@@ -30,7 +30,8 @@| Gemini CLI | Supported | MCP config + lifecycle hooks. || Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. || Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. |-| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, and OMP. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). |+| Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |+| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, and OMP. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. || Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |@@ -65,7 +66,12 @@ priors are at the [bottom](#influences-and-prior-art).- **Opt-in managed workstreams.** `ai-memory run claude`, then `ai-memory runcodex --yolo`, transparently resumes one logical workstream with nativeper-harness sessions, a portable visible-event ledger, and full-ledger search.- Native arguments pass through unchanged; direct agent commands are unaffected.+ `ai-memory run` with no harness continues the newest usable Claude Code,+ Codex, OpenCode, Pi, or Crush session for this checkout. On first explicit use,+ an interactive launcher can adopt a previous session from the same checkout;+ later switches cannot select unrelated native history. Native arguments pass+ through unchanged except the wrapper-owned `--yolo`; direct commands are+ unaffected.- **Per-repository capture exclusions.** A nearest-marker `[capture]``ignore_paths` policy drops matching recognized file-tool events before theyreach the local spool or server. See [the capture policy reference](docs/marker-file.md#capture-exclusions).@@ -250,7 +256,7 @@ it. Adding a bearer token is a one-line change once you're ready toexpose the server on the LAN; see [Security](#security) below.```bash-# 1. Install the ai-memory CLI wrapper (a ~3 KB shell script that+# 1. Install the ai-memory CLI wrapper (a small shell script that# runs the binary inside docker with your $HOME mounted). This is# the only thing that needs to live on the host filesystem.mkdir -p ~/.local/bin@@ -319,6 +325,17 @@ The Docker wrapper also bridges thin-client commands such asloopback server. With the local Docker quick start above, no`AI_MEMORY_SERVER_URL` override is needed.+Managed workstreams are optional. They execute the harness on the host while+the server may remain local or remote:++```bash+ai-memory run claude+# later, continue the same workstream in another harness+ai-memory run codex --yolo+# omit the name to continue the newest usable local harness session+ai-memory run+```+To remove ai-memory later, run `ai-memory uninstall --apply` from thesame host environment. It removes ai-memory-owned config entries, instructionblocks, default-root managed skill files, and generated plugin files only after@@ -343,6 +360,12 @@ one matching entry.MCP/hooks. Explicit `--server-url` flags still work, but are no longerrequired when the env vars are set. Any non-loopback server should usebearer auth.+- **Managed-run wrapper:** `ai-memory run` must be intercepted by the current+ host wrapper so the native harness and its session store remain accessible.+ An old wrapper may pass `run` into Docker and fail with `No such file or+ directory` for `codex`, `claude`, or another host executable. Run+ `ai-memory upgrade` on the agent machine to refresh it. The host-native runner+ inherits `AI_MEMORY_SERVER_URL`, `AI_MEMORY_AUTH_TOKEN`, and the host `PATH`.- **Upgrades:** for Docker-wrapper installs, run `ai-memory upgrade` on eachagent machine. It refreshes the local wrapper, pulls the latest image, andre-stages hook scripts under `~/.local/share/ai-memory/hooks/<agent>/`.@@ -631,7 +654,8 @@ diagram, crate breakdown, schema notes, and invariants.|---|---|| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. || [`docs/usage.md`](docs/usage.md) | Handoffs, proactive memory queries, slim routing snippet + managed Agent Skills, migration from other memory tools, web UI, raw-wiki inspection, and rules-vs-facts workflow. |-| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, and OMP: transparent native resume, argument forwarding, ledger search, privacy, and recovery. |+| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, Crush, and OMP: automatic harness selection, native resume, argument forwarding, ledger search, privacy, and recovery. |+| [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md) | Protocol and acceptance bar for contributors adding managed resume, read-only transcript import, and startup context delivery to another harness. || [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation. || [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: default single-slot routing, session-aware isolation, and multi-user `per_actor` behavior. || [`docs/macos.md`](docs/macos.md) | macOS install paths: native release binary (recommended), source build, the Docker wrapper, hook-platform notes, and current macOS limitations. |diff --git a/bin/ai-memory b/bin/ai-memoryindex d46ff799..7f64d6ce 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -197,7 +197,7 @@ cmd_upgrade() {touch "${VERSION_CHECK_FILE}"}-# `ai-memory run` must execute on the host: Claude/Codex/OpenCode and their+# `ai-memory run` must execute on the host: native harnesses and their# native transcript stores are host resources, not contents of the helper# container. Keep a checksum-verified release client beside the wrapper cache.native_run_binary() {@@ -292,8 +292,9 @@ case "${1:-}" inexit 0;;run)+ shiftNATIVE_RUN_BIN=$(native_run_binary)- exec "${NATIVE_RUN_BIN}" "$@"+ exec "${NATIVE_RUN_BIN}" run "$@";;esacdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 0f5791fd..dad4a3f8 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -180,9 +180,14 @@ pub struct RunArgs {/// Override the native harness executable path.#[arg(long)]pub executable: Option<PathBuf>,- /// Agent harness to launch.+ /// Disable native permission prompts using the selected harness's+ /// equivalent dangerous-mode option.+ #[arg(long)]+ pub yolo: bool,+ /// Agent harness to launch. When omitted, continue the newest managed or+ /// checkout-local session among the auto-detected harnesses.#[arg(value_enum)]- pub harness: RunHarnessChoice,+ pub harness: Option<RunHarnessChoice>,/// Native harness arguments, forwarded byte-for-byte and in order.#[arg(allow_hyphen_values = true, trailing_var_arg = true)]pub native_args: Vec<OsString>,@@ -201,6 +206,8 @@ pub enum RunHarnessChoice {OpenCode,/// Pi coding agent.Pi,+ /// Charmbracelet Crush.+ Crush,/// Oh My Pi.#[value(alias = "oh-my-pi")]Omp,diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 8dca4ff0..509082c2 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -891,13 +891,36 @@ fn apply_to_devin_settings(auth_token: Option<&str>,data_dir: &Path,args: &InstallHooksArgs,+) -> Result<()> {+ let staged = stage_hook_scripts(hooks_dir, "devin")?;+ apply_to_devin_settings_with_staged(&staged, server_url, auth_token, data_dir, args)+}++#[cfg(test)]+fn apply_to_devin_settings_in(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ staging_data_local: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ let staged = stage_hook_scripts_in(hooks_dir, "devin", staging_data_local)?;+ apply_to_devin_settings_with_staged(&staged, server_url, auth_token, data_dir, args)+}++fn apply_to_devin_settings_with_staged(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,) -> Result<()> {let path = match &args.config_file {Some(p) => p.clone(),None => devin_hooks_path()?,};- let staged = stage_hook_scripts(hooks_dir, "devin")?;- let command_dir = staged_command_dir(&staged, "devin");+ let command_dir = staged_command_dir(staged, "devin");let strategy = args.project_strategy.baked();let payload = build_devin_payload_with_data_dir(&command_dir,@@ -5219,11 +5242,12 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessiolet config_tmp = TempDir::new().unwrap();let config_path = config_tmp.path().join("hooks.v1.json");- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp.path(),+ config_tmp.path(),&InstallHooksArgs {agent: AgentChoice::Devin,hooks_dir: Some(hooks_tmp.path().to_path_buf()),@@ -5280,11 +5304,12 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio).unwrap();- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp.path(),+ config_tmp.path(),&InstallHooksArgs {agent: AgentChoice::Devin,hooks_dir: Some(hooks_tmp.path().to_path_buf()),@@ -5347,20 +5372,22 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioapply: false,};- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp.path(),+ config_tmp.path(),&args_v1,).unwrap();- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp.path(),+ config_tmp.path(),&args_v1,).unwrap();@@ -5389,20 +5416,22 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessioapply: false,};- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp2.path(),+ config_tmp2.path(),&args_config,).unwrap();- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp2.path(),+ config_tmp2.path(),&args_config,).unwrap();@@ -5439,11 +5468,12 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio).unwrap();- apply_to_devin_settings(+ apply_to_devin_settings_in(hooks_tmp.path(),"http://127.0.0.1:49374",None,config_tmp.path(),+ config_tmp.path(),&InstallHooksArgs {agent: AgentChoice::Devin,hooks_dir: Some(hooks_tmp.path().to_path_buf()),diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex a64c4aea..62751b44 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -1,16 +1,20 @@//! Opt-in managed cross-harness launcher.-use std::path::PathBuf;+use std::ffi::{OsStr, OsString};+use std::io::{self, IsTerminal as _};+use std::path::{Path, PathBuf};use std::process::Stdio;use std::time::{Duration, SystemTime};use ai_memory_core::{- FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest, ManagedRunStatus,- PrepareManagedRunRequest, PrepareManagedRunResponse,+ AgentKind, FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,+ ManagedRunContextResponse, ManagedRunStatus, PrepareManagedRunRequest,+ PrepareManagedRunResponse,};use ai_memory_workstream::{- ExportedTranscript, ManagedHarness, build_launch_plan, discover_native_session,- export_transcript, inspect_repository, wait_for_transcript_flush,+ 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,};use anyhow::{Context as _, Result, anyhow};use tokio::process::Command;@@ -23,13 +27,58 @@ use crate::http_client::{ServerEndpoint, get_json, post_empty, post_json, post_jconst HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);const IMPORT_BATCH_EVENTS: usize = 400;const IMPORT_BATCH_BYTES: usize = 1024 * 1024;+const ADOPTION_CANDIDATE_LIMIT: usize = 8;+const AUTO_HARNESSES: [ManagedHarness; 5] = [+ ManagedHarness::Claude,+ ManagedHarness::Codex,+ ManagedHarness::OpenCode,+ ManagedHarness::Pi,+ ManagedHarness::Crush,+];++#[derive(Debug, Clone)]+struct AutoSessionCandidate {+ harness: ManagedHarness,+ session: NativeSessionCandidate,+}/// Run one native harness and return its exact process exit code.pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {- let harness = managed_harness(args.harness);let cwd = std::env::current_dir().context("getting managed run working directory")?;let repository = inspect_repository(&cwd)?;+ let home = native_home(config).context("locating native harness session storage")?;+ let automatic_harness = args.harness.is_none();+ let mut native_args = args.native_args;+ let trailing_yolo = remove_wrapper_yolo(&mut native_args);+ if automatic_harness && !native_args.is_empty() {+ return Err(anyhow!(+ "native harness arguments require an explicit harness; try `ai-memory run codex ...`"+ ));+ }+ if automatic_harness && args.executable.is_some() {+ return Err(anyhow!(+ "--executable requires an explicit harness; try `ai-memory run --executable <path> codex`"+ ));+ }+ let auto_candidates = if automatic_harness {+ filter_usable_auto_sessions(+ list_auto_sessions(&home, &repository.cwd).await?,+ |harness| executable_available(OsStr::new(harness.executable())),+ )?+ } else {+ Vec::new()+ };+ let provisional_harness = match args.harness {+ Some(choice) => managed_harness(choice),+ None => auto_candidates+ .first()+ .map(|candidate| candidate.harness)+ .ok_or_else(no_auto_session_error)?,+ };+ let executable = args.executable.map(PathBuf::into_os_string);+ ensure_executable_available(provisional_harness, executable.as_deref())?;let project = resolve_project_name(config, args.project.as_deref())?;+ let may_adopt_native_session = args.new_workstream.is_none();let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;let prepare = PrepareManagedRunRequest {workspace: args.workspace,@@ -37,7 +86,12 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {cwd: repository.cwd.to_string_lossy().into_owned(),repo_fingerprint: repository.repo_fingerprint,worktree_fingerprint: repository.worktree_fingerprint,- agent: harness.agent_kind(),+ agent: provisional_harness.agent_kind(),+ automatic_harness,+ available_agents: auto_candidates+ .iter()+ .map(|candidate| candidate.harness.agent_kind())+ .collect(),workstream: args.workstream,new_workstream: args.new_workstream,lease_owner: lease_owner(),@@ -45,13 +99,102 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {let prepared: PrepareManagedRunResponse = post_json(&endpoint, "/workstream/runs", &prepare).await.context("opening managed workstream; the agent was not started")?;- let plan = build_launch_plan(+ let run_path = format!("/workstream/runs/{}", prepared.run_id);+ let harness = if automatic_harness {+ let resolved = prepared.resolved_agent.unwrap_or_else(|| {+ eprintln!(+ "ai-memory: the server does not support managed harness precedence; using the newest checkout-local session. Upgrade the server for established-workstream selection"+ );+ provisional_harness.agent_kind()+ });+ managed_harness_from_agent(resolved).ok_or_else(|| {+ anyhow!(+ "the server selected unsupported automatic harness '{}'",+ resolved.as_str()+ )+ })?+ } else {+ provisional_harness+ };+ ensure_executable_available(harness, executable.as_deref())?;+ let mut plan = build_launch_plan(harness,- args.executable.map(PathBuf::into_os_string),- args.native_args,+ executable.clone(),+ native_args.clone(),prepared.native_session_id.as_deref(),)?;- let run_path = format!("/workstream/runs/{}", prepared.run_id);+ if automatic_harness+ && prepared.native_session_id.is_none()+ && prepared.may_adopt_existing_session+ && may_adopt_native_session+ {+ let candidate = auto_candidates+ .iter()+ .find(|candidate| candidate.harness == harness)+ .context("the selected automatic harness no longer has a checkout-local session")?;+ plan = build_launch_plan(+ harness,+ executable.clone(),+ native_args.clone(),+ Some(&candidate.session.native_session_id),+ )?;+ eprintln!(+ "ai-memory: continuing newest checkout-local {} session {}",+ harness.as_str(),+ display_session_id(&candidate.session.native_session_id)+ );+ } else if prepared.native_session_id.is_none()+ && prepared.may_adopt_existing_session+ && may_adopt_native_session+ && allows_native_session_adoption(harness, &native_args)+ && io::stdin().is_terminal()+ && io::stderr().is_terminal()+ && let Some(home) = native_home(config)+ {+ match list_native_sessions(+ harness,+ &home,+ &repository.cwd,+ plan.session_dir.as_deref(),+ ADOPTION_CANDIDATE_LIMIT,+ )+ .await+ {+ Ok(candidates) if !candidates.is_empty() => {+ let selection = choose_native_session_interactive(+ harness,+ prepared.workstream_name.clone(),+ candidates,+ &endpoint,+ &run_path,+ )+ .await?;+ match selection {+ Ok(Some(native_session_id)) => {+ plan = build_launch_plan(+ harness,+ executable,+ native_args,+ Some(&native_session_id),+ )?;+ }+ Ok(None) => {}+ Err(error) => eprintln!(+ "ai-memory: could not read the native session choice ({error}); starting a new {} session",+ harness.as_str()+ ),+ }+ }+ Ok(_) => {}+ Err(error) => eprintln!(+ "ai-memory: could not inspect prior {} sessions ({error}); starting a new session",+ harness.as_str()+ ),+ }+ }+ if args.yolo || trailing_yolo {+ apply_yolo(harness, &mut plan.args);+ }if let Some(native_session_id) = &plan.expected_session_id {post_json_no_content(&endpoint,@@ -64,8 +207,15 @@ 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 {+ prepare_crush_context(&endpoint, &run_path, &home).await?+ } else {+ None+ };+let started_at = SystemTime::now();- let child = Command::new(&plan.program)+ let mut command = Command::new(&plan.program);+ command.args(&plan.args).current_dir(&repository.cwd).env("AI_MEMORY_RUN_ID", prepared.run_id.to_string())@@ -76,8 +226,11 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {.env("AI_MEMORY_HOOK_URL", endpoint.build_url("")).stdin(Stdio::inherit()).stdout(Stdio::inherit())- .stderr(Stdio::inherit())- .spawn();+ .stderr(Stdio::inherit());+ if let Some(context) = &crush_context {+ command.env("CRUSH_GLOBAL_CONFIG", context.path());+ }+ let child = command.spawn();let mut child = match child {Ok(child) => child,@@ -102,6 +255,16 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {));}};+ if harness == ManagedHarness::Crush+ && let Err(error) = post_empty_with_retry(+ &endpoint,+ &format!("{run_path}/context/accept"),+ "acknowledging Crush managed context",+ )+ .await+ {+ eprintln!("ai-memory: {error}; the context may be delivered again on the next Crush run");+ }let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL);heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);@@ -121,12 +284,6 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {let server_status = get_json::<ManagedRunStatus>(&endpoint, &run_path, &[]).await.ok();- let home = config- .home_dir- .as_deref()- .map(PathBuf::from)- .or_else(path_util::home_dir)- .context("locating the home directory for native transcript import")?;let discovered_session = if plan.expected_session_id.is_none() {discover_native_session(harness,@@ -188,6 +345,346 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {Ok(exit_code)}+async fn list_auto_sessions(home: &Path, cwd: &Path) -> Result<Vec<AutoSessionCandidate>> {+ let mut found = Vec::new();+ let mut failures = Vec::new();+ for harness in AUTO_HARNESSES {+ match list_native_sessions(harness, home, cwd, None, 1).await {+ Ok(candidates) => found.extend(+ candidates+ .into_iter()+ .map(|session| AutoSessionCandidate { harness, session }),+ ),+ Err(error) => failures.push(format!("{}: {error}", harness.as_str())),+ }+ }+ if found.is_empty() && !failures.is_empty() {+ return Err(anyhow!(+ "could not inspect checkout-local sessions: {}",+ failures.join("; ")+ ));+ }+ for failure in failures {+ eprintln!("ai-memory: session scan skipped {failure}");+ }+ found.sort_by(|left, right| {+ right+ .session+ .updated_at+ .cmp(&left.session.updated_at)+ .then_with(|| left.harness.as_str().cmp(right.harness.as_str()))+ });+ Ok(found)+}++fn filter_usable_auto_sessions(+ candidates: Vec<AutoSessionCandidate>,+ available: impl Fn(ManagedHarness) -> bool,+) -> Result<Vec<AutoSessionCandidate>> {+ let mut missing = Vec::new();+ let usable = candidates+ .into_iter()+ .filter(|candidate| {+ if available(candidate.harness) {+ true+ } else {+ missing.push(candidate.harness.executable());+ false+ }+ })+ .collect::<Vec<_>>();+ if usable.is_empty() && !missing.is_empty() {+ missing.sort_unstable();+ missing.dedup();+ return Err(anyhow!(+ "checkout-local sessions were found, but their harness executables are not available in the host PATH: {}",+ missing.join(", ")+ ));+ }+ Ok(usable)+}++fn no_auto_session_error() -> anyhow::Error {+ anyhow!(+ "no Claude Code, Codex, OpenCode, Pi, or Crush session was found for this directory; start one explicitly with `ai-memory run claude`, `ai-memory run codex`, `ai-memory run opencode`, `ai-memory run pi`, or `ai-memory run crush`"+ )+}++fn remove_wrapper_yolo(args: &mut Vec<OsString>) -> bool {+ let before = args.len();+ args.retain(|arg| arg != OsStr::new("--yolo"));+ args.len() != before+}++fn ensure_executable_available(harness: ManagedHarness, executable: Option<&OsStr>) -> Result<()> {+ let program = executable.unwrap_or_else(|| OsStr::new(harness.executable()));+ if executable_available(program) {+ return Ok(());+ }+ Err(anyhow!(+ "managed {} executable `{}` was not found in the host PATH; install it or pass `--executable`. Docker users should run `ai-memory upgrade` to refresh the host wrapper",+ harness.as_str(),+ program.to_string_lossy()+ ))+}++fn executable_available(program: &OsStr) -> bool {+ let path = Path::new(program);+ if path.components().count() > 1 {+ return executable_path_available(path);+ }+ std::env::var_os("PATH").is_some_and(|path_value| {+ std::env::split_paths(&path_value)+ .map(|dir| dir.join(path))+ .any(|candidate| executable_path_available(&candidate))+ })+}++fn executable_path_available(path: &Path) -> bool {+ if executable_file(path) {+ return true;+ }+ #[cfg(windows)]+ if path.extension().is_none() {+ let extensions =+ std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());+ return extensions+ .split(';')+ .filter(|extension| !extension.is_empty())+ .map(|extension| path.with_extension(extension.trim_start_matches('.')))+ .any(|candidate| executable_file(&candidate));+ }+ false+}++fn executable_file(path: &Path) -> bool {+ let Ok(metadata) = path.metadata() else {+ return false;+ };+ if !metadata.is_file() {+ return false;+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ metadata.permissions().mode() & 0o111 != 0+ }+ #[cfg(not(unix))]+ {+ true+ }+}++async fn prepare_crush_context(+ endpoint: &ServerEndpoint,+ run_path: &str,+ home: &Path,+) -> Result<Option<tempfile::TempDir>> {+ let response: ManagedRunContextResponse = post_json(+ endpoint,+ &format!("{run_path}/context"),+ &serde_json::json!({}),+ )+ .await+ .context("loading the managed context for Crush; the agent was not started")?;+ let Some(context) = response.context else {+ return Ok(None);+ };++ write_crush_context_config(&crush_global_config_path(home), &context).map(Some)+}++fn write_crush_context_config(source: &Path, context: &str) -> Result<tempfile::TempDir> {+ let temp = tempfile::Builder::new()+ .prefix("ai-memory-crush-")+ .tempdir()+ .context("creating the temporary Crush context directory")?;+ let context_path = temp.path().join("managed-workstream.md");+ write_private(&context_path, context.as_bytes())?;++ let mut config = if source.is_file() {+ let raw = std::fs::read(source)+ .with_context(|| format!("reading Crush config {}", source.display()))?;+ serde_json::from_slice::<serde_json::Value>(&raw)+ .with_context(|| format!("parsing Crush config {}", source.display()))?+ } else {+ serde_json::json!({})+ };+ let root = config+ .as_object_mut()+ .context("Crush global config must be a JSON object")?;+ let options = root+ .entry("options")+ .or_insert_with(|| serde_json::json!({}))+ .as_object_mut()+ .context("Crush global config `options` must be a JSON object")?;+ let paths = options+ .entry("global_context_paths")+ .or_insert_with(|| serde_json::json!([]))+ .as_array_mut()+ .context("Crush `options.global_context_paths` must be an array")?;+ let context_path = context_path.to_string_lossy().into_owned();+ if !paths+ .iter()+ .any(|value| value.as_str() == Some(&context_path))+ {+ paths.push(serde_json::Value::String(context_path));+ }+ let rendered = serde_json::to_vec_pretty(&config).context("rendering Crush config")?;+ write_private(&temp.path().join("crush.json"), &rendered)?;+ Ok(temp)+}++fn crush_global_config_path(home: &Path) -> PathBuf {+ if let Some(dir) = std::env::var_os("CRUSH_GLOBAL_CONFIG").filter(|value| !value.is_empty()) {+ return PathBuf::from(dir).join("crush.json");+ }+ if let Some(dir) = std::env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty()) {+ return PathBuf::from(dir).join("crush/crush.json");+ }+ home.join(".config/crush/crush.json")+}++fn write_private(path: &Path, content: &[u8]) -> Result<()> {+ use std::io::Write as _;++ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt as _;+ options.mode(0o600);+ }+ let mut file = options+ .open(path)+ .with_context(|| format!("creating {}", path.display()))?;+ file.write_all(content)+ .with_context(|| format!("writing {}", path.display()))+}++fn native_home(config: &Config) -> Option<PathBuf> {+ config+ .home_dir+ .as_deref()+ .map(PathBuf::from)+ .or_else(path_util::home_dir)+}++async fn choose_native_session_interactive(+ harness: ManagedHarness,+ workstream_name: String,+ candidates: Vec<NativeSessionCandidate>,+ endpoint: &ServerEndpoint,+ run_path: &str,+) -> Result<io::Result<Option<String>>> {+ let mut chooser = tokio::task::spawn_blocking(move || {+ let stdin = io::stdin();+ let stderr = io::stderr();+ choose_native_session(+ harness,+ &workstream_name,+ &candidates,+ &mut stdin.lock(),+ &mut stderr.lock(),+ SystemTime::now(),+ )+ });+ let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL);+ heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ heartbeat.tick().await;+ let selection = loop {+ tokio::select! {+ result = &mut chooser => {+ break result.context("waiting for the native session choice")?;+ }+ _ = heartbeat.tick() => {+ if let Err(error) = post_empty(endpoint, &format!("{run_path}/heartbeat")).await {+ eprintln!("ai-memory: managed workstream heartbeat failed: {error}");+ }+ }+ }+ };+ post_empty(endpoint, &format!("{run_path}/heartbeat"))+ .await+ .context(+ "renewing the managed workstream after session selection; the agent was not started",+ )?;+ Ok(selection)+}++fn choose_native_session(+ harness: ManagedHarness,+ workstream_name: &str,+ candidates: &[NativeSessionCandidate],+ input: &mut impl io::BufRead,+ output: &mut impl io::Write,+ now: SystemTime,+) -> io::Result<Option<String>> {+ writeln!(+ output,+ "ai-memory: no {} session is linked to workstream '{}'.",+ harness.as_str(),+ workstream_name+ )?;+ writeln!(output, "Previous sessions for this checkout:")?;+ for (index, candidate) in candidates.iter().enumerate() {+ writeln!(+ output,+ " {}) {} (updated {})",+ index + 1,+ display_session_id(&candidate.native_session_id),+ session_age(candidate.updated_at, now)+ )?;+ }+ writeln!(output, " 0) Start a new {} session", harness.as_str())?;++ loop {+ write!(output, "Select [1]: ")?;+ output.flush()?;+ let mut line = String::new();+ if input.read_line(&mut line)? == 0 {+ writeln!(output)?;+ return Ok(None);+ }+ let choice = line.trim();+ if choice.is_empty() {+ return Ok(Some(candidates[0].native_session_id.clone()));+ }+ if matches!(choice.to_ascii_lowercase().as_str(), "0" | "n" | "new") {+ return Ok(None);+ }+ if let Ok(index) = choice.parse::<usize>()+ && let Some(candidate) = index.checked_sub(1).and_then(|i| candidates.get(i))+ {+ return Ok(Some(candidate.native_session_id.clone()));+ }+ writeln!(output, "Enter 0 through {}.", candidates.len())?;+ }+}++fn display_session_id(value: &str) -> String {+ const MAX_CHARS: usize = 64;+ let mut output = value.chars().take(MAX_CHARS).collect::<String>();+ if value.chars().count() > MAX_CHARS {+ output.push_str("...");+ }+ output+}++fn session_age(updated_at: SystemTime, now: SystemTime) -> String {+ let age = now.duration_since(updated_at).unwrap_or_default().as_secs();+ match age {+ 0..60 => "just now".into(),+ 60..3_600 => plural_age(age / 60, "minute"),+ 3_600..86_400 => plural_age(age / 3_600, "hour"),+ _ => plural_age(age / 86_400, "day"),+ }+}++fn plural_age(value: u64, unit: &str) -> String {+ format!("{value} {unit}{} ago", if value == 1 { "" } else { "s" })+}+async fn export_after_flush(harness: ManagedHarness,home: &std::path::Path,@@ -300,6 +797,18 @@ async fn finish_with_retry(.context("persisting the managed transcript; the native process has already exited")}+async fn post_empty_with_retry(endpoint: &ServerEndpoint, path: &str, label: &str) -> Result<()> {+ let mut last_error = None;+ for attempt in 0..3 {+ match post_empty(endpoint, path).await {+ Ok(()) => return Ok(()),+ Err(error) => last_error = Some(error),+ }+ tokio::time::sleep(Duration::from_millis(250 * (attempt + 1))).await;+ }+ Err(last_error.unwrap_or_else(|| anyhow!("request failed"))).context(label.to_string())+}+fn nonempty_session(value: &str) -> Option<String> {(!value.is_empty()).then(|| value.to_string())}@@ -315,20 +824,132 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {RunHarnessChoice::Codex => ManagedHarness::Codex,RunHarnessChoice::OpenCode => ManagedHarness::OpenCode,RunHarnessChoice::Pi => ManagedHarness::Pi,+ RunHarnessChoice::Crush => ManagedHarness::Crush,RunHarnessChoice::Omp => ManagedHarness::Omp,}}+const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness> {+ match agent {+ AgentKind::ClaudeCode => Some(ManagedHarness::Claude),+ AgentKind::Codex => Some(ManagedHarness::Codex),+ AgentKind::OpenCode => Some(ManagedHarness::OpenCode),+ AgentKind::Pi => Some(ManagedHarness::Pi),+ AgentKind::Crush => Some(ManagedHarness::Crush),+ _ => None,+ }+}+#[cfg(test)]mod tests {use std::ffi::{OsStr, OsString};+ use std::io::Cursor;use clap::Parser as _;+ use super::*;use crate::cli::{Cli, Command as CliCommand};+ fn candidates() -> Vec<NativeSessionCandidate> {+ vec![+ NativeSessionCandidate {+ native_session_id: "newest".into(),+ updated_at: SystemTime::UNIX_EPOCH + Duration::from_secs(3_600),+ },+ NativeSessionCandidate {+ native_session_id: "older".into(),+ updated_at: SystemTime::UNIX_EPOCH,+ },+ ]+ }++ fn auto_candidate(harness: ManagedHarness, updated: u64) -> AutoSessionCandidate {+ AutoSessionCandidate {+ harness,+ session: NativeSessionCandidate {+ native_session_id: format!("{}-{updated}", harness.as_str()),+ updated_at: SystemTime::UNIX_EPOCH + Duration::from_secs(updated),+ },+ }+ }++ #[test]+ fn automatic_selection_skips_newer_sessions_for_unavailable_harnesses() {+ let candidates = vec![+ auto_candidate(ManagedHarness::Claude, 200),+ auto_candidate(ManagedHarness::Codex, 100),+ ];+ let usable =+ filter_usable_auto_sessions(candidates, |harness| harness == ManagedHarness::Codex)+ .unwrap();+ assert_eq!(usable.len(), 1);+ assert_eq!(usable[0].harness, ManagedHarness::Codex);++ let error =+ filter_usable_auto_sessions(vec![auto_candidate(ManagedHarness::Claude, 200)], |_| {+ false+ })+ .unwrap_err();+ assert!(error.to_string().contains("claude"));+ }++ #[test]+ fn adoption_prompt_defaults_to_newest_checkout_session() {+ let mut input = Cursor::new(b"\n");+ let mut output = Vec::new();+ let selected = choose_native_session(+ ManagedHarness::Codex,+ "default",+ &candidates(),+ &mut input,+ &mut output,+ SystemTime::UNIX_EPOCH + Duration::from_secs(7_200),+ )+ .unwrap();+ assert_eq!(selected.as_deref(), Some("newest"));+ let rendered = String::from_utf8(output).unwrap();+ assert!(rendered.contains("no codex session is linked"));+ assert!(rendered.contains("updated 1 hour ago"));+ assert!(rendered.contains("Start a new codex session"));+ }+#[test]- fn native_arguments_do_not_require_separator_and_remain_opaque() {+ fn adoption_prompt_can_start_fresh_or_select_an_older_session() {+ let mut fresh_input = Cursor::new(b"0\n");+ let mut output = Vec::new();+ assert!(+ choose_native_session(+ ManagedHarness::Claude,+ "default",+ &candidates(),+ &mut fresh_input,+ &mut output,+ SystemTime::UNIX_EPOCH,+ )+ .unwrap()+ .is_none()+ );++ let mut older_input = Cursor::new(b"invalid\n2\n");+ let selected = choose_native_session(+ ManagedHarness::Codex,+ "default",+ &candidates(),+ &mut older_input,+ &mut output,+ SystemTime::UNIX_EPOCH,+ )+ .unwrap();+ assert_eq!(selected.as_deref(), Some("older"));+ assert!(+ String::from_utf8(output)+ .unwrap()+ .contains("Enter 0 through 2.")+ );+ }++ #[test]+ fn native_arguments_do_not_require_separator_and_wrapper_yolo_is_consumed() {let cli = Cli::try_parse_from([OsStr::new("ai-memory"),OsStr::new("run"),@@ -345,9 +966,10 @@ mod tests {panic!("expected run command");};assert_eq!(args.project.as_deref(), Some("memory"));+ assert!(args.yolo);assert_eq!(args.native_args,- ["--yolo", "-m", "gpt-5", "continue here"]+ ["-m", "gpt-5", "continue here"].map(OsString::from).to_vec());@@ -370,7 +992,7 @@ mod tests {};assert!(matches!(args.harness,- crate::cli::RunHarnessChoice::OpenCode+ Some(crate::cli::RunHarnessChoice::OpenCode)));assert_eq!(args.native_args,@@ -379,4 +1001,52 @@ mod tests {.to_vec());}++ #[test]+ fn bare_run_and_wrapper_yolo_parse_without_a_harness() {+ let cli = Cli::try_parse_from(["ai-memory", "run", "--yolo"]).unwrap();+ let CliCommand::Run(args) = cli.command else {+ panic!("expected run command");+ };+ assert!(args.harness.is_none());+ assert!(args.yolo);+ assert!(args.native_args.is_empty());+ }++ #[test]+ fn trailing_wrapper_yolo_is_removed_before_native_resume_detection() {+ let mut args = ["--yolo", "resume", "native-id"]+ .map(OsString::from)+ .to_vec();+ assert!(remove_wrapper_yolo(&mut args));+ assert_eq!(args, ["resume", "native-id"].map(OsString::from));+ }++ #[test]+ fn crush_context_config_preserves_user_settings_and_adds_packet() {+ let source_dir = tempfile::tempdir().unwrap();+ let source = source_dir.path().join("crush.json");+ std::fs::write(+ &source,+ serde_json::to_vec(&serde_json::json!({+ "options": {"debug": true, "global_context_paths": ["/existing.md"]},+ "providers": {"custom": {"type": "openai"}}+ }))+ .unwrap(),+ )+ .unwrap();++ let generated = write_crush_context_config(&source, "managed packet").unwrap();+ let config: serde_json::Value =+ serde_json::from_slice(&std::fs::read(generated.path().join("crush.json")).unwrap())+ .unwrap();+ assert_eq!(config["options"]["debug"], true);+ assert_eq!(config["providers"]["custom"]["type"], "openai");+ let paths = config["options"]["global_context_paths"]+ .as_array()+ .unwrap();+ assert_eq!(paths[0], "/existing.md");+ let packet = paths[1].as_str().unwrap();+ assert_eq!(std::fs::read_to_string(packet).unwrap(), "managed packet");+ }}diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rsindex 1cb3d4c7..bf0fbe38 100644--- a/crates/ai-memory-cli/tests/packaging.rs+++ b/crates/ai-memory-cli/tests/packaging.rs@@ -204,6 +204,73 @@ fn macos_wrapper_routes_urls_by_real_subcommand() {);}+#[cfg(unix)]+#[test]+fn managed_run_wrapper_uses_host_binary_path_and_remote_server_without_docker() {+ let tmp = tempfile::tempdir().unwrap();+ let native = tmp.path().join("native-ai-memory");+ let docker = tmp.path().join("docker");+ let record = tmp.path().join("native-record.txt");+ let docker_record = tmp.path().join("docker-record.txt");+ std::fs::write(+ &native,+ format!(+ "#!/usr/bin/env bash\n\+ printf 'server=%s\\nauth=%s\\npath=%s\\n' \"$AI_MEMORY_SERVER_URL\" \"$AI_MEMORY_AUTH_TOKEN\" \"$PATH\" > {}\n\+ printf 'arg=%s\\n' \"$@\" >> {}\n",+ shell_path(&record),+ shell_path(&record)+ ),+ )+ .unwrap();+ std::fs::write(+ &docker,+ format!(+ "#!/usr/bin/env bash\nprintf '%s\\n' \"$@\" > {}\nexit 99\n",+ shell_path(&docker_record)+ ),+ )+ .unwrap();+ {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::set_permissions(&native, std::fs::Permissions::from_mode(0o755)).unwrap();+ std::fs::set_permissions(&docker, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let host_path = format!(+ "{}:{}",+ shell_path(tmp.path()),+ std::env::var("PATH").unwrap_or_default()+ );+ let output = shell_script_command(&repo_root().join("bin/ai-memory"))+ .args(["run", "codex", "--yolo", "resume"])+ .env("AI_MEMORY_NATIVE_BIN", &native)+ .env("AI_MEMORY_DOCKER", &docker)+ .env("AI_MEMORY_SERVER_URL", "http://192.168.0.90:49374")+ .env("AI_MEMORY_AUTH_TOKEN", "remote-test-token")+ .env("PATH", &host_path)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "wrapper failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let record = std::fs::read_to_string(record).unwrap();+ assert_eq!(+ record,+ format!(+ "server=http://192.168.0.90:49374\n\+ auth=remote-test-token\n\+ path={host_path}\n\+ arg=run\n\+ arg=codex\n\+ arg=--yolo\n\+ arg=resume\n"+ )+ );+ assert!(!docker_record.exists(), "managed run entered Docker");+}+// Unlike run_wrapper_on_fake_macos's docker fake (which only ever sees one// meaningful call — the final `docker run`), the rootless-Docker UID check// calls `docker info` *before* `docker run`, so this fake must dispatch ondiff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex b8a3d150..cbde6213 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -198,6 +198,8 @@ pub enum AgentKind {/// Pi coding agent.#[serde(rename = "pi")]Pi,+ /// Charmbracelet Crush coding agent.+ Crush,/// xAI Grok Build CLI (`grok`).Grok,/// Zero coding agent (Gitlawb/zero).@@ -216,7 +218,7 @@ impl AgentKind {/// CHECK constraint accepts every kind (the Zero integration shipped/// with the enum variant but without the V26 migration and only a/// live test caught it). Extend together with the enum.- pub const ALL: [Self; 15] = [+ pub const ALL: [Self; 16] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@ -227,6 +229,7 @@ impl AgentKind {Self::AntigravityCli,Self::Omp,Self::Pi,+ Self::Crush,Self::Grok,Self::Zero,Self::Devin,@@ -248,6 +251,7 @@ impl AgentKind {Self::AntigravityCli => "antigravity-cli",Self::Omp => "omp",Self::Pi => "pi",+ Self::Crush => "crush",Self::Grok => "grok",Self::Zero => "zero",Self::Devin => "devin",@@ -271,6 +275,7 @@ impl AgentKind {"openclaw" | "open-claw" => Self::OpenClaw,"antigravity-cli" | "antigravity" | "agy" => Self::AntigravityCli,"pi" => Self::Pi,+ "crush" => Self::Crush,"omp" | "oh-my-pi" => Self::Omp,"grok" => Self::Grok,"zero" => Self::Zero,@@ -297,7 +302,7 @@ impl AgentKind {/// should fail safe.#[must_use]pub fn session_start_injects_handoff(self) -> bool {- !matches!(self, Self::Grok | Self::Zero | Self::Other)+ !matches!(self, Self::Crush | Self::Grok | Self::Zero | Self::Other)}}@@ -442,6 +447,11 @@ mod tests {AgentKind::Pi);+ let crush = serde_json::to_string(&AgentKind::Crush).unwrap();+ assert_eq!(crush, "\"crush\"");+ assert_eq!(AgentKind::from_wire("crush"), AgentKind::Crush);+ assert!(!AgentKind::Crush.session_start_injects_handoff());+let openclaw = serde_json::to_string(&AgentKind::OpenClaw).unwrap();assert_eq!(openclaw, "\"openclaw\"");assert_eq!(diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 27a25703..c2dd141d 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -50,7 +50,7 @@ pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, find_marker_lipub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};pub use workstream::{- FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest, ManagedRunStatus,- NewWorkstreamEvent, PrepareManagedRunRequest, PrepareManagedRunResponse, WorkstreamCheckpoint,- WorkstreamEvent, WorkstreamEventKind,+ FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,+ ManagedRunContextResponse, ManagedRunStatus, NewWorkstreamEvent, PrepareManagedRunRequest,+ PrepareManagedRunResponse, WorkstreamCheckpoint, WorkstreamEvent, WorkstreamEventKind,};diff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsindex 59d64245..8d210073 100644--- a/crates/ai-memory-core/src/workstream.rs+++ b/crates/ai-memory-core/src/workstream.rs@@ -119,6 +119,14 @@ pub struct PrepareManagedRunRequest {pub worktree_fingerprint: String,/// Harness being launched.pub agent: AgentKind,+ /// Resolve the harness from the established workstream when possible.+ /// The provisional `agent` is the newest checkout-local candidate.+ #[serde(default)]+ pub automatic_harness: bool,+ /// Checkout-local harnesses with resumable sessions. The server only uses+ /// these values when `automatic_harness` is true.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub available_agents: Vec<AgentKind>,/// Select an existing named workstream instead of the current selection.#[serde(default, skip_serializing_if = "Option::is_none")]pub workstream: Option<String>,@@ -138,6 +146,10 @@ pub struct PrepareManagedRunResponse {pub workstream_name: String,/// Lease/run identifier exported to the child process.pub run_id: ManagedRunId,+ /// Harness selected by the server. Old servers omit this field; explicit+ /// harness launches remain compatible, while automatic launches fail safe.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub resolved_agent: Option<AgentKind>,/// Previously linked native session for this harness, if any.#[serde(default, skip_serializing_if = "Option::is_none")]pub native_session_id: Option<String>,@@ -148,6 +160,18 @@ pub struct PrepareManagedRunResponse {pub sync_after: i64,/// Portable high-water mark assigned to this launch.pub sync_through: i64,+ /// Whether this otherwise-empty workstream may adopt a pre-existing native+ /// session. Old servers omit this field, which safely defaults to fresh.+ #[serde(default)]+ pub may_adopt_existing_session: bool,+}++/// One-time startup context for harnesses without a SessionStart hook.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ManagedRunContextResponse {+ /// Bounded portable context packet, or `None` when there is nothing new.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub context: Option<String>,}/// Bind the actual native session selected or created by a managed launch.@@ -236,3 +260,40 @@ pub struct WorkstreamEvent {#[serde(default, skip_serializing_if = "Option::is_none")]pub occurred_at: Option<String>,}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn older_prepare_response_defaults_to_no_adoption() {+ let response: PrepareManagedRunResponse = serde_json::from_value(serde_json::json!({+ "workstream_id": "018f0000-0000-7000-8000-000000000001",+ "workstream_name": "default",+ "run_id": "018f0000-0000-7000-8000-000000000002",+ "sync_after": 0,+ "sync_through": 0+ }))+ .unwrap();++ assert!(!response.may_adopt_existing_session);+ assert!(response.resolved_agent.is_none());+ }++ #[test]+ fn older_prepare_request_defaults_to_explicit_harness() {+ let request: PrepareManagedRunRequest = serde_json::from_value(serde_json::json!({+ "workspace": "default",+ "project": "memory",+ "cwd": "/repo",+ "repo_fingerprint": "repo",+ "worktree_fingerprint": "worktree",+ "agent": "codex",+ "lease_owner": "host:1"+ }))+ .unwrap();++ assert!(!request.automatic_harness);+ assert!(request.available_agents.is_empty());+ }+}diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 2c161e12..08d58d6c 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -1280,7 +1280,7 @@ fn render_handoff_markdown(h: &Handoff) -> String {buf}-fn render_managed_context(+pub(crate) fn render_managed_context(events: &[WorkstreamEvent],workstream_name: &str,workstream_id: ai_memory_core::WorkstreamId,diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 45ce6471..1c4e90ce 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -6,9 +6,9 @@ use std::str::FromStr as _;use ai_memory_core::{AgentKind, AuthLevel, Capability, FinishManagedRunRequest, FinishManagedRunResponse,- LinkManagedRunRequest, ManagedRunId, ManagedRunStatus, NewWorkstreamEvent,- PrepareManagedRunRequest, PrepareManagedRunResponse, Sanitizer, WorkstreamEventKind,- WorkstreamId,+ LinkManagedRunRequest, ManagedRunContextResponse, ManagedRunId, ManagedRunStatus,+ NewWorkstreamEvent, PrepareManagedRunRequest, PrepareManagedRunResponse, Sanitizer,+ WorkstreamEventKind, WorkstreamId,};use ai_memory_store::{FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, StoreError, WorkstreamSelection,@@ -51,6 +51,11 @@ pub fn workstream_router(state: WorkstreamState) -> Router {.route("/workstream/runs", post(prepare_run)).route("/workstream/runs/{run_id}", get(run_status)).route("/workstream/runs/{run_id}/heartbeat", post(heartbeat_run))+ .route("/workstream/runs/{run_id}/context", post(run_context))+ .route(+ "/workstream/runs/{run_id}/context/accept",+ post(accept_run_context),+ ).route("/workstream/runs/{run_id}/link", post(link_run)).route("/workstream/runs/{run_id}/finish", post(finish_run)).route("/workstream/{workstream_id}/events", get(search_events))@@ -127,6 +132,7 @@ async fn prepare_run(| AgentKind::Codex| AgentKind::OpenCode| AgentKind::Pi+ | AgentKind::Crush| AgentKind::Omp) {return error(@@ -134,6 +140,26 @@ async fn prepare_run("managed run requires a supported command-line harness",);}+ const AUTO_AGENTS: [AgentKind; 5] = [+ AgentKind::ClaudeCode,+ AgentKind::Codex,+ AgentKind::OpenCode,+ AgentKind::Pi,+ AgentKind::Crush,+ ];+ if request.automatic_harness+ && (!AUTO_AGENTS.contains(&request.agent)+ || !request.available_agents.contains(&request.agent)+ || request+ .available_agents+ .iter()+ .any(|agent| !AUTO_AGENTS.contains(agent)))+ {+ return error(+ StatusCode::BAD_REQUEST,+ "automatic managed run requires supported checkout-local harnesses",+ );+ }for (label, value) in [("workspace", request.workspace.as_str()),("project", request.project.as_str()),@@ -178,6 +204,8 @@ async fn prepare_run(worktree_fingerprint: request.worktree_fingerprint,cwd: request.cwd,agent: request.agent,+ automatic_harness: request.automatic_harness,+ available_agents: request.available_agents,selection,lease_owner: request.lease_owner,})@@ -187,10 +215,12 @@ async fn prepare_run(workstream_id: prepared.workstream_id,workstream_name: prepared.workstream_name,run_id: prepared.run_id,+ resolved_agent: Some(prepared.agent),native_session_id: prepared.native_session_id,source_cursor: prepared.source_cursor,sync_after: prepared.sync_after,sync_through: prepared.sync_through,+ may_adopt_existing_session: prepared.may_adopt_existing_session,}).into_response(),Err(failure) => store_error_response(failure),@@ -243,6 +273,71 @@ async fn heartbeat_run(}}+async fn run_context(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_run_id): AxumPath<String>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ let run_id = match parse_run_id(&raw_run_id) {+ Ok(id) => id,+ Err(response) => return response.into_response(),+ };+ let context = match state.reader.managed_run_context(run_id, 256).await {+ Ok(Some(context)) => context,+ Ok(None) => return error(StatusCode::NOT_FOUND, "active managed run not found"),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ if context.agent != AgentKind::Crush {+ return error(+ StatusCode::BAD_REQUEST,+ "direct managed context is only supported for Crush",+ );+ }+ if context.context_delivered {+ return Json(ManagedRunContextResponse { context: None }).into_response();+ }+ let rendered = crate::router::render_managed_context(+ &context.events,+ &context.workstream_name,+ context.workstream_id,+ context.sync_after,+ );+ Json(ManagedRunContextResponse { context: rendered }).into_response()+}++async fn accept_run_context(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_run_id): AxumPath<String>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ let run_id = match parse_run_id(&raw_run_id) {+ Ok(id) => id,+ Err(response) => return response.into_response(),+ };+ let status = match state.reader.managed_run_status(run_id).await {+ Ok(Some(status)) => status,+ Ok(None) => return error(StatusCode::NOT_FOUND, "managed run not found"),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ if status.agent != AgentKind::Crush {+ return error(+ StatusCode::BAD_REQUEST,+ "direct managed context is only supported for Crush",+ );+ }+ match state.writer.accept_managed_run_context(run_id).await {+ Ok(true) => StatusCode::NO_CONTENT.into_response(),+ Ok(false) => error(StatusCode::CONFLICT, "managed run lease is not active"),+ Err(failure) => store_error_response(failure),+ }+}+#[derive(Debug, Default, Deserialize)]struct EventQuery {#[serde(default)]@@ -603,3 +698,217 @@ fn truncate_owned(value: &mut String, max: usize) {value.truncate(end);value.push_str("\n[truncated by ai-memory]");}++#[cfg(test)]+mod tests {+ use ai_memory_store::Store;+ use axum::body::to_bytes;+ use tempfile::TempDir;++ use super::*;++ fn test_state(store: &Store, data_dir: &Path) -> WorkstreamState {+ WorkstreamState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ sanitizer: Sanitizer::default(),+ data_dir: data_dir.to_path_buf(),+ }+ }++ fn prepare_input(+ workspace_id: ai_memory_core::WorkspaceId,+ project_id: ai_memory_core::ProjectId,+ agent: AgentKind,+ owner: &str,+ ) -> PrepareWorkstreamRun {+ PrepareWorkstreamRun {+ workspace_id,+ project_id,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::Current,+ lease_owner: owner.into(),+ }+ }++ async fn seed_scope(store: &Store) -> (ai_memory_core::WorkspaceId, ai_memory_core::ProjectId) {+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project_id = store+ .writer+ .get_or_create_project(workspace_id, "managed", None)+ .await+ .unwrap();+ (workspace_id, project_id)+ }++ #[tokio::test]+ async fn automatic_prepare_returns_the_established_available_harness() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (workspace_id, project_id) = seed_scope(&store).await;+ let claude = store+ .writer+ .prepare_workstream_run(prepare_input(+ workspace_id,+ project_id,+ AgentKind::ClaudeCode,+ "claude",+ ))+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: claude.run_id,+ native_session_id: Some("claude-current".into()),+ source_cursor: Some("cursor".into()),+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let response = prepare_run(+ State(state),+ None,+ Json(PrepareManagedRunRequest {+ workspace: "default".into(),+ project: "managed".into(),+ cwd: "/repo".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ agent: AgentKind::Codex,+ automatic_harness: true,+ available_agents: vec![AgentKind::Codex, AgentKind::ClaudeCode],+ workstream: None,+ new_workstream: None,+ lease_owner: "automatic".into(),+ }),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();+ assert_eq!(prepared.resolved_agent, Some(AgentKind::ClaudeCode));+ assert_eq!(+ prepared.native_session_id.as_deref(),+ Some("claude-current")+ );+ assert!(!prepared.may_adopt_existing_session);+ }++ #[tokio::test]+ async fn crush_context_fetch_is_repeatable_until_explicit_accept() {+ let temp = TempDir::new().unwrap();+ let store = Store::open(temp.path()).unwrap();+ let state = test_state(&store, temp.path());+ let (workspace_id, project_id) = seed_scope(&store).await;+ let codex = store+ .writer+ .prepare_workstream_run(prepare_input(+ workspace_id,+ project_id,+ AgentKind::Codex,+ "codex",+ ))+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: codex.run_id,+ native_session_id: Some("codex-native".into()),+ source_cursor: None,+ events: vec![NewWorkstreamEvent {+ event_id: "codex:assistant:1".into(),+ agent: AgentKind::Codex,+ native_session_id: "codex-native".into(),+ source_record_id: None,+ kind: WorkstreamEventKind::Message,+ role: Some("assistant".into()),+ content: "AMWS-CODEX-SENTINEL".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ }],+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();+ let crush = store+ .writer+ .prepare_workstream_run(prepare_input(+ workspace_id,+ project_id,+ AgentKind::Crush,+ "crush",+ ))+ .await+ .unwrap();++ let fetch = || {+ run_context(+ State(state.clone()),+ None,+ AxumPath(crush.run_id.to_string()),+ )+ };+ for _ in 0..2 {+ let response = fetch().await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();+ let packet: ManagedRunContextResponse = serde_json::from_slice(&body).unwrap();+ assert!(+ packet+ .context+ .as_deref()+ .is_some_and(|context| context.contains("AMWS-CODEX-SENTINEL"))+ );+ assert!(+ !store+ .reader+ .managed_run_status(crush.run_id)+ .await+ .unwrap()+ .unwrap()+ .context_delivered+ );+ }++ let accepted = accept_run_context(+ State(state.clone()),+ None,+ AxumPath(crush.run_id.to_string()),+ )+ .await;+ assert_eq!(accepted.status(), StatusCode::NO_CONTENT);+ assert!(+ store+ .reader+ .managed_run_status(crush.run_id)+ .await+ .unwrap()+ .unwrap()+ .context_delivered+ );++ let response = fetch().await;+ assert_eq!(response.status(), StatusCode::OK);+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();+ let packet: ManagedRunContextResponse = serde_json::from_slice(&body).unwrap();+ assert!(packet.context.is_none());+ }+}diff --git a/crates/ai-memory-store/migrations/V32__sessions_crush_agent_kind.sql b/crates/ai-memory-store/migrations/V32__sessions_crush_agent_kind.sqlnew file mode 100644index 00000000..cd8b7e61--- /dev/null+++ b/crates/ai-memory-store/migrations/V32__sessions_crush_agent_kind.sql@@ -0,0 +1,53 @@+-- Expand sessions.agent_kind CHECK for Charmbracelet Crush.+--+-- Every sessions-table rebuild must retain the complete AgentKind set and the+-- V18/V22 scope-pairing triggers. Even though managed Crush runs use the+-- workstream tables, every shared core AgentKind must remain persistable by+-- the session APIs.++PRAGMA foreign_keys = OFF;++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;++CREATE TABLE sessions_new (+ id BLOB PRIMARY KEY NOT NULL,+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','other')),+ cwd TEXT,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL+);++INSERT INTO sessions_new SELECT * FROM sessions;++DROP TABLE sessions;++ALTER TABLE sessions_new RENAME TO sessions;++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);+CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);+CREATE INDEX idx_sessions_scope_ended+ ON sessions(workspace_id, project_id, ended_at ASC)+ WHERE ended_at IS NOT NULL;++CREATE TRIGGER sessions_ws_proj_pairing_ai+BEFORE INSERT ON sessions+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)+BEGIN+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');+END;++CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai+BEFORE INSERT ON auto_improve_scheduler_claims+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)+BEGIN+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');+END;++PRAGMA foreign_keys = ON;diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 0bd1b827..b1ab282b 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -3316,6 +3316,8 @@ mod tests {worktree_fingerprint: "worktree".into(),cwd: "/repo".into(),agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),selection: WorkstreamSelection::Current,lease_owner: "test:1".into(),};@@ -3324,6 +3326,7 @@ mod tests {.prepare_workstream_run(prepare.clone()).await.unwrap();+ assert!(run.may_adopt_existing_session);let busy = store.writer.prepare_workstream_run(prepare.clone())@@ -3413,6 +3416,7 @@ mod tests {.prepare_workstream_run(prepare.clone()).await.unwrap();+ assert!(!next.may_adopt_existing_session);assert_eq!(next.workstream_id, run.workstream_id);assert_eq!(next.native_session_id.as_deref(), Some("native-1"));assert_eq!(next.source_cursor.as_deref(), Some("cursor-1"));@@ -3500,6 +3504,154 @@ mod tests {assert_eq!(undelivered.sync_through, 1);}+ #[tokio::test]+ async fn managed_adoption_stops_after_any_harness_links_the_workstream() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let workspace = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(workspace, "managed", None)+ .await+ .unwrap();+ let prepare = |agent, owner: &str| PrepareWorkstreamRun {+ workspace_id: workspace,+ project_id: project,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::Current,+ lease_owner: owner.into(),+ };++ let blank = store+ .writer+ .prepare_workstream_run(prepare(AgentKind::Codex, "blank"))+ .await+ .unwrap();+ assert!(blank.may_adopt_existing_session);+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: blank.run_id,+ native_session_id: None,+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let first = store+ .writer+ .prepare_workstream_run(prepare(AgentKind::ClaudeCode, "claude"))+ .await+ .unwrap();+ assert!(+ first.may_adopt_existing_session,+ "a blank run with no native session or portable history remains adoptable"+ );+ assert!(+ store+ .writer+ .link_managed_run_session(first.run_id, AgentKind::ClaudeCode, "claude-native")+ .await+ .unwrap()+ );+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: first.run_id,+ native_session_id: Some("claude-native".into()),+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let codex = store+ .writer+ .prepare_workstream_run(prepare(AgentKind::Codex, "codex"))+ .await+ .unwrap();+ assert!(codex.native_session_id.is_none());+ assert!(+ !codex.may_adopt_existing_session,+ "an established Claude workstream must start a fresh Codex session"+ );+ }++ #[tokio::test]+ async fn automatic_run_prefers_newest_linked_available_harness() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let workspace = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(workspace, "managed", None)+ .await+ .unwrap();+ let base = |agent, owner: &str| PrepareWorkstreamRun {+ workspace_id: workspace,+ project_id: project,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent,+ automatic_harness: false,+ available_agents: Vec::new(),+ selection: WorkstreamSelection::Current,+ lease_owner: owner.into(),+ };+ let claude = store+ .writer+ .prepare_workstream_run(base(AgentKind::ClaudeCode, "claude"))+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: claude.run_id,+ native_session_id: Some("claude-current".into()),+ source_cursor: Some("cursor".into()),+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();++ let mut automatic = base(AgentKind::Codex, "automatic");+ automatic.automatic_harness = true;+ automatic.available_agents = vec![AgentKind::Codex, AgentKind::ClaudeCode];+ let resumed = store+ .writer+ .prepare_workstream_run(automatic)+ .await+ .unwrap();+ assert_eq!(resumed.agent, AgentKind::ClaudeCode);+ assert_eq!(resumed.native_session_id.as_deref(), Some("claude-current"));+ assert_eq!(resumed.source_cursor.as_deref(), Some("cursor"));+ assert!(!resumed.may_adopt_existing_session);+ }+#[tokio::test]async fn managed_workstreams_are_isolated_across_workspaces() {let tmp = TempDir::new().unwrap();@@ -3529,6 +3681,8 @@ mod tests {worktree_fingerprint: "same-worktree".into(),cwd: "/same/path".into(),agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),selection: WorkstreamSelection::Current,lease_owner: workspace_name.into(),})diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 4fbf3b00..cd6f70c1 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -2559,21 +2559,7 @@ mod tests {#[test]fn begin_session_accepts_all_supported_agent_kinds() {let (_tmp, mut conn, ws, proj) = fresh_db();- for agent_kind in [- AgentKind::ClaudeCode,- AgentKind::Codex,- AgentKind::OpenCode,- AgentKind::Cursor,- AgentKind::GeminiCli,- AgentKind::ClaudeDesktop,- AgentKind::OpenClaw,- AgentKind::AntigravityCli,- AgentKind::Omp,- AgentKind::Pi,- AgentKind::Grok,- AgentKind::Devin,- AgentKind::Other,- ] {+ for agent_kind in AgentKind::ALL {let sid = SessionId::new();begin_session(&mut conn,diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex aa137aa8..6c452c57 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -41,6 +41,10 @@ pub struct PrepareWorkstreamRun {pub cwd: String,/// Harness being launched.pub agent: AgentKind,+ /// Prefer the newest linked harness that is also available locally.+ pub automatic_harness: bool,+ /// Harnesses with checkout-local resumable sessions.+ pub available_agents: Vec<AgentKind>,/// Workstream selection behavior.pub selection: WorkstreamSelection,/// Diagnostic lease owner.@@ -56,6 +60,8 @@ pub struct PreparedWorkstreamRun {pub workstream_name: String,/// New invocation/lease id.pub run_id: ManagedRunId,+ /// Harness selected for this invocation.+ pub agent: AgentKind,/// Current native session for the requested harness.pub native_session_id: Option<String>,/// Last adapter cursor for that native session.@@ -64,6 +70,9 @@ pub struct PreparedWorkstreamRun {pub sync_after: i64,/// Workstream high-water mark assigned to the launch.pub sync_through: i64,+ /// Whether no harness has established this workstream yet, allowing the+ /// launcher to offer checkout-local native session adoption.+ pub may_adopt_existing_session: bool,}/// Store-level finish input after the raw segment has been made durable.@@ -188,12 +197,17 @@ pub(crate) fn prepare_run(params![workstream_id.as_bytes()],|row| row.get(0),)?;+ let agent = if input.automatic_harness {+ newest_available_agent(&tx, workstream_id, &input.available_agents)?.unwrap_or(input.agent)+ } else {+ input.agent+ };let native: Option<(String, Option<String>, i64)> = tx.query_row("SELECT native_session_id, source_cursor, delivery_cursor \FROM workstream_native_sessions \WHERE workstream_id = ?1 AND agent_kind = ?2 AND is_current = 1",- params![workstream_id.as_bytes(), input.agent.as_str()],+ params![workstream_id.as_bytes(), agent.as_str()],|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),).optional()?;@@ -201,6 +215,16 @@ pub(crate) fn prepare_run(.map_or((None, None, 0), |(session, cursor, delivery)| {(Some(session), cursor, delivery)});+ let established: i64 = tx.query_row(+ "SELECT CASE WHEN \+ EXISTS(SELECT 1 FROM workstream_native_sessions WHERE workstream_id = ?1) \+ OR EXISTS(SELECT 1 FROM workstream_events \+ WHERE workstream_id = ?1 \+ AND kind IN ('message', 'tool_call', 'tool_result', 'compaction')) \+ THEN 1 ELSE 0 END",+ params![workstream_id.as_bytes()],+ |row| row.get(0),+ )?;let run_id = ManagedRunId::new();tx.execute(@@ -211,7 +235,7 @@ pub(crate) fn prepare_run(params![run_id.as_bytes(),workstream_id.as_bytes(),- input.agent.as_str(),+ agent.as_str(),input.lease_owner,native_session_id,sync_after,@@ -230,13 +254,36 @@ pub(crate) fn prepare_run(workstream_id,workstream_name,run_id,+ agent,native_session_id,source_cursor,sync_after,sync_through: latest_sequence,+ may_adopt_existing_session: established == 0,})}+fn newest_available_agent(+ tx: &Transaction<'_>,+ workstream_id: WorkstreamId,+ available: &[AgentKind],+) -> StoreResult<Option<AgentKind>> {+ let mut statement = tx.prepare(+ "SELECT agent_kind FROM workstream_native_sessions \+ WHERE workstream_id = ?1 AND is_current = 1 ORDER BY updated_at DESC",+ )?;+ let rows = statement.query_map(params![workstream_id.as_bytes()], |row| {+ row.get::<_, String>(0)+ })?;+ for row in rows {+ let agent = AgentKind::from_wire(&row?);+ if available.contains(&agent) {+ return Ok(Some(agent));+ }+ }+ Ok(None)+}+fn select_workstream(tx: &Transaction<'_>,input: &PrepareWorkstreamRun,diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex 0719c3f9..53aa9b33 100644--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@ -18,6 +18,8 @@ pub enum ManagedHarness {OpenCode,/// Pi coding agent.Pi,+ /// Charmbracelet Crush.+ Crush,/// Oh My Pi.Omp,}@@ -31,6 +33,7 @@ impl ManagedHarness {"codex" => Some(Self::Codex),"opencode" | "open-code" => Some(Self::OpenCode),"pi" => Some(Self::Pi),+ "crush" => Some(Self::Crush),"omp" | "oh-my-pi" => Some(Self::Omp),_ => None,}@@ -44,6 +47,7 @@ impl ManagedHarness {Self::Codex => AgentKind::Codex,Self::OpenCode => AgentKind::OpenCode,Self::Pi => AgentKind::Pi,+ Self::Crush => AgentKind::Crush,Self::Omp => AgentKind::Omp,}}@@ -56,6 +60,7 @@ impl ManagedHarness {Self::Codex => "codex",Self::OpenCode => "opencode",Self::Pi => "pi",+ Self::Crush => "crush",Self::Omp => "omp",}}@@ -68,6 +73,7 @@ impl ManagedHarness {Self::Codex => "codex",Self::OpenCode => "opencode",Self::Pi => "pi",+ Self::Crush => "crush",Self::Omp => "omp",}}@@ -113,6 +119,7 @@ pub fn build_launch_plan(let mut args = native_args;let session_dir = match harness {ManagedHarness::Pi | ManagedHarness::Omp => flag_path(&args, &["--session-dir"]),+ ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),_ => None,}.or_else(|| environment_session_dir(harness));@@ -172,6 +179,13 @@ pub fn build_launch_plan(args.extend([OsString::from(selector), OsString::from(&id)]);expected = Some(id);}+ ManagedHarness::Crush => {+ if let Some(id) = linked_session_id {+ args.insert(0, OsString::from(id));+ args.insert(0, OsString::from("--session"));+ expected = Some(id.to_string());+ }+ }ManagedHarness::Omp => {if let Some(id) = linked_session_id {args.push(OsString::from(format!("--resume={id}")));@@ -190,6 +204,44 @@ pub fn build_launch_plan(})}+/// Apply the wrapper-owned dangerous-mode flag using native harness syntax.+/// Harnesses that already execute tools without a permission gate need no+/// extra argument.+pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {+ let flag = match harness {+ ManagedHarness::Claude => Some("--dangerously-skip-permissions"),+ ManagedHarness::Codex => Some("--dangerously-bypass-approvals-and-sandbox"),+ ManagedHarness::OpenCode => Some("--auto"),+ ManagedHarness::Pi => Some("--approve"),+ ManagedHarness::Crush => Some("--yolo"),+ ManagedHarness::Omp => None,+ };+ if let Some(flag) = flag+ && !has_flag(args, &[flag])+ {+ args.push(OsString::from(flag));+ }+}++/// Whether a native invocation may use ai-memory's one-time adoption prompt.+/// Explicit selectors and utility/ephemeral invocations always pass through.+#[must_use]+pub fn allows_native_session_adoption(harness: ManagedHarness, native_args: &[OsString]) -> bool {+ launch_mode(harness, native_args) == LaunchMode::Session+ && !has_explicit_session_selector(harness, native_args)+ && !noninteractive_invocation(harness, native_args)+}++fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> bool {+ match harness {+ ManagedHarness::Claude => has_flag(args, &["--print", "-p"]),+ ManagedHarness::Codex => first_arg_is(args, "exec"),+ ManagedHarness::OpenCode => first_arg_is(args, "run"),+ ManagedHarness::Crush => first_arg_is(args, "run"),+ ManagedHarness::Pi | ManagedHarness::Omp => has_flag(args, &["--print", "-p"]),+ }+}+fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {if has_flag(args, &["--help", "-h", "--version", "-v"])|| has_flag(args, &["--no-session", "--no-session-persistence"])@@ -272,6 +324,21 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {ManagedHarness::Pi => {["install", "remove", "uninstall", "update", "list", "config"].as_slice()}+ ManagedHarness::Crush => [+ "completion",+ "dirs",+ "help",+ "login",+ "logout",+ "logs",+ "models",+ "projects",+ "server",+ "session",+ "stats",+ "update-providers",+ ]+ .as_slice(),ManagedHarness::Omp => ["acp","agents",@@ -328,6 +395,7 @@ fn has_explicit_session_selector(harness: ManagedHarness, args: &[OsString]) ->"--fork",],),+ ManagedHarness::Crush => has_flag(args, &["--session", "-s", "--continue", "-C"]),ManagedHarness::Omp => has_flag(args, &["--resume", "-r", "--continue", "-c"]),}}@@ -349,6 +417,7 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str}ManagedHarness::OpenCode => flag_value(args, &["--session", "-s"]),ManagedHarness::Pi => flag_value(args, &["--session", "--session-id"]),+ ManagedHarness::Crush => flag_value(args, &["--session", "-s"]),ManagedHarness::Omp => flag_value(args, &["--resume", "-r"]),}}@@ -427,6 +496,7 @@ fn environment_session_dir_with(ManagedHarness::OpenCode => value("XDG_DATA_HOME").map(|dir| dir.join("opencode")),ManagedHarness::Pi => value("PI_CODING_AGENT_SESSION_DIR").or_else(|| value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions"))),+ ManagedHarness::Crush => None,ManagedHarness::Omp => value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions")),}}@@ -539,6 +609,46 @@ mod tests {assert_eq!(plan.expected_session_id.as_deref(), Some("chosen"));}+ #[test]+ fn adoption_is_only_allowed_for_session_launches_without_a_selector() {+ assert!(allows_native_session_adoption(+ ManagedHarness::Codex,+ &[OsString::from("--yolo")]+ ));+ assert!(allows_native_session_adoption(+ ManagedHarness::OpenCode,+ &[OsString::from("--auto")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::Codex,+ &[OsString::from("resume")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::Claude,+ &[OsString::from("--continue")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::Pi,+ &[OsString::from("--no-session")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::Codex,+ &[OsString::from("login")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::Codex,+ &[OsString::from("exec"), OsString::from("continue here")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::Claude,+ &[OsString::from("--print"), OsString::from("continue here")]+ ));+ assert!(!allows_native_session_adoption(+ ManagedHarness::OpenCode,+ &[OsString::from("run"), OsString::from("continue here")]+ ));+ }+#[test]fn opencode_resume_places_selector_after_run_subcommand() {let plan = build_launch_plan(@@ -583,6 +693,57 @@ mod tests {);}+ #[test]+ fn crush_resumes_linked_session_and_observes_data_directory() {+ let plan = build_launch_plan(+ ManagedHarness::Crush,+ None,+ vec![+ OsString::from("--data-dir"),+ OsString::from("/tmp/crush-data"),+ ],+ Some("crush-id"),+ )+ .unwrap();+ assert_eq!(+ strings(&plan.args),+ ["--session", "crush-id", "--data-dir", "/tmp/crush-data"]+ );+ assert_eq!(plan.expected_session_id.as_deref(), Some("crush-id"));+ assert_eq!(+ plan.session_dir.as_deref(),+ Some(std::path::Path::new("/tmp/crush-data"))+ );+ }++ #[test]+ fn wrapper_yolo_uses_each_harness_native_flag_without_duplicates() {+ for (harness, expected) in [+ (+ ManagedHarness::Claude,+ Some("--dangerously-skip-permissions"),+ ),+ (+ ManagedHarness::Codex,+ Some("--dangerously-bypass-approvals-and-sandbox"),+ ),+ (ManagedHarness::OpenCode, Some("--auto")),+ (ManagedHarness::Pi, Some("--approve")),+ (ManagedHarness::Crush, Some("--yolo")),+ (ManagedHarness::Omp, None),+ ] {+ let mut args = Vec::new();+ apply_yolo(harness, &mut args);+ apply_yolo(harness, &mut args);+ assert_eq!(+ strings(&args),+ expected.into_iter().collect::<Vec<_>>(),+ "{} yolo mapping",+ harness.as_str()+ );+ }+ }+#[test]fn omp_resume_uses_equals_form_without_reordering_native_args() {let plan = build_launch_plan(diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rsindex c4eed954..4a544e67 100644--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@ -4,8 +4,12 @@ mod harness;mod repository;mod transcript;-pub use harness::{LaunchMode, LaunchPlan, ManagedHarness, build_launch_plan};+pub use harness::{+ LaunchMode, LaunchPlan, ManagedHarness, allows_native_session_adoption, apply_yolo,+ build_launch_plan,+};pub use repository::{RepositoryIdentity, inspect_repository};pub use transcript::{- ExportedTranscript, discover_native_session, export_transcript, wait_for_transcript_flush,+ ExportedTranscript, NativeSessionCandidate, discover_native_session, export_transcript,+ list_native_sessions, wait_for_transcript_flush,};diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 919ef9ec..1880caa2 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -1,5 +1,6 @@//! Incremental, read-only extraction from native harness session stores.+use std::collections::HashSet;use std::fs::{self, File};use std::io::{BufRead as _, BufReader, Seek as _, SeekFrom};use std::path::{Path, PathBuf};@@ -16,6 +17,16 @@ use crate::ManagedHarness;const MAX_SCAN_FILES: usize = 50_000;const MAX_EVENT_BYTES: usize = 128 * 1024;+const MAX_NATIVE_SESSION_ID_BYTES: usize = 512;++/// Checkout-local native session that can seed an otherwise-empty workstream.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NativeSessionCandidate {+ /// Harness-native session identifier.+ pub native_session_id: String,+ /// Last observed native-store update time.+ pub updated_at: SystemTime,+}/// Incremental transcript export produced after a managed child exits.#[derive(Debug, Clone, Default)]@@ -37,7 +48,7 @@ struct FileCursor {}#[derive(Debug, Clone, Serialize, Deserialize, Default)]-struct OpenCodeCursor {+struct SqlCursor {updated: i64,id: String,}@@ -54,6 +65,9 @@ pub async fn export_transcript(if harness == ManagedHarness::OpenCode {return export_opencode(home, session_dir, native_session_id, source_cursor);}+ if harness == ManagedHarness::Crush {+ return export_crush(cwd, session_dir, native_session_id, source_cursor);+ }let path = locate_session_file(harness, home, cwd, session_dir, native_session_id)?.ok_or_else(|| anyhow!("native transcript for {native_session_id} was not found"))?;export_jsonl(harness, &path, native_session_id, source_cursor)@@ -71,9 +85,12 @@ pub async fn discover_native_session(if harness == ManagedHarness::OpenCode {return discover_opencode(home, session_dir, cwd, started_at);}+ if harness == ManagedHarness::Crush {+ return discover_crush(cwd, session_dir, started_at);+ }let root = session_root(harness, home, session_dir);let mut candidates = collect_files(&root, |path| transcript_file(harness, path))?;- candidates.sort_by_key(modified);+ candidates.sort_by_key(|path| modified(path));candidates.reverse();for path in candidates.into_iter().take(512) {if modified(&path).is_some_and(|time| time + Duration::from_secs(2) < started_at) {@@ -88,6 +105,56 @@ pub async fn discover_native_session(Ok(None)}+/// List newest native sessions whose recorded working directory matches the+/// current checkout. Native stores are opened read-only and unrelated paths are+/// excluded before candidates reach the launcher prompt.+pub async fn list_native_sessions(+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ limit: usize,+) -> Result<Vec<NativeSessionCandidate>> {+ if limit == 0 {+ return Ok(Vec::new());+ }+ if harness == ManagedHarness::OpenCode {+ return list_opencode_sessions(home, session_dir, cwd, limit);+ }+ if harness == ManagedHarness::Crush {+ return list_crush_sessions(cwd, session_dir, limit);+ }++ let root = session_root(harness, home, session_dir);+ let mut files = collect_files(&root, |path| transcript_file(harness, path))?;+ files.sort_by_key(|path| modified(path));+ files.reverse();+ let mut seen = HashSet::new();+ let mut sessions = Vec::new();+ for path in files.into_iter().take(2_000) {+ let Some(updated_at) = modified(&path) else {+ continue;+ };+ let Ok(Some((native_session_id, recorded_cwd))) = session_header(harness, &path) else {+ continue;+ };+ if !same_path(&recorded_cwd, cwd)+ || !valid_native_session_id(&native_session_id)+ || !seen.insert(native_session_id.clone())+ {+ continue;+ }+ sessions.push(NativeSessionCandidate {+ native_session_id,+ updated_at,+ });+ if sessions.len() >= limit {+ break;+ }+ }+ Ok(sessions)+}+/// Wait briefly for buffered transcript writers to settle before importing.pub async fn wait_for_transcript_flush(harness: ManagedHarness,@@ -100,6 +167,8 @@ pub async fn wait_for_transcript_flush(for _ in 0..10 {let current = if harness == ManagedHarness::OpenCode {opencode_updated(home, session_dir, native_session_id)?.map(|value| value.to_string())+ } else if harness == ManagedHarness::Crush {+ crush_updated(cwd, session_dir, native_session_id)?.map(|value| value.to_string())} else {locate_session_file(harness, home, cwd, session_dir, native_session_id)?.and_then(|path| {@@ -184,7 +253,12 @@ fn export_jsonl(&mut events,&mut losses,),- ManagedHarness::OpenCode => unreachable!("OpenCode uses its SQLite adapter"),+ ManagedHarness::OpenCode | ManagedHarness::Crush => {+ return Err(anyhow!(+ "{} transcripts must use their SQLite adapter",+ harness.as_str()+ ));+ }}}Ok(ExportedTranscript {@@ -588,7 +662,7 @@ fn export_opencode()})?;let cursor = source_cursor- .and_then(|raw| serde_json::from_str::<OpenCodeCursor>(raw).ok())+ .and_then(|raw| serde_json::from_str::<SqlCursor>(raw).ok()).unwrap_or_default();let mut statement = connection.prepare("SELECT p.id, p.time_updated, m.data, p.data@@ -609,7 +683,7 @@ fn export_opencode(let mut next_cursor = cursor;for row in rows {let (id, updated, message_raw, part_raw) = row?;- next_cursor = OpenCodeCursor {+ next_cursor = SqlCursor {updated,id: id.clone(),};@@ -631,6 +705,155 @@ fn export_opencode(})}+fn export_crush(+ cwd: &Path,+ session_dir: Option<&Path>,+ session: &str,+ source_cursor: Option<&str>,+) -> Result<ExportedTranscript> {+ let db = crush_db(cwd, session_dir);+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )+ .with_context(|| format!("opening Crush session database {} read-only", db.display()))?;+ let cursor = source_cursor+ .and_then(|raw| serde_json::from_str::<SqlCursor>(raw).ok())+ .unwrap_or_default();+ let mut statement = connection.prepare(+ "SELECT id, role, parts, updated_at, is_summary_message \+ FROM messages \+ WHERE session_id = ?1 \+ AND (updated_at > ?2 OR (updated_at = ?2 AND id > ?3)) \+ ORDER BY updated_at, id",+ )?;+ let rows = statement.query_map(params![session, cursor.updated, cursor.id], |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, i64>(3)?,+ row.get::<_, i64>(4)?,+ ))+ })?;+ let mut events = Vec::new();+ let mut losses = Vec::new();+ let mut next_cursor = cursor;+ for row in rows {+ let (id, role, parts_raw, updated, is_summary) = row?;+ next_cursor = SqlCursor {+ updated,+ id: id.clone(),+ };+ let Ok(parts) = serde_json::from_str::<Value>(&parts_raw) else {+ losses.push(format!("malformed Crush message parts for {id}"));+ continue;+ };+ let Some(parts) = parts.as_array() else {+ losses.push(format!("malformed Crush message parts for {id}"));+ continue;+ };+ parse_crush_parts(+ &role,+ parts,+ is_summary != 0,+ session,+ &id,+ &mut events,+ &mut losses,+ );+ }+ Ok(ExportedTranscript {+ native_session_id: session.to_string(),+ source_cursor: Some(serde_json::to_string(&next_cursor)?),+ events,+ losses: deduplicate_losses(losses),+ })+}++fn parse_crush_parts(+ role: &str,+ parts: &[Value],+ is_summary: bool,+ session: &str,+ message_id: &str,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ for (index, part) in parts.iter().enumerate() {+ let kind = part.get("type").and_then(Value::as_str).unwrap_or_default();+ let data = part.get("data").unwrap_or(&Value::Null);+ match kind {+ "text" if matches!(role, "user" | "assistant") => {+ if let Some(content) = first_string(data, &["text", "content"]) {+ push_event(+ events,+ AgentKind::Crush,+ session,+ message_id,+ index,+ if is_summary {+ WorkstreamEventKind::Compaction+ } else {+ WorkstreamEventKind::Message+ },+ Some(role),+ content,+ None,+ json!({}),+ );+ }+ }+ "tool_call" => {+ if data.get("finished").and_then(Value::as_bool) == Some(false) {+ losses.push("unfinished Crush tool calls were intentionally excluded".into());+ continue;+ }+ let name = data.get("name").and_then(Value::as_str).unwrap_or("tool");+ let input = data.get("input").map(value_text).unwrap_or_default();+ push_event(+ events,+ AgentKind::Crush,+ session,+ message_id,+ index,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{name}: {input}"),+ None,+ json!({"tool": name}),+ );+ }+ "tool_result" => {+ let name = data.get("name").and_then(Value::as_str).unwrap_or("tool");+ let content = data+ .get("content")+ .or_else(|| data.get("data"))+ .map(value_text)+ .unwrap_or_default();+ push_event(+ events,+ AgentKind::Crush,+ session,+ message_id,+ index,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ &content,+ None,+ json!({+ "tool": name,+ "is_error": data.get("is_error").and_then(Value::as_bool)+ }),+ );+ }+ "reasoning" => losses.push("Crush hidden reasoning was intentionally excluded".into()),+ "binary" => losses.push("Crush binary attachment was intentionally excluded".into()),+ _ => {}+ }+ }+}+fn parse_opencode(message: &Value,part: &Value,@@ -827,7 +1050,7 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(Stringvalue.get("id").and_then(Value::as_str),value.get("cwd").and_then(Value::as_str),),- ManagedHarness::OpenCode => (None, None),+ ManagedHarness::OpenCode | ManagedHarness::Crush => (None, None),};if let (Some(id), Some(cwd)) = (id, cwd) {return Ok(Some((id.to_string(), PathBuf::from(cwd))));@@ -864,6 +1087,126 @@ fn discover_opencode(}}+fn list_opencode_sessions(+ home: &Path,+ session_dir: Option<&Path>,+ cwd: &Path,+ limit: usize,+) -> Result<Vec<NativeSessionCandidate>> {+ let db = opencode_db(home, session_dir);+ if !db.is_file() {+ return Ok(Vec::new());+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ let mut statement = connection.prepare(+ "SELECT id, time_updated FROM session \+ WHERE directory = ?1 ORDER BY time_updated DESC LIMIT ?2",+ )?;+ let rows = statement.query_map(params![cwd.to_string_lossy(), limit as i64], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))+ })?;+ let mut sessions = Vec::new();+ for row in rows {+ let (native_session_id, updated_millis) = row?;+ let Ok(updated_millis) = u64::try_from(updated_millis) else {+ continue;+ };+ if !valid_native_session_id(&native_session_id) {+ continue;+ }+ let Some(updated_at) = UNIX_EPOCH.checked_add(Duration::from_millis(updated_millis)) else {+ continue;+ };+ sessions.push(NativeSessionCandidate {+ native_session_id,+ updated_at,+ });+ }+ Ok(sessions)+}++fn discover_crush(+ cwd: &Path,+ session_dir: Option<&Path>,+ started_at: SystemTime,+) -> Result<Option<String>> {+ Ok(list_crush_sessions(cwd, session_dir, 1)?+ .into_iter()+ .find(|candidate| candidate.updated_at + Duration::from_secs(2) >= started_at)+ .map(|candidate| candidate.native_session_id))+}++fn list_crush_sessions(+ cwd: &Path,+ session_dir: Option<&Path>,+ limit: usize,+) -> Result<Vec<NativeSessionCandidate>> {+ let db = crush_db(cwd, session_dir);+ if !db.is_file() {+ return Ok(Vec::new());+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ let mut statement = connection+ .prepare("SELECT id, updated_at FROM sessions ORDER BY updated_at DESC LIMIT ?1")?;+ let rows = statement.query_map([limit as i64], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))+ })?;+ let mut sessions = Vec::new();+ for row in rows {+ let (native_session_id, updated) = row?;+ if !valid_native_session_id(&native_session_id) {+ continue;+ }+ let Some(updated_at) = native_timestamp(updated) else {+ continue;+ };+ sessions.push(NativeSessionCandidate {+ native_session_id,+ updated_at,+ });+ }+ Ok(sessions)+}++fn crush_updated(cwd: &Path, session_dir: Option<&Path>, session: &str) -> Result<Option<i64>> {+ let db = crush_db(cwd, session_dir);+ if !db.is_file() {+ return Ok(None);+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ match connection.query_row(+ "SELECT updated_at FROM sessions WHERE id = ?1",+ [session],+ |row| row.get(0),+ ) {+ Ok(value) => Ok(Some(value)),+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),+ Err(error) => Err(error.into()),+ }+}++fn crush_db(cwd: &Path, session_dir: Option<&Path>) -> PathBuf {+ session_dir.unwrap_or(&cwd.join(".crush")).join("crush.db")+}++fn native_timestamp(value: i64) -> Option<SystemTime> {+ let value = u64::try_from(value).ok()?;+ if value < 100_000_000_000 {+ UNIX_EPOCH.checked_add(Duration::from_secs(value))+ } else {+ UNIX_EPOCH.checked_add(Duration::from_millis(value))+ }+}+fn opencode_updated(home: &Path, session_dir: Option<&Path>, session: &str) -> Result<Option<i64>> {let db = opencode_db(home, session_dir);if !db.is_file() {@@ -900,6 +1243,7 @@ fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&PathManagedHarness::Codex => home.join(".codex/sessions"),ManagedHarness::OpenCode => home.join(".local/share/opencode"),ManagedHarness::Pi => home.join(".pi/agent/sessions"),+ ManagedHarness::Crush => home.join(".crush"),ManagedHarness::Omp => home.join(".omp/agent/sessions"),}}@@ -986,10 +1330,17 @@ fn truncate_utf8(value: &str, max: usize) -> &str {&value[..end]}-fn modified(path: &PathBuf) -> Option<SystemTime> {+fn modified(path: &Path) -> Option<SystemTime> {fs::metadata(path).ok()?.modified().ok()}+fn valid_native_session_id(value: &str) -> bool {+ !value.trim().is_empty()+ && value.len() <= MAX_NATIVE_SESSION_ID_BYTES+ && !value.starts_with('-')+ && !value.chars().any(char::is_control)+}+fn same_path(left: &Path, right: &Path) -> bool {left.canonicalize().ok() == right.canonicalize().ok()}@@ -1008,6 +1359,174 @@ fn deduplicate_losses(losses: Vec<String>) -> Vec<String> {mod tests {use super::*;+ #[tokio::test]+ async fn jsonl_candidate_discovery_covers_every_file_adapter_and_checkout_scope() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let other = temp.path().join("other");+ fs::create_dir_all(&cwd).unwrap();+ fs::create_dir_all(&other).unwrap();++ for (harness, header) in [+ (+ ManagedHarness::Claude,+ json!({"sessionId":"claude-id","cwd":cwd}),+ ),+ (+ ManagedHarness::Codex,+ json!({"type":"session_meta","payload":{"id":"codex-id","cwd":cwd}}),+ ),+ (+ ManagedHarness::Pi,+ json!({"type":"session","id":"pi-id","cwd":cwd}),+ ),+ (+ ManagedHarness::Omp,+ json!({"type":"session","id":"omp-id","cwd":cwd}),+ ),+ ] {+ let root = temp.path().join(harness.as_str());+ fs::create_dir_all(&root).unwrap();+ fs::write(root.join("matching.jsonl"), format!("{header}\n")).unwrap();+ fs::write(+ root.join("other.jsonl"),+ match harness {+ ManagedHarness::Claude => {+ format!("{}\n", json!({"sessionId":"other-id","cwd":other}))+ }+ ManagedHarness::Codex => format!(+ "{}\n",+ json!({"type":"session_meta","payload":{"id":"other-id","cwd":other}})+ ),+ ManagedHarness::Pi | ManagedHarness::Omp => format!(+ "{}\n",+ json!({"type":"session","id":"other-id","cwd":other})+ ),+ ManagedHarness::OpenCode | ManagedHarness::Crush => unreachable!(),+ },+ )+ .unwrap();++ let sessions = list_native_sessions(harness, temp.path(), &cwd, Some(&root), 8)+ .await+ .unwrap();+ assert_eq!(sessions.len(), 1, "{} candidates", harness.as_str());+ assert_eq!(+ sessions[0].native_session_id,+ format!("{}-id", harness.as_str())+ );+ }+ }++ #[tokio::test]+ async fn opencode_candidate_discovery_is_newest_first_and_checkout_scoped() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let other = temp.path().join("other");+ fs::create_dir_all(&cwd).unwrap();+ fs::create_dir_all(&other).unwrap();+ let db_root = temp.path().join("opencode");+ fs::create_dir_all(&db_root).unwrap();+ let connection = Connection::open(db_root.join("opencode.db")).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE session( \+ id TEXT PRIMARY KEY, directory TEXT NOT NULL, time_updated INTEGER NOT NULL);",+ )+ .unwrap();+ for (id, directory, updated) in [+ ("older", &cwd, 100_i64),+ ("newer", &cwd, 200_i64),+ ("unrelated", &other, 300_i64),+ ] {+ connection+ .execute(+ "INSERT INTO session VALUES (?1, ?2, ?3)",+ params![id, directory.to_string_lossy(), updated],+ )+ .unwrap();+ }++ let sessions = list_native_sessions(+ ManagedHarness::OpenCode,+ temp.path(),+ &cwd,+ Some(&db_root),+ 8,+ )+ .await+ .unwrap();+ assert_eq!(+ sessions+ .iter()+ .map(|candidate| candidate.native_session_id.as_str())+ .collect::<Vec<_>>(),+ ["newer", "older"]+ );+ }++ #[tokio::test]+ async fn crush_candidate_discovery_and_incremental_export_are_read_only() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let data = cwd.join(".crush");+ fs::create_dir_all(&data).unwrap();+ let db = data.join("crush.db");+ let connection = Connection::open(&db).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE sessions(id TEXT PRIMARY KEY, updated_at INTEGER NOT NULL);\n\+ CREATE TABLE messages(\+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL, role TEXT NOT NULL,\+ parts TEXT NOT NULL, updated_at INTEGER NOT NULL,\+ is_summary_message INTEGER NOT NULL DEFAULT 0);",+ )+ .unwrap();+ for (id, updated) in [("older", 1_700_000_000_i64), ("newer", 1_800_000_000)] {+ connection+ .execute("INSERT INTO sessions VALUES (?1, ?2)", params![id, updated])+ .unwrap();+ }+ connection+ .execute(+ "INSERT INTO messages VALUES ('m1', 'newer', 'assistant', ?1, 1, 0)",+ [json!([+ {"type":"reasoning","data":{"text":"private"}},+ {"type":"tool_call","data":{"name":"bash","input":{"cmd":"date"},"finished":false}},+ {"type":"text","data":{"text":"visible"}}+ ])+ .to_string()],+ )+ .unwrap();++ let candidates = list_native_sessions(ManagedHarness::Crush, temp.path(), &cwd, None, 8)+ .await+ .unwrap();+ assert_eq!(+ candidates+ .iter()+ .map(|candidate| candidate.native_session_id.as_str())+ .collect::<Vec<_>>(),+ ["newer", "older"]+ );++ let first = export_crush(&cwd, None, "newer", None).unwrap();+ assert_eq!(first.events.len(), 1);+ assert_eq!(first.events[0].content, "visible");+ assert!(first.losses.iter().any(|loss| loss.contains("reasoning")));+ assert!(first.losses.iter().any(|loss| loss.contains("unfinished")));+ connection+ .execute(+ "INSERT INTO messages VALUES ('m2', 'newer', 'tool', ?1, 2, 0)",+ [json!([{"type":"tool_result","data":{"name":"bash","content":"ok","is_error":false}}]).to_string()],+ )+ .unwrap();+ let second = export_crush(&cwd, None, "newer", first.source_cursor.as_deref()).unwrap();+ assert_eq!(second.events.len(), 1);+ assert_eq!(second.events[0].kind, WorkstreamEventKind::ToolResult);+ assert_eq!(second.events[0].content, "ok");+ }+#[test]fn incomplete_final_jsonl_record_does_not_advance_cursor() {let temp = tempfile::tempdir().unwrap();diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 35e7aeec..40be546b 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -103,14 +103,21 @@ from hook paths.reverses. Or: `git push` the wiki dir + `rsync` the data dir.**Optional managed-workstream loop:** `ai-memory run` opens a lease for the-current repository/worktree workstream, uses a harness adapter to create or-resume that harness's native session, and marks lifecycle calls with an-invocation-scoped run id. SessionStart injects an unseen bounded event range;-the host imports the native transcript tail and a Git checkpoint when the child-exits. Native stores are read-only. Raw sanitized JSONL segments are immutable,-while SQLite supplies monotonic sequences, FTS, native source/delivery cursors,-and idempotent retry state. A full-ledger `workstream-search` path complements-the bounded startup packet. See [Managed cross-harness+current repository/worktree workstream, resolves an explicit harness or the+newest usable local/linked harness, creates or resumes that harness's native+session, and marks lifecycle calls with an invocation-scoped run id.+SessionStart injects an unseen bounded event range; Crush receives it through a+temporary supported global-context path because it lacks SessionStart. The host+imports the native transcript tail and a Git checkpoint when the child exits.+ai-memory opens native stores read-only. Raw sanitized JSONL segments are+immutable, while SQLite supplies monotonic sequences, FTS, native+source/delivery cursors, and idempotent retry state. A full-ledger+`workstream-search` path complements+the bounded startup packet. An interactive empty workstream may adopt a+checkout-matching native session once. Eligibility comes from authoritative+ledger/session state: after any harness establishes the workstream, a newly+joining harness starts fresh and receives portable history instead of adopting+unrelated old native history. See [Managed cross-harnessworkstreams](managed-workstreams.md).## Hook event vocabularydiff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex a3aff4a0..ebf3a6ed 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -283,10 +283,10 @@ Top-line rules carved into the codebase:## 15. Managed workstreams use a portable ledger, not native format conversionManaged cross-harness continuity is explicitly opt-in through `ai-memory run`.-Direct Claude Code, Codex, OpenCode, Pi, and OMP launches retain the existing-hook and single-use handoff behavior. There is no process-global mode or manual-harness switch: the wrapper selects the current repository/worktree workstream-and each adapter applies that harness's native create/resume syntax.+Direct Claude Code, Codex, OpenCode, Pi, Crush, and OMP launches retain the+existing hook and single-use handoff behavior. There is no process-global mode+or manual harness switch: the wrapper selects the current repository/worktree+workstream and each adapter applies that harness's native create/resume syntax.One logical workstream owns one native session per harness plus an append-onlyportable event ledger. We rejected converting a Claude transcript into a fake@@ -304,6 +304,27 @@ are evidence at run boundaries and never commit, stash, reset, or otherwisemutate the checkout. The markdown wiki remains the durable knowledge surface;the managed ledger is an operational continuity substrate.+Native-session adoption is restricted to bootstrapping an otherwise-empty+workstream. The interactive launcher may offer recent sessions recorded for the+same canonical checkout, but an explicit new workstream and noninteractive+invocations start fresh. After any harness links a session or contributes+portable history, server-side state disables adoption for every harness. This+prevents a first Codex launch after Claude work from attaching an unrelated old+Codex transcript; it creates a clean Codex session, injects the established+ledger, and resumes that linked Codex session on later returns.++Bare `ai-memory run` treats local timestamps as a bootstrap hint, not global+precedence. Once a workstream is established, the server selects the most+recently linked harness among the locally available candidates. This prevents a+newer obsolete transcript file from overriding the logical workstream. When no+checkout-local candidate exists, bare mode fails before creating server state.++We also rejected automatic private-store rewrites after a checkout directory+rename. Most harnesses persist absolute paths, there is no shared relocation+API, and the server cannot distinguish a moved checkout from another clone of+the same remote. Exact-path discovery and explicit native recovery are safer;+Crush is the exception because its project-local database moves with the tree.+This design follows the harness-format and session-portability experiments inthe companion `ai-babel` research project: semantic continuity is portable,while exact native context is preserved by resuming that harness's own session.diff --git a/docs/install.md b/docs/install.mdindex 2d24e00f..29013861 100644--- a/docs/install.md+++ b/docs/install.md@@ -1094,7 +1094,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree| Subcommand | Pattern | What it does ||---|---|---|| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server |-| `run <harness> [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; all arguments after the harness name go to the harness unchanged |+| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, or OMP explicitly; exact `--yolo` is wrapper-owned and other native arguments pass through || `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically || `status` | `docker exec` | Counts, paths, derived-index diagnostics, and passive LLM/embedding provider health || `search "<query>"` | `docker exec` | Wiki search with FTS5 + graph/vector RRF |@@ -1337,6 +1337,13 @@ that helper back to the host's `127.0.0.1:49374`, so `ai-memory status`,`ai-memory search`, and `ai-memory bootstrap` work with the same defaultURL as the generated agent config.+`ai-memory run` is the exception: the current wrapper intercepts it and starts a+cached checksum-verified native client on the host, where harness executables+and session stores exist. It preserves an explicit remote+`AI_MEMORY_SERVER_URL`. If `run` logs `data_dir=/data` and then cannot find+`codex`, `claude`, or another harness executable, refresh the stale wrapper with+`ai-memory upgrade` on that client machine.+### Docker compose alternativeIf you prefer compose, clone the repo and run:diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 0debd310..f8f6100a 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -125,6 +125,10 @@ What happens:Zero files move on disk because the disk path is keyed by`project_id`, not name. The web UI URL `/web/w/<ws>/<proj-name>/…`just resolves to the same `project_id` after the column update.+This command also does not rename a source checkout or rewrite any native agent+session locator. See [managed workstream rename+behavior](managed-workstreams.md#project-and-directory-renames) before+physically renaming a checkout that has native sessions.Failure modes:diff --git a/docs/managed-harness-contributions.md b/docs/managed-harness-contributions.mdnew file mode 100644index 00000000..4e87641a--- /dev/null+++ b/docs/managed-harness-contributions.md@@ -0,0 +1,156 @@+# Adding a managed harness++Managed-workstream support is narrower than MCP or lifecycle-hook support. This+release can manage Claude Code, Codex, OpenCode, Pi, Crush, and OMP. Gemini CLI,+Kimi Code, Devin CLI, Cursor, Grok Build CLI, and the other integrations in the+README support matrix do not become managed merely because ai-memory can capture+their hooks.++A managed adapter must preserve a harness's real native session, deliver the+portable workstream delta exactly once, and import only visible history without+writing the harness's private store. Contributors adding another harness should+follow this protocol.++## 1. Establish the native contract++Start with current upstream documentation and repeatable fixtures. The+companion `ai-babel` research project is useful prior work, but it is not a+substitute for verifying the installed CLI version.++Document and test:++- the default executable and supported host platforms;+- fresh-session and resume syntax, including selector placement;+- explicit selectors supplied by the user;+- print/noninteractive modes and utility subcommands that must pass through;+- session-store roots, environment overrides, and path options;+- the stored checkout identifier and timestamp units;+- complete versus in-progress records, tool-pairing rules, compaction records,+ and records containing hidden reasoning or credentials;+- a supported way to inject startup context before the first model turn; and+- the native dangerous/approval-bypass option, if the harness has one.++If exact session identity, read-only extraction, or pre-turn context delivery+cannot be demonstrated, document the limitation instead of adding a partial+managed adapter.++## 2. Register the harness deliberately++Add or reuse the harness's `AgentKind`. A new kind must also be added to+`AgentKind::ALL` and to a forward SQLite migration that rebuilds the sessions+constraint and pairing triggers without losing existing rows. Never edit an+already-released migration.++Then wire the explicit managed surface:++- `RunHarnessChoice` in `ai-memory-cli`;+- `ManagedHarness`, its executable, and its `AgentKind` mapping in+ `ai-memory-workstream`;+- the server's managed-harness validation list; and+- README, install, architecture, design-decision, and changelog references.++Explicit support comes first. Add a harness to bare `ai-memory run` automatic+selection only after checkout-local candidate discovery is reliable. A local+file timestamp is a bootstrap hint; the server's current linked harness remains+authoritative for an established workstream.++## 3. Preserve native argv and session ownership++Implement fresh, resume, and explicit-selector behavior in+`crates/ai-memory-workstream/src/harness.rs`. Preserve every user argument and+its order except the exact wrapper-owned `--yolo` token. An explicit native+selector always wins over ai-memory's linked session. Help, version, login,+doctor, export, and similar utility commands must not receive session flags.++Generate a session id only when the native CLI officially accepts a caller+provided id. Otherwise let the harness create the session, then discover it by+exact checkout and launch time. Do not infer a session from "newest globally."++Map `--yolo` only to a verified native option and avoid duplicates. If the+harness has no equivalent, add no flag and document that fact.++## 4. Discover and export read-only++Implement candidate discovery and incremental export in+`crates/ai-memory-workstream/src/transcript.rs`.++The adapter must:++- restrict candidates to the exact current checkout;+- honor documented store-root environment and command-line overrides;+- open SQLite stores read-only and never create, migrate, vacuum, or repair+ them;+- tolerate an incomplete final JSONL record or an in-progress tool call without+ advancing past it;+- emit deterministic source record and event ids;+- resume from a persisted source cursor without duplicates;+- normalize visible user/assistant messages, completed tool calls/results, and+ compaction summaries; and+- exclude system/developer prompts, hidden reasoning, binary payloads,+ credentials, provider metadata, and unsupported records.++Extraction gaps should become bounded loss annotations. They must not cause the+adapter to copy a private record "just in case."++## 5. Deliver context before acknowledging it++The preferred path is a native SessionStart hook. The managed child inherits+`AI_MEMORY_RUN_ID`; the hook links the actual native session, renders the unseen+bounded workstream range, makes it model-visible, and only then accepts the+delivery cursor.++If the harness has no suitable hook, use a documented native context mechanism.+Crush is the reference: the launcher fetches without accepting, writes a private+temporary copy of the supported config plus an ephemeral context file, starts+the child, and acknowledges only after spawn succeeds. The original config and+session store are never written by ai-memory, the harness retains its normal+native writes, and the temporary directory is removed after exit.++Fetching must be repeatable until acceptance. A failed spawn, hook, or network+ack may redeliver context; it must never silently lose it. Historical tool calls+must be labelled completed evidence so another harness cannot interpret them as+pending work.++## 6. Keep workstream invariants intact++One logical workstream has at most one current native session per harness. A+new harness joining an established workstream starts a clean native session and+receives portable history; it must not adopt an unrelated older local session.+First-use adoption is allowed only while authoritative server state has no+linked native session or substantive portable event.++Keep leases, delivery cursors, source cursors, immutable sanitized segments,+batch limits, and idempotent imports on the existing shared path. Do not add a+harness-specific synchronization database or mutate private stores to resolve+precedence, directory renames, or conflicts.++## 7. Required tests++A managed-harness PR should include focused coverage for:++- fresh launch, linked resume, explicit-selector precedence, argv order,+ utility passthrough, path overrides, and `--yolo` mapping;+- candidate ordering, exact-checkout isolation, timestamp handling, read-only+ access, incremental cursors, stable ids, incomplete records, visible record+ inclusion, and private record exclusion;+- first-use adoption and the established-workstream obsolete-session guard;+- startup context fetch/injection/accept ordering and spawn-failure redelivery;+- the `AgentKind::ALL` schema invariant when a kind is added;+- deterministic fake-process acceptance in+ `scripts/managed-workstream-acceptance.sh`; and+- a manual real-harness pass that switches into the new harness, observes the+ prior sentinel, persists its reply, and resumes its original native session+ when revisited.++The deterministic phase remains credential-free and suitable for frequent+local runs. Real model calls stay opt-in and outside CI. Record the tested CLI+version and any platform limitation in the PR description.++Run the repository's complete Rust gate before requesting review:++```bash+cargo fmt --check+git diff --check+TAILWIND_SKIP=1 cargo test --workspace+TAILWIND_SKIP=1 cargo clippy --workspace --all-targets -- -D warnings+```diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 3107c565..dc7552f2 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -1,8 +1,8 @@# Managed cross-harness workstreams`ai-memory run` is an opt-in launcher that lets one logical coding session move-between Claude Code, Codex, OpenCode, Pi, and OMP. Direct agent launches keep-their existing ai-memory behavior. There is no global mode toggle and no+between Claude Code, Codex, OpenCode, Pi, Crush, and OMP. Direct agent launches+keep their existing ai-memory behavior. There is no global mode toggle and no`switch` command: using `run` selects the current workstream and transparentlycreates or resumes the correct native session for the requested harness.@@ -14,16 +14,18 @@ ai-memory run claudeai-memory run codex --yolo# return to Claude Code later; ai-memory supplies Claude's native --resumeai-memory run claude --model opus+# or omit the harness and continue the newest usable session automatically+ai-memory run```-Everything after the harness name is native argv. No `--` separator is needed,-and ai-memory does not maintain a second copy of each harness's option schema.-Wrapper options must come first:+Everything after the harness name is native argv except the wrapper-owned exact+flag `--yolo`. No `--` separator is needed, and ai-memory does not maintain a+second copy of each harness's option schema. Other wrapper options come first:```textai-memory run [--workspace NAME] [--project NAME]- [--workstream NAME | --new NAME] [--executable PATH]- <claude|codex|opencode|pi|omp> [native arguments...]+ [--workstream NAME | --new NAME] [--executable PATH] [--yolo]+ [claude|codex|opencode|pi|crush|omp] [native arguments...]```The default is the most recently selected workstream for the current repository@@ -31,18 +33,59 @@ and worktree, creating one named `default` on first use. `--new NAME` starts anindependent line of work; `--workstream NAME` returns to one. These are optionalbranching controls, not harness-switch controls.+## Automatic harness selection++With no harness name, `ai-memory run` inspects checkout-local sessions for+Claude Code, Codex, OpenCode, Pi, and Crush. For an empty workstream it resumes+the newest session automatically. For an established workstream, server state+takes precedence: ai-memory resumes the most recently linked harness that still+has a usable local session. It never chooses a newer but obsolete session from+another harness merely because that file has a later timestamp. OMP remains+available explicitly but is not in the automatic pool.++Bare mode accepts wrapper options but not harness-native arguments or+`--executable`, because their meaning depends on the selected harness. In a new+directory with no session in the automatic pool, it exits without creating a+workstream and suggests the explicit `ai-memory run <harness>` commands.++## First managed launch++An otherwise-empty workstream may adopt one of the requested harness's existing+native sessions. On an interactive launch, ai-memory inspects that harness's+store without modifying it and lists up to eight recent sessions whose recorded+working directory matches the current checkout. Choose one to resume it, press+Enter to accept the newest candidate, or choose `0` to start a new session.+Sessions from another checkout are never offered.++Adoption is only a bootstrap operation. Once any harness has linked a native+session or contributed portable message/tool/compaction history, the workstream+is established. If Claude established it and Codex has not joined it yet, for+example, `ai-memory run codex` creates a fresh Codex session and injects the+Claude workstream history. It does not inspect or select an older unrelated+Codex session. Returning to Codex later resumes the Codex session already linked+to that workstream.++Explicit native selectors always win. `--new NAME` always creates a fresh+native session for the new workstream. Scripted/noninteractive invocations and+launches without terminal input skip the chooser and start fresh. A launch that+exits before producing either a native session or portable history does not+consume the later adoption opportunity.+## What happens on each run1. The host client resolves the normal workspace/project scope and a stablerepository plus worktree fingerprint. It opens a 90-second renewable lease.One writer may own a workstream at a time, so two terminals cannot silentlyrace its native-session pointers or delivery cursors.-2. The harness adapter passes every native argument through in order and adds a- native create/resume selector only when the user did not supply one.+2. Bare mode resolves the correct available harness. For an empty workstream,+ an explicit interactive adapter can offer matching local sessions for+ one-time adoption. Otherwise the adapter passes native arguments through in+ order and adds a create/resume selector only when the user did not supply one.3. `AI_MEMORY_RUN_ID` marks lifecycle hooks as managed. SessionStart links theactual native session and injects only the portable events that session has- not seen. Direct launches do not set this variable and continue to use the- existing single-use handoff path.+ not seen. Crush, which has no SessionStart hook, receives the same bounded+ packet through a temporary `options.global_context_paths` entry. Direct+ launches continue to use the existing single-use handoff path.4. When the child exits, ai-memory reads the native transcript store withoutmodifying it. Visible user/assistant messages, completed tool calls/results,compaction summaries, and a non-mutating Git checkpoint enter an append-only@@ -74,19 +117,38 @@ is labelled completed evidence and must never be replayed as a pending call.| Codex | native default creation | `resume <id>` | `~/.codex/sessions/**/rollout-*.jsonl` || OpenCode | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only || Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` |+| Crush | native default creation | `--session <id>` | `<project>/.crush/crush.db` opened read-only || OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,or Codex's `resume` wins. ai-memory links the selected native session and resetsan unrelated adapter cursor rather than assuming it belongs to the old session.-Pi and OMP `--session-dir` values are passed through unchanged and used as the-read-only import root. Native store environment overrides are also honored:+Pi and OMP `--session-dir` values and Crush `--data-dir` values are passed+through unchanged and used as the read-only import root. Native store+environment overrides are also honored:`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_DATA_HOME`,`PI_CODING_AGENT_SESSION_DIR`, and `PI_CODING_AGENT_DIR`. The Pi-family adapteralso recognizes a complete `.jsonl.<nonce>.tmp` atomic-write file when a nativeprocess exits before renaming it; incomplete final JSONL records are neverimported. Help, version, and known utility subcommands pass through without-session flags.+session flags. Claude/Pi/OMP print mode, Codex `exec`, OpenCode/Crush `run`,+redirected input, and other noninteractive launches never open the adoption+chooser.++`ai-memory run --yolo <harness>` and `ai-memory run <harness> --yolo` both use+the harness's native dangerous mode. The translation is Claude Code+`--dangerously-skip-permissions`, Codex+`--dangerously-bypass-approvals-and-sandbox`, OpenCode `--auto`, Pi `--approve`,+and Crush `--yolo`. OMP currently needs no added flag. ai-memory does not add a+duplicate when the translated native flag is already present.++Managed support is intentionally narrower than the general integration matrix.+Gemini CLI, Kimi Code, Devin CLI, Cursor, Grok Build CLI, and other agents may+have MCP or lifecycle-hook support without native managed resume. Contributors+adding another managed harness must follow the [managed-harness contribution+protocol](managed-harness-contributions.md), including read-only extraction,+pre-turn context delivery, migration invariants, deterministic tests, and an+opt-in real-harness acceptance pass.## Installation and recovery@@ -101,6 +163,14 @@ ai-memory install-hooks --agent pi --applyai-memory install-hooks --agent omp --apply```+Crush needs no ai-memory hook installation for managed mode. The launcher reads+its one-time context from the server, copies the existing global Crush JSON into+a private temporary directory, appends an ephemeral context path, and points the+child at that directory with `CRUSH_GLOBAL_CONFIG`. Delivery is acknowledged+only after the child starts, so a spawn failure cannot lose the packet. The+original config is not modified. ai-memory opens the project database read-only;+the launched Crush process continues its normal native session writes.+The Linux/macOS Docker shell wrapper cannot execute a host agent from inside itshelper container. For `run` only, it downloads the matching native release into`~/.cache/ai-memory/native-runner`, verifies the published SHA-256 checksum, and@@ -108,6 +178,13 @@ executes that host client. Set `AI_MEMORY_NATIVE_BIN=/path/to/ai-memory` to usespecific native build. Native package, release, and source installs need noshim. On native Windows, use the published `ai-memory.exe` or a source build.+The wrapper intercepts `run` before Docker and preserves the host `PATH`,+`AI_MEMORY_SERVER_URL`, and authentication environment. If logs show+`data_dir=/data` followed by `starting managed ... No such file or directory`,+the installed wrapper is stale and sent the command into the helper container.+Run `ai-memory upgrade` on the client machine. A remote/homelab server must be+upgraded separately.+If a client is killed before final import, its lease expires. A later managedrun starts from the last committed adapter cursor, so already linked nativesessions can import the missing tail without duplicating earlier events. A@@ -116,22 +193,42 @@ not silently start an unmanaged agent.## Privacy and storage boundaries-Managed mode does not write to Claude, Codex, OpenCode, Pi, or OMP private-stores. Adapters read only documented/observed local session formats. Provider-credentials, encrypted content, system/developer prompt records, and hidden-reasoning are not copied. The server sanitizer runs before both the SQLite FTS-ledger and immutable files under+ai-memory's managed adapters do not write to Claude, Codex, OpenCode, Pi, Crush,+or OMP private stores. The launched harness retains normal ownership of its own+session writes. Adapters read only documented or observed local session formats.+Provider credentials, encrypted content, system/developer prompt records, and+hidden reasoning are not copied. The server sanitizer runs before both the+SQLite FTS ledger and immutable files under`<data_dir>/raw/workstreams/<workstream-id>/segments/` are written.The ledger is an operational continuity substrate, not a replacement for themarkdown wiki. Durable decisions, rules, procedures, and project facts stillbelong in wiki pages through consolidation or explicit durable writes.+## Project and directory renames++`ai-memory rename-project --from OLD --to NEW` changes only the server-side+project name. Wiki paths are UUID-keyed, so it moves no server directory, source+checkout, or native harness session. If the source checkout path itself is+renamed, absolute-path session locators used by Claude Code, Codex, OpenCode,+Pi, and OMP may still reference the old path; Crush's project-local `.crush`+database moves with the checkout.++There is no portable, supported API that rewrites every harness's private+project locator. ai-memory therefore does not mutate those stores or silently+equate a renamed checkout with another clone of the same remote. Explicit+native selectors still win and can recover a session when that harness supports+cross-directory resume; OpenCode also provides its own export/import flow. For+a renamed checkout, use an explicit harness and its documented session selector+to seed the new managed workstream. Keep the old checkout path available until+recovery is verified. Automatic discovery intentionally requires the recorded+checkout to match exactly.+## Manual acceptance-The opt-in acceptance runner exercises wrapper edge cases and then orchestrates-the locally installed Claude, Codex, OpenCode, Pi, and OMP CLIs through one real-workstream:+The opt-in acceptance runner exercises launcher edge cases and then orchestrates+the locally installed Claude, Codex, OpenCode, Pi, Crush, and OMP CLIs through+one real workstream:```bashscripts/managed-workstream-acceptance.sh@@ -142,8 +239,14 @@ and model calls. Hook configs, native session stores, the ai-memory server, andthe Git fixture are isolated under a temporary directory. Claude, Codex, andOpenCode receive only copied authentication material; OMP receives a temporaryagent directory with read-consistent credential/model database backups and-copied settings. Native session creation, read-only extraction, cross-harness-injection, and returning resume paths are all exercised. Set+copied settings. Crush uses its existing global provider configuration and an+isolated project database. The deterministic phase also covers first-run+adoption, bare-mode selection and empty-directory failure, wrapper `--yolo`,+lease exclusion, Crush context cleanup, and the established-workstream guard+against obsolete sessions. Native session creation, read-only extraction,+cross-harness injection, and returning resume paths are all exercised. Docker+wrapper host execution and remote URL preservation are covered separately by+the `ai-memory-cli` packaging tests. Set`AI_MEMORY_ACCEPTANCE_HARNESSES="claude codex"` to selecta subset, `AI_MEMORY_ACCEPTANCE_DETERMINISTIC_ONLY=1` to skip model calls, or`AI_MEMORY_ACCEPTANCE_KEEP=1` to retain all temporary logs and data.diff --git a/docs/marker-file.md b/docs/marker-file.mdindex d618d940..4c300ae3 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -283,13 +283,13 @@ the `default` bucket entirely.## Migrating existing projects-Projects already created under workspace `default` stay there. Move-one with the CLI:+Projects already created under workspace `default` stay there. Move one to a+different workspace with the CLI:```sh-ai-memory rename-project \- --workspace default --project foo \- --new-workspace movvia+ai-memory move-project \+ --from-workspace default --project foo \+ --to-workspace movvia --confirm```## Install-wide default (no marker)diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.shindex 8c693993..406c47fb 100755--- a/scripts/managed-workstream-acceptance.sh+++ b/scripts/managed-workstream-acceptance.sh@@ -8,7 +8,7 @@ ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)BIN=${AI_MEMORY_ACCEPTANCE_BIN:-"$ROOT/target/debug/ai-memory"}KEEP=${AI_MEMORY_ACCEPTANCE_KEEP:-0}DETERMINISTIC_ONLY=${AI_MEMORY_ACCEPTANCE_DETERMINISTIC_ONLY:-0}-HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi omp"}+HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi crush omp"}TMP=$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-workstream-acceptance.XXXXXX")DATA="$TMP/data"REPO="$TMP/repo"@@ -30,7 +30,7 @@ cleanup() {}trap cleanup EXIT INT TERM-for command in cargo curl diff git jq sqlite3; do+for command in cargo curl diff git jq script sqlite3; docommand -v "$command" >/dev/null 2>&1 || {printf 'missing required command: %s\n' "$command" >&2exit 1@@ -100,6 +100,13 @@ case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" in: >"$AI_MEMORY_ACCEPTANCE_STARTED"sleep "${AI_MEMORY_ACCEPTANCE_SLEEP:-3}";;+ crush)+ printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"+ printf '%s\n' "$CRUSH_GLOBAL_CONFIG" >"$AI_MEMORY_ACCEPTANCE_CRUSH_ENV_LOG"+ cp "$CRUSH_GLOBAL_CONFIG/crush.json" "$AI_MEMORY_ACCEPTANCE_CRUSH_CONFIG_LOG"+ packet=$(jq -r '.options.global_context_paths[-1]' "$CRUSH_GLOBAL_CONFIG/crush.json")+ cp "$packet" "$AI_MEMORY_ACCEPTANCE_CRUSH_PACKET_LOG"+ ;;esacEOFchmod +x "$FAKE"@@ -112,7 +119,9 @@ printf 'running deterministic wrapper edge checks\n'"$BIN" --data-dir "$DATA" run --new edge-argv --executable "$FAKE" \codex --yolo -m gpt-5 "prompt words" >"$LOGS/edge-argv.log" 2>&1)-diff -u <(printf '%s\n' --yolo -m gpt-5 "prompt words") "$TMP/argv.log"+diff -u \+ <(printf '%s\n' -m gpt-5 "prompt words" --dangerously-bypass-approvals-and-sandbox) \+ "$TMP/argv.log"set +e(@@ -160,6 +169,164 @@ set -e}wait "$lease_pid"+# Bare run must fail before contacting the server when this checkout has no+# native session in any auto-detected harness.+mkdir -p "$CONFIG/empty-home"+set +e+(+ cd "$REPO"+ HOME="$CONFIG/empty-home" XDG_DATA_HOME="$CONFIG/empty-home/xdg-data" \+ "$BIN" --data-dir "$DATA" run >"$LOGS/edge-auto-empty.log" 2>&1+)+auto_empty_code=$?+set -e+[ "$auto_empty_code" -ne 0 ] || {+ printf 'bare run unexpectedly started without a checkout-local session\n' >&2+ exit 1+}+grep -q 'no Claude Code, Codex, OpenCode, Pi, or Crush session' \+ "$LOGS/edge-auto-empty.log"++# On a new workstream, bare run automatically adopts the newest local session.+AUTO_HOME="$CONFIG/auto-home"+AUTO_CODEX_HOME="$AUTO_HOME/.codex"+AUTO_CLAUDE_HOME="$AUTO_HOME/.claude"+AUTO_BIN="$AUTO_HOME/bin"+mkdir -p "$AUTO_CODEX_HOME/sessions/2026/01/01" \+ "$AUTO_CLAUDE_HOME/projects/fixture" "$AUTO_BIN"+ln -s "$FAKE" "$AUTO_BIN/codex"+ln -s "$FAKE" "$AUTO_BIN/claude"+printf '{"sessionId":"auto-claude-old","cwd":"%s"}\n' "$REPO" \+ >"$AUTO_CLAUDE_HOME/projects/fixture/auto-claude-old.jsonl"+sleep 1+printf '{"type":"session_meta","payload":{"id":"auto-codex-new","cwd":"%s"}}\n' \+ "$REPO" >"$AUTO_CODEX_HOME/sessions/2026/01/01/rollout-auto.jsonl"+(+ cd "$REPO"+ HOME="$AUTO_HOME" CODEX_HOME="$AUTO_CODEX_HOME" \+ CLAUDE_CONFIG_DIR="$AUTO_CLAUDE_HOME" PATH="$AUTO_BIN:$PATH" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/auto-newest-argv.log" \+ "$BIN" --data-dir "$DATA" run --workspace edge-auto --project edge-auto --yolo \+ >"$LOGS/edge-auto-newest.log" 2>&1+)+diff -u \+ <(printf '%s\n' resume auto-codex-new --dangerously-bypass-approvals-and-sandbox) \+ "$TMP/auto-newest-argv.log"++# Establish Claude after Codex, then verify bare run follows the managed+# workstream's current Claude link instead of the newer but obsolete Codex file.+(+ cd "$REPO"+ HOME="$AUTO_HOME" CLAUDE_CONFIG_DIR="$AUTO_CLAUDE_HOME" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/auto-claude-first-argv.log" \+ "$BIN" --data-dir "$DATA" run --workspace edge-auto --project edge-auto \+ --executable "$FAKE" claude >"$LOGS/edge-auto-claude-first.log" 2>&1+)+mapfile -t auto_claude_first <"$TMP/auto-claude-first-argv.log"+[ "${auto_claude_first[0]:-}" = --session-id ] || {+ printf 'Claude did not create a fresh managed session\n' >&2+ exit 1+}+auto_claude_id=${auto_claude_first[1]}+(+ cd "$REPO"+ HOME="$AUTO_HOME" CODEX_HOME="$AUTO_CODEX_HOME" \+ CLAUDE_CONFIG_DIR="$AUTO_CLAUDE_HOME" PATH="$AUTO_BIN:$PATH" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/auto-managed-precedence-argv.log" \+ "$BIN" --data-dir "$DATA" run --workspace edge-auto --project edge-auto \+ >"$LOGS/edge-auto-managed-precedence.log" 2>&1+)+diff -u <(printf '%s\n' --resume "$auto_claude_id") \+ "$TMP/auto-managed-precedence-argv.log"++# Crush has no SessionStart hook. Verify the launcher fetches the packet into a+# temporary supported global-context config, then removes it after exit.+(+ cd "$REPO"+ HOME="$AUTO_HOME" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=crush \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/crush-context-argv.log" \+ AI_MEMORY_ACCEPTANCE_CRUSH_ENV_LOG="$TMP/crush-context-env.log" \+ AI_MEMORY_ACCEPTANCE_CRUSH_CONFIG_LOG="$TMP/crush-context-config.json" \+ AI_MEMORY_ACCEPTANCE_CRUSH_PACKET_LOG="$TMP/crush-context-packet.md" \+ "$BIN" --data-dir "$DATA" run --workspace edge-auto --project edge-auto \+ --executable "$FAKE" --yolo crush >"$LOGS/edge-crush-context.log" 2>&1+)+diff -u <(printf '%s\n' --yolo) "$TMP/crush-context-argv.log"+grep -q 'ai-memory managed workstream' "$TMP/crush-context-packet.md"+crush_context_dir=$(cat "$TMP/crush-context-env.log")+[ ! -e "$crush_context_dir" ] || {+ printf 'temporary Crush context directory was not removed\n' >&2+ exit 1+}++# A blank first launch remains eligible for one-time native-session adoption.+# Use a pseudo-terminal because redirected/scripted launches deliberately skip+# the chooser.+ADOPTION_CODEX_HOME="$CONFIG/adoption-codex"+mkdir -p "$ADOPTION_CODEX_HOME/sessions/2026/01/01"+(+ cd "$REPO"+ CODEX_HOME="$ADOPTION_CODEX_HOME" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/adoption-blank-argv.log" \+ "$BIN" --data-dir "$DATA" run --new edge-adopt --executable "$FAKE" \+ codex >"$LOGS/edge-adoption-blank.log" 2>&1+)+printf '{"type":"session_meta","payload":{"id":"adoption-codex-id","cwd":"%s"}}\n' \+ "$REPO" >"$ADOPTION_CODEX_HOME/sessions/2026/01/01/rollout-adoption.jsonl"++ADOPTION_RUNNER="$TMP/adoption-runner.sh"+cat >"$ADOPTION_RUNNER" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+cd "$AI_MEMORY_ACCEPTANCE_REPO"+exec "$AI_MEMORY_ACCEPTANCE_BIN" --data-dir "$AI_MEMORY_ACCEPTANCE_DATA" \+ run --workstream edge-adopt --executable "$AI_MEMORY_ACCEPTANCE_FAKE" "$@"+EOF+chmod +x "$ADOPTION_RUNNER"++printf '\n' | env \+ AI_MEMORY_ACCEPTANCE_REPO="$REPO" \+ AI_MEMORY_ACCEPTANCE_BIN="$BIN" \+ AI_MEMORY_ACCEPTANCE_DATA="$DATA" \+ AI_MEMORY_ACCEPTANCE_FAKE="$FAKE" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/adoption-codex-argv.log" \+ CODEX_HOME="$ADOPTION_CODEX_HOME" \+ script -qefc "$ADOPTION_RUNNER codex" /dev/null \+ >"$LOGS/edge-adoption-codex.log" 2>&1+diff -u <(printf '%s\n' resume adoption-codex-id) "$TMP/adoption-codex-argv.log"++# Once Codex establishes the workstream, Claude must start clean even when an+# obsolete checkout-local Claude session exists.+ADOPTION_CLAUDE_HOME="$CONFIG/adoption-claude"+mkdir -p "$ADOPTION_CLAUDE_HOME/projects/fixture"+printf '{"sessionId":"obsolete-claude-id","cwd":"%s"}\n' "$REPO" \+ >"$ADOPTION_CLAUDE_HOME/projects/fixture/obsolete-claude-id.jsonl"+printf '\n' | env \+ AI_MEMORY_ACCEPTANCE_REPO="$REPO" \+ AI_MEMORY_ACCEPTANCE_BIN="$BIN" \+ AI_MEMORY_ACCEPTANCE_DATA="$DATA" \+ AI_MEMORY_ACCEPTANCE_FAKE="$FAKE" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/adoption-claude-argv.log" \+ CLAUDE_CONFIG_DIR="$ADOPTION_CLAUDE_HOME" \+ script -qefc "$ADOPTION_RUNNER claude" /dev/null \+ >"$LOGS/edge-adoption-claude.log" 2>&1+mapfile -t adoption_claude_argv <"$TMP/adoption-claude-argv.log"+[ "${adoption_claude_argv[0]:-}" = --session-id ] || {+ printf 'established workstream did not create a fresh Claude session\n' >&2+ exit 1+}+[ "${adoption_claude_argv[1]:-}" != obsolete-claude-id ] || {+ printf 'established workstream adopted an obsolete Claude session\n' >&2+ exit 1+}+if [ "$DETERMINISTIC_ONLY" = 1 ]; thenprintf 'deterministic managed-workstream acceptance passed\n'exit 0@@ -189,9 +356,11 @@ OPENCODE_DATA_HOME="$CONFIG/opencode-xdg-data"PI_EXTENSION="$CONFIG/pi/ai-memory.ts"OMP_EXTENSION="$CONFIG/omp/ai-memory.ts"OMP_AGENT_DIR="$CONFIG/omp/agent"+CRUSH_DATA_DIR="$CONFIG/crush/data"mkdir -p "$(dirname "$CLAUDE_SETTINGS")" "$(dirname "$CODEX_HOOKS")" \"$(dirname "$OPENCODE_PLUGIN")" "$(dirname "$PI_EXTENSION")" \- "$(dirname "$OMP_EXTENSION")" "$OMP_AGENT_DIR" "$OPENCODE_DATA_HOME/opencode"+ "$(dirname "$OMP_EXTENSION")" "$OMP_AGENT_DIR" "$OPENCODE_DATA_HOME/opencode" \+ "$CRUSH_DATA_DIR"# Redirect native transcript stores into the fixture while reusing only the# minimum authentication material required for real model calls.@@ -319,6 +488,10 @@ run_harness() {native_args=(-p --no-tools --no-extensions --extension "$PI_EXTENSION" --session-dir "$CONFIG/pi/sessions" "$prompt")[ -z "${AI_MEMORY_ACCEPTANCE_PI_MODEL:-}" ] || native_args=(-p --no-tools --no-extensions --extension "$PI_EXTENSION" --session-dir "$CONFIG/pi/sessions" --model "$AI_MEMORY_ACCEPTANCE_PI_MODEL" "$prompt");;+ crush)+ native_args=(run --quiet --data-dir "$CRUSH_DATA_DIR" "$prompt")+ [ -z "${AI_MEMORY_ACCEPTANCE_CRUSH_MODEL:-}" ] || native_args=(run --quiet --data-dir "$CRUSH_DATA_DIR" --model "$AI_MEMORY_ACCEPTANCE_CRUSH_MODEL" "$prompt")+ ;;omp)native_args=(-p --no-tools --extension "$OMP_EXTENSION" --session-dir "$CONFIG/omp/sessions" "$prompt")[ -z "${AI_MEMORY_ACCEPTANCE_OMP_MODEL:-}" ] || native_args=(-p --no-tools --extension "$OMP_EXTENSION" --session-dir "$CONFIG/omp/sessions" --model "$AI_MEMORY_ACCEPTANCE_OMP_MODEL" "$prompt")