Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: release managed leases after launcher failures
AkitaOnRailsb3f137b1426d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 134de636..5d64d254 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Managed launch failures now cancel their server lease immediately, and a new+ launch waits briefly when the previous launcher is still finalizing. The+ parent launcher also survives terminal interrupts long enough to finish or+ cancel the run, preventing a normal quit-and-reopen from being blocked by the+ 90-second crash-recovery lease.+- CLI startup diagnostics now show the configured server URL and use the real+ host name in lease-owner messages, avoiding misleading `localhost` labels for+ remote-server clients.+## [1.17.0] - 2026-07-20### Addeddiff --git a/README.md b/README.mdindex 697d640e..00389245 100644--- a/README.md+++ b/README.md@@ -150,9 +150,11 @@ priors are at the [bottom](#influences-and-prior-art).The first explicit run can offer an existing session from this exact checkoutor start a new one. Switching harnesses starts or resumes the native sessionlinked to the shared workstream, so an obsolete local session cannot replace- newer cross-harness history. Managed mode currently covers Claude Code,- Codex, OpenCode, Pi, Crush, and OMP; direct harness launches remain unchanged.- See [Managed cross-harness workstreams](docs/managed-workstreams.md).+ newer cross-harness history. After a normal quit, the next launch waits+ briefly if the previous launcher is still finalizing; handled failures release+ the workstream immediately. Managed mode currently covers Claude Code, Codex,+ OpenCode, Pi, Crush, and OMP; direct harness launches remain unchanged. See+ [Managed cross-harness workstreams](docs/managed-workstreams.md).- **"Quit at 4 PM, pick up at 9 AM in a different agent."** Theclassic. SessionStart hook in the next supported hook client prepends atyped handoff with open questions, next steps, and a session summary. Grokdiff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex d238df97..ae51fcc1 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -4,6 +4,8 @@ use std::ffi::{OsStr, OsString};use std::io::{self, IsTerminal as _};use std::path::{Path, PathBuf};use std::process::Stdio;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};use std::time::{Duration, SystemTime};use ai_memory_core::{@@ -22,9 +24,13 @@ use tokio::process::Command;use crate::cli::{RunArgs, RunHarnessChoice};use crate::commands::{path_util, resolve_project_name};use crate::config::Config;-use crate::http_client::{ServerEndpoint, get_json, post_empty, post_json, post_json_no_content};+use crate::http_client::{+ ServerEndpoint, ServerResponseError, get_json, post_empty, post_json, post_json_no_content,+};const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);+const PREPARE_BUSY_RETRY_WINDOW: Duration = Duration::from_secs(5);+const PREPARE_BUSY_RETRY_INTERVAL: Duration = Duration::from_millis(250);const IMPORT_BATCH_EVENTS: usize = 400;const IMPORT_BATCH_BYTES: usize = 1024 * 1024;const ADOPTION_CANDIDATE_LIMIT: usize = 8;@@ -96,10 +102,36 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {new_workstream: args.new_workstream,lease_owner: lease_owner(),};- let prepared: PrepareManagedRunResponse = post_json(&endpoint, "/workstream/runs", &prepare)+ let interrupted_before_spawn = Arc::new(AtomicBool::new(false));+ let interrupt_task = tokio::spawn(capture_interrupts(Arc::clone(&interrupted_before_spawn)));+ let prepared = prepare_managed_run(&endpoint, &prepare).await- .context("opening managed workstream; the agent was not started")?;+ .context("opening managed workstream; the agent was not started");+ let prepared = match prepared {+ Ok(prepared) => prepared,+ Err(error) => {+ interrupt_task.abort();+ return Err(error);+ }+ };let run_path = format!("/workstream/runs/{}", prepared.run_id);+ macro_rules! acquired_try {+ ($result:expr) => {+ match $result {+ Ok(value) => value,+ Err(error) => {+ interrupt_task.abort();+ cancel_managed_run_after_failure(&endpoint, &run_path).await;+ return Err(error);+ }+ }+ };+ }+ if interrupted_before_spawn.load(Ordering::SeqCst) {+ acquired_try!(Err(anyhow!(+ "managed run interrupted before the agent started"+ )));+ }let harness = if automatic_harness {let resolved = prepared.resolved_agent.unwrap_or_else(|| {eprintln!(@@ -107,37 +139,39 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {);provisional_harness.agent_kind()});- managed_harness_from_agent(resolved).ok_or_else(|| {+ acquired_try!(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(+ acquired_try!(ensure_executable_available(harness, executable.as_deref()));+ let mut plan = acquired_try!(build_launch_plan(harness,executable.clone(),native_args.clone(),prepared.native_session_id.as_deref(),- )?;+ ));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(+ let candidate = acquired_try!(+ auto_candidates+ .iter()+ .find(|candidate| candidate.harness == harness)+ .context("the selected automatic harness no longer has a checkout-local session")+ );+ plan = acquired_try!(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(),@@ -161,22 +195,24 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {.await{Ok(candidates) if !candidates.is_empty() => {- let selection = choose_native_session_interactive(- harness,- prepared.workstream_name.clone(),- candidates,- &endpoint,- &run_path,- )- .await?;+ let selection = acquired_try!(+ 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(+ plan = acquired_try!(build_launch_plan(harness,executable,native_args,Some(&native_session_id),- )?;+ ));}Ok(None) => {}Err(error) => eprintln!(@@ -198,22 +234,29 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {if plan.mode == LaunchMode::Session&& let Some(native_session_id) = &plan.expected_session_id{- post_json_no_content(- &endpoint,- &format!("{run_path}/link"),- &LinkManagedRunRequest {- native_session_id: native_session_id.clone(),- },- )- .await- .context("linking the managed native session; the agent was not started")?;+ acquired_try!(+ post_json_no_content(+ &endpoint,+ &format!("{run_path}/link"),+ &LinkManagedRunRequest {+ native_session_id: native_session_id.clone(),+ },+ )+ .await+ .context("linking the managed native session; the agent was not started")+ );}let crush_context = if harness == ManagedHarness::Crush && plan.mode == LaunchMode::Session {- prepare_crush_context(&endpoint, &run_path, &home).await?+ acquired_try!(prepare_crush_context(&endpoint, &run_path, &home).await)} else {None};+ if interrupted_before_spawn.load(Ordering::SeqCst) {+ acquired_try!(Err(anyhow!(+ "managed run interrupted before the agent started"+ )));+ }let started_at = SystemTime::now();let mut command = Command::new(&plan.program);@@ -249,7 +292,13 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {)],exit_code: None,};- let _ = finish_with_retry(&endpoint, &run_path, &request).await;+ let finished = finish_with_retry(&endpoint, &run_path, &request)+ .await+ .is_ok();+ interrupt_task.abort();+ if !finished {+ cancel_managed_run_after_failure(&endpoint, &run_path).await;+ }return Err(anyhow!(spawn_message)).context(format!("starting managed {} executable {}",harness.as_str(),@@ -273,7 +322,7 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {heartbeat.tick().await;let status = loop {tokio::select! {- result = child.wait() => break result.context("waiting for managed harness")?,+ result = child.wait() => break acquired_try!(result.context("waiting for managed harness")),_ = heartbeat.tick() => {if let Err(error) = post_empty(&endpoint, &format!("{run_path}/heartbeat")).await {eprintln!("ai-memory: managed workstream heartbeat failed: {error}");@@ -290,15 +339,17 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {} else {None};- let native_session_id = resolve_native_session_after_run(- &plan,- harness,- &home,- &repository.cwd,- started_at,- server_status.as_ref(),- )- .await?;+ let native_session_id = acquired_try!(+ resolve_native_session_after_run(+ &plan,+ harness,+ &home,+ &repository.cwd,+ started_at,+ server_status.as_ref(),+ )+ .await+ );let transcript = if plan.mode == LaunchMode::Session {let source_cursor = if native_session_id.as_deref() == prepared.native_session_id.as_deref(){@@ -321,14 +372,16 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {let checkpoint = inspect_repository(&repository.cwd).map(|identity| identity.checkpoint).unwrap_or(repository.checkpoint);- let imported = import_batches(- &endpoint,- &run_path,- transcript,- checkpoint,- Some(exit_code),- )- .await?;+ let imported = acquired_try!(+ import_batches(+ &endpoint,+ &run_path,+ transcript,+ checkpoint,+ Some(exit_code),+ )+ .await+ );if plan.mode == LaunchMode::Session&& prepared.sync_through > prepared.sync_after@@ -342,9 +395,30 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {"ai-memory: workstream '{}' saved {imported} new event(s)",prepared.workstream_name);+ interrupt_task.abort();Ok(exit_code)}+async fn capture_interrupts(interrupted: Arc<AtomicBool>) {+ while tokio::signal::ctrl_c().await.is_ok() {+ interrupted.store(true, Ordering::SeqCst);+ }+}++async fn cancel_managed_run_after_failure(endpoint: &ServerEndpoint, run_path: &str) {+ if let Err(error) = post_empty_with_retry(+ endpoint,+ &format!("{run_path}/cancel"),+ "releasing the managed workstream after a launcher failure",+ )+ .await+ {+ eprintln!(+ "ai-memory: {error}; the orphaned lease will expire automatically within 90 seconds"+ );+ }+}+async fn resolve_native_session_after_run(plan: &LaunchPlan,harness: ManagedHarness,@@ -817,6 +891,60 @@ async fn finish_with_retry(.context("persisting the managed transcript; the native process has already exited")}+async fn prepare_managed_run(+ endpoint: &ServerEndpoint,+ request: &PrepareManagedRunRequest,+) -> Result<PrepareManagedRunResponse> {+ prepare_managed_run_with_retry(+ endpoint,+ request,+ PREPARE_BUSY_RETRY_WINDOW,+ PREPARE_BUSY_RETRY_INTERVAL,+ )+ .await+}++async fn prepare_managed_run_with_retry(+ endpoint: &ServerEndpoint,+ request: &PrepareManagedRunRequest,+ retry_window: Duration,+ retry_interval: Duration,+) -> Result<PrepareManagedRunResponse> {+ let deadline = tokio::time::Instant::now() + retry_window;+ let mut reported_wait = false;+ loop {+ match post_json(endpoint, "/workstream/runs", request).await {+ Ok(response) => return Ok(response),+ Err(error)+ if is_active_workstream_conflict(&error)+ && tokio::time::Instant::now() < deadline =>+ {+ if !reported_wait {+ eprintln!(+ "ai-memory: another launcher owns this workstream; waiting briefly in case it is finalizing"+ );+ reported_wait = true;+ }+ tokio::time::sleep(retry_interval).await;+ }+ Err(error) => return Err(error),+ }+ }+}++fn is_active_workstream_conflict(error: &anyhow::Error) -> bool {+ let Some(response) = error.downcast_ref::<ServerResponseError>() else {+ return false;+ };+ if response.status() != reqwest::StatusCode::CONFLICT {+ return false;+ }+ serde_json::from_str::<serde_json::Value>(response.body())+ .ok()+ .and_then(|body| body.get("error")?.as_str().map(str::to_owned))+ .is_some_and(|message| message.starts_with("workstream is already active:"))+}+async fn post_empty_with_retry(endpoint: &ServerEndpoint, path: &str, label: &str) -> Result<()> {let mut last_error = None;for attempt in 0..3 {@@ -834,8 +962,14 @@ fn nonempty_session(value: &str) -> Option<String> {}fn lease_owner() -> String {- let host = std::env::var("HOSTNAME").unwrap_or_else(|_| "localhost".to_string());- format!("{host}:{}", std::process::id())+ let host = sysinfo::System::host_name()+ .or_else(|| std::env::var("HOSTNAME").ok())+ .filter(|value| !value.trim().is_empty());+ lease_owner_label(host.as_deref(), std::process::id())+}++fn lease_owner_label(host: Option<&str>, process_id: u32) -> String {+ format!("{}:{process_id}", host.unwrap_or("localhost"))}const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {@@ -864,7 +998,13 @@ const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness>mod tests {use std::ffi::{OsStr, OsString};use std::io::Cursor;+ use std::sync::atomic::AtomicUsize;+ use ai_memory_core::{ManagedRunId, WorkstreamId};+ use axum::Router;+ use axum::http::StatusCode;+ use axum::response::IntoResponse as _;+ use axum::routing::post;use clap::Parser as _;use super::*;@@ -883,6 +1023,77 @@ mod tests {]}+ #[test]+ fn lease_owner_uses_the_resolved_host_and_process() {+ assert_eq!(lease_owner_label(Some("workstation"), 42), "workstation:42");+ assert_eq!(lease_owner_label(None, 42), "localhost:42");+ }++ #[tokio::test]+ async fn prepare_waits_for_a_previous_launcher_to_finish() {+ let attempts = Arc::new(AtomicUsize::new(0));+ let handler_attempts = Arc::clone(&attempts);+ let app = Router::new().route(+ "/workstream/runs",+ post(move || {+ let attempts = Arc::clone(&handler_attempts);+ async move {+ if attempts.fetch_add(1, Ordering::SeqCst) < 2 {+ return (+ StatusCode::CONFLICT,+ axum::Json(serde_json::json!({+ "error": "workstream is already active: owned by workstation:42"+ })),+ )+ .into_response();+ }+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: Some(AgentKind::Codex),+ native_session_id: None,+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ })+ .into_response()+ }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let endpoint = ServerEndpoint::from_pair(Some(format!("http://{address}")), None);+ let request = PrepareManagedRunRequest {+ workspace: "default".into(),+ project: "project".into(),+ cwd: "/tmp/project".into(),+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ agent: AgentKind::Codex,+ automatic_harness: false,+ available_agents: Vec::new(),+ workstream: None,+ new_workstream: None,+ lease_owner: "workstation:43".into(),+ };++ let prepared = prepare_managed_run_with_retry(+ &endpoint,+ &request,+ Duration::from_millis(100),+ Duration::from_millis(1),+ )+ .await+ .unwrap();++ assert_eq!(prepared.workstream_name, "default");+ assert_eq!(attempts.load(Ordering::SeqCst), 3);+ server.abort();+ }+fn auto_candidate(harness: ManagedHarness, updated: u64) -> AutoSessionCandidate {AutoSessionCandidate {harness,diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex 0d2e984d..2b27275f 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -10,16 +10,48 @@//! `AI_MEMORY_AUTH_TOKEN` exactly once; this module consumes those values//! and can fall back to the stored OIDC device-flow token used by native hooks.+use std::fmt;use std::io::{BufWriter, Write as _};use std::path::Path;-use anyhow::{Context, Result, bail};+use anyhow::{Context, Result};use serde::Serialize;use serde::de::DeserializeOwned;use crate::commands::serve::normalize_prefix;use crate::config::{Config, DEFAULT_SERVER_URL};+/// Non-success response returned by the configured ai-memory server.+#[derive(Debug)]+pub(crate) struct ServerResponseError {+ status: reqwest::StatusCode,+ body: String,+}++impl ServerResponseError {+ #[must_use]+ pub(crate) const fn status(&self) -> reqwest::StatusCode {+ self.status+ }++ #[must_use]+ pub(crate) fn body(&self) -> &str {+ &self.body+ }+}++impl fmt::Display for ServerResponseError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(formatter, "server returned {}: {}", self.status, self.body)+ }+}++impl std::error::Error for ServerResponseError {}++fn server_response_error(status: reqwest::StatusCode, body: String) -> anyhow::Error {+ ServerResponseError { status, body }.into()+}+/// Resolved server target — origin URL + base-path prefix + optional bearer token.#[derive(Debug, Clone)]pub struct ServerEndpoint {@@ -181,7 +213,7 @@ pub async fn get_json<T: DeserializeOwned>(let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();- bail!("server returned {status}: {body}");+ return Err(server_response_error(status, body));}resp.json::<T>().await@@ -216,7 +248,7 @@ pub async fn post_json_no_content<B: Serialize>(let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();- bail!("server returned {status}: {body}");+ return Err(server_response_error(status, body));}Ok(())}@@ -233,7 +265,7 @@ pub async fn post_empty(endpoint: &ServerEndpoint, path: &str) -> Result<()> {let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();- bail!("server returned {status}: {body}");+ return Err(server_response_error(status, body));}Ok(())}@@ -259,7 +291,7 @@ pub async fn post_json_with_query<B: Serialize, T: DeserializeOwned>(let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();- bail!("server returned {status}: {body}");+ return Err(server_response_error(status, body));}resp.json::<T>().await@@ -349,7 +381,7 @@ pub async fn post_to_file(endpoint: &ServerEndpoint, path: &str, dest: &Path) ->let status = resp.status();if !status.is_success() {let body = resp.text().await.unwrap_or_default();- bail!("server returned {status}: {body}");+ return Err(server_response_error(status, body));}let file = std::fs::File::create(dest).with_context(|| format!("creating output file {}", dest.display()))?;diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 9d6ccadf..413ad34e 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -59,6 +59,7 @@ async fn main() -> Result<()> {info!(version = env!("CARGO_PKG_VERSION"),+ server_url = %config.server_url,data_dir = %config.data_dir.display(),bind = %config.bind,"ai-memory starting",diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 1c4e90ce..a1952d86 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -51,6 +51,7 @@ 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}/cancel", post(cancel_run)).route("/workstream/runs/{run_id}/context", post(run_context)).route("/workstream/runs/{run_id}/context/accept",@@ -273,6 +274,24 @@ async fn heartbeat_run(}}+async fn cancel_run(+ 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(),+ };+ match state.writer.cancel_managed_run(run_id).await {+ Ok(_) => StatusCode::NO_CONTENT.into_response(),+ Err(failure) => store_error_response(failure),+ }+}+async fn run_context(State(state): State<WorkstreamState>,level: Option<Extension<AuthLevel>>,@@ -809,6 +828,31 @@ mod tests {assert!(!prepared.may_adopt_existing_session);}+ #[tokio::test]+ async fn cancel_endpoint_is_idempotent_and_releases_the_workstream() {+ 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 input = prepare_input(workspace_id, project_id, AgentKind::Codex, "launcher");+ let prepared = store+ .writer+ .prepare_workstream_run(input.clone())+ .await+ .unwrap();++ for _ in 0..2 {+ let response = cancel_run(+ State(state.clone()),+ None,+ AxumPath(prepared.run_id.to_string()),+ )+ .await;+ assert_eq!(response.status(), StatusCode::NO_CONTENT);+ }+ store.writer.prepare_workstream_run(input).await.unwrap();+ }+#[tokio::test]async fn crush_context_fetch_is_repeatable_until_explicit_accept() {let temp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex b1ab282b..46713d87 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -3504,6 +3504,62 @@ mod tests {assert_eq!(undelivered.sync_through, 1);}+ #[tokio::test]+ async fn managed_run_cancel_releases_the_lease_immediately() {+ 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-cancel", None)+ .await+ .unwrap();+ let prepare = PrepareWorkstreamRun {+ workspace_id: workspace,+ project_id: project,+ repo_fingerprint: "repo".into(),+ 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(),+ };+ let first = store+ .writer+ .prepare_workstream_run(prepare.clone())+ .await+ .unwrap();+ assert!(+ store+ .writer+ .prepare_workstream_run(prepare.clone())+ .await+ .is_err()+ );+ assert!(store.writer.cancel_managed_run(first.run_id).await.unwrap());+ assert!(+ !store.writer.cancel_managed_run(first.run_id).await.unwrap(),+ "cancel is idempotent once the run is no longer active"+ );+ assert_eq!(+ store+ .reader+ .managed_run_status(first.run_id)+ .await+ .unwrap()+ .unwrap()+ .state,+ "expired"+ );+ store.writer.prepare_workstream_run(prepare).await.unwrap();+ }+#[tokio::test]async fn managed_adoption_stops_after_any_harness_links_the_workstream() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsindex 6c452c57..b792d89c 100644--- a/crates/ai-memory-store/src/workstream.rs+++ b/crates/ai-memory-store/src/workstream.rs@@ -420,6 +420,17 @@ pub(crate) fn heartbeat(conn: &mut Connection, run_id: ManagedRunId) -> StoreResOk(changed > 0)}+/// Release an active managed-run lease without importing any events.+pub(crate) fn cancel_run(conn: &mut Connection, run_id: ManagedRunId) -> StoreResult<bool> {+ let now = Timestamp::now().as_microsecond();+ let changed = conn.execute(+ "UPDATE managed_runs SET state = 'expired', ended_at = ?1, lease_expires_at = ?1 \+ WHERE id = ?2 AND state = 'active'",+ params![now, run_id.as_bytes()],+ )?;+ Ok(changed > 0)+}+/// Link the native session reported by a managed child hook.pub(crate) fn link_native_session(conn: &mut Connection,diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 986c7790..c1693ff6 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -269,6 +269,10 @@ pub(crate) enum WriteCmd {run_id: ManagedRunId,reply: oneshot::Sender<StoreResult<bool>>,},+ CancelManagedRun {+ run_id: ManagedRunId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },LinkManagedRunSession {run_id: ManagedRunId,agent: AgentKind,@@ -1072,6 +1076,14 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Release a managed-run lease after a handled launcher failure.+ pub async fn cancel_managed_run(&self, run_id: ManagedRunId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::CancelManagedRun { run_id, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Attach the harness-native session observed by a managed SessionStart.pub async fn link_managed_run_session(&self,@@ -1472,6 +1484,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = crate::workstream::heartbeat(&mut conn, run_id);send_or_warn(reply, result, "heartbeat_managed_run");}+ WriteCmd::CancelManagedRun { run_id, reply } => {+ let result = crate::workstream::cancel_run(&mut conn, run_id);+ send_or_warn(reply, result, "cancel_managed_run");+ }WriteCmd::LinkManagedRunSession {run_id,agent,diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 40be546b..00e19fe5 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -117,7 +117,9 @@ the bounded startup packet. An interactive empty workstream may adopt acheckout-matching native session once. Eligibility comes from authoritativeledger/session state: after any harness establishes the workstream, a newlyjoining harness starts fresh and receives portable history instead of adopting-unrelated old native history. See [Managed cross-harness+unrelated old native history. Handled launcher failures cancel their lease;+normal reopen retries brief finalization conflicts, while an unclean process+death remains bounded by the renewable lease expiry. See [Managed cross-harnessworkstreams](managed-workstreams.md).## Hook event vocabularydiff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex dc7552f2..42934ad1 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -179,17 +179,28 @@ specific 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+`AI_MEMORY_SERVER_URL`, and authentication environment. The native client's+startup log shows `server_url` as well as its local config paths; `data_dir` and+`bind` describe local defaults and do not override a configured remote server.+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 beupgraded separately.-If a client is killed before final import, its lease expires. A later managed-run starts from the last committed adapter cursor, so already linked native-sessions can import the missing tail without duplicating earlier events. A-server or authentication failure before process launch is fatal; ai-memory does-not silently start an unmanaged agent.+On a normal exit, ai-memory imports the transcript and closes the lease before+returning. Handled setup, launch, or import failures cancel the lease+immediately. A new launch retries an active-workstream conflict briefly so a+previous launcher can finish; if another harness is genuinely still running,+the conflict remains and concurrent writers are still rejected. Terminal+interrupts continue to reach the child while the parent stays alive to finish+or cancel the run.++If the client is terminated without cleanup, such as with `kill -9`, its lease+expires within 90 seconds. A later managed run starts from the last committed+adapter cursor, so already linked native sessions can import the missing tail+without duplicating earlier events. A server or authentication failure before+process launch is fatal; ai-memory does not silently start an unmanaged agent.## Privacy and storage boundariesdiff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.shindex 1fceee21..c9ff2722 100755--- a/scripts/managed-workstream-acceptance.sh+++ b/scripts/managed-workstream-acceptance.sh@@ -162,6 +162,7 @@ set -e(cd "$REPO"AI_MEMORY_ACCEPTANCE_FAKE_MODE=lease \+ AI_MEMORY_ACCEPTANCE_SLEEP=7 \AI_MEMORY_ACCEPTANCE_STARTED="$TMP/lease-started" \"$BIN" --data-dir "$DATA" run --new edge-lease --executable "$FAKE" \codex >"$LOGS/edge-lease-owner.log" 2>&1@@ -264,6 +265,28 @@ auto_claude_id=${auto_claude_first[1]}diff -u <(printf '%s\n' --resume "$auto_claude_id") \"$TMP/auto-managed-precedence-argv.log"+# A handled failure after lease acquisition must release immediately. A+# malformed Crush config fails after context fetch; the next run below would+# hit a stale 409 if cancellation were missing.+BAD_CRUSH_CONFIG="$CONFIG/bad-crush"+mkdir -p "$BAD_CRUSH_CONFIG"+printf '{not-json\n' >"$BAD_CRUSH_CONFIG/crush.json"+set +e+(+ cd "$REPO"+ HOME="$AUTO_HOME" CRUSH_GLOBAL_CONFIG="$BAD_CRUSH_CONFIG" \+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=crush \+ "$BIN" --data-dir "$DATA" run --workspace edge-auto --project edge-auto \+ --executable "$FAKE" crush >"$LOGS/edge-crush-invalid-config.log" 2>&1+)+bad_crush_code=$?+set -e+[ "$bad_crush_code" -ne 0 ] || {+ printf 'malformed Crush config unexpectedly succeeded\n' >&2+ exit 1+}+grep -q 'parsing Crush config' "$LOGS/edge-crush-invalid-config.log"+# Crush has no SessionStart hook. Verify the launcher fetches the packet into a# temporary supported global-context config, then removes it after exit.(