Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(run): launch the harness offline when the server is unreachable (#NNN)
AkitaOnRailsede7c661b314
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7d8355ba..50be7864 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Added `--require-server` to `ai-memory run` (plus `run.require_server` in+ config.toml and `AI_MEMORY_RUN_REQUIRE_SERVER=true`) to restore fail-closed+ launches when the server is unreachable: the reachability probe still runs,+ and an unreachable server returns the existing "could not reach …"+ diagnosis — including "the agent was not started" — without starting the+ harness. (#NNN)- Added bounded install-wide identity and component-safe path routes in the exactoperator-home `.ai-memory.toml`. Exact hostful repository identity wins thelongest lexical path route, local non-home markers stay authoritative, aliases@@ -251,6 +257,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0size limits remain. (#1092)### Changed+- Changed `ai-memory run` to no longer fail closed when the server is+ unreachable: a bounded ~2s reachability probe (any HTTP answer counts as+ reachable, so pre-`/healthz` servers pass) downgrades the launch with one+ loud warning instead of aborting it. The harness starts with no server work+ at all (no lease, link, context, heartbeat, status, finish, or import),+ lifecycle hooks keep spooling locally with the bounded retention surfaced in+ the warning, auto-wire installs hooks but defers the MCP registration to the+ next online launch, sessions resume only through an explicit native selector+ (no lease means no mutual exclusion), the child runs without+ `AI_MEMORY_RUN_ID`/`AI_MEMORY_WORKSTREAM_ID` so its session cannot be+ misattributed, and the child's exit code is returned with a local+ spool-health account. A server that dies mid-run, after the child exits, no+ longer discards the exit code either: the unimported transcript is+ downgraded to a warning naming the exact `ai-memory finalize-session` repair+ command, while protocol-level failures still fail hard. (#NNN)- Changed static CLI/MCP project-name resolution to accept an existingrepository's canonical hostless path name and its v2 basename compatibilitykey. Reads remain find-only; an authorized write through the canonical keydiff --git a/README.md b/README.mdindex abdd8c03..8075121e 100644--- a/README.md+++ b/README.md@@ -372,7 +372,10 @@ ai-memory hooks + MCP if they are missing (so capture and recall just work —no separate `install-hooks`/`install-mcp` step to forget), it wires the rightproject scope by construction, and it adds cross-harness *session* continuity ontop of shared memory. Everything is idempotent and one-time per harness and-config home.+config home. If the server is unreachable, `run` warns and launches anyway+with local capture spooling (see [Degraded offline+launches](docs/managed-workstreams.md#degraded-offline-launches)); pass+`--require-server` to fail closed instead.```bashai-memory run claudediff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex c214daf7..44a4d48b 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -435,6 +435,14 @@ pub struct RunArgs {/// `AI_MEMORY_RUN_AUTOWIRE=false`) to launch without touching harness config.#[arg(long)]pub no_autowire: bool,+ /// Refuse to launch when the ai-memory server is unreachable, restoring+ /// the pre-degraded-launch fail-closed behavior. Without this flag an+ /// unreachable server downgrades the launch: the harness still starts+ /// (hooks spool locally, no workstream lease or context is delivered) and+ /// the child's exit code is returned. Also set with `run.require_server+ /// = true` in config.toml or `AI_MEMORY_RUN_REQUIRE_SERVER=true`.+ #[arg(long)]+ pub require_server: bool,/// Apply a named env-only launch profile from/// `[run.profiles.<name>.env]` in config.toml. Must precede `harness`;/// a later `--env-file` or `--env` entry wins on the same key.diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rsindex a1b1c87e..8b1aeff7 100644--- a/crates/ai-memory-cli/src/commands/continue_session.rs+++ b/crates/ai-memory-cli/src/commands/continue_session.rs@@ -78,6 +78,7 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {fresh: args.fresh,force_unlock: false,no_autowire: false,+ require_server: false,profile: None,env: Vec::new(),env_file: None,diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rsindex f6e62f60..32405df9 100644--- a/crates/ai-memory-cli/src/commands/resume.rs+++ b/crates/ai-memory-cli/src/commands/resume.rs@@ -94,6 +94,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {fresh: args.fresh,force_unlock: false,no_autowire: false,+ require_server: false,profile: None,env: Vec::new(),env_file: None,diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 4ee47d6a..d1826312 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -36,7 +36,8 @@ use crate::cli::{RunArgs, RunHarnessChoice};use crate::commands::{path_util, resolve_scope};use crate::config::Config;use crate::http_client::{- ServerEndpoint, ServerResponseError, get_json, post_empty, post_json, post_json_no_content,+ ServerEndpoint, ServerProbe, ServerResponseError, augment_connect_error, get_json, post_empty,+ post_json, post_json_no_content, probe_server,};const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);@@ -266,6 +267,10 @@ struct RunOutcome {interactive_session: bool,mode: LaunchMode,workstream_name: String,+ /// A degraded launch made without the server: it has no workstream, so+ /// the post-run switch/rerun menu (which reuses the workstream name)+ /// must not be offered.+ degraded: bool,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -328,6 +333,7 @@ fn should_offer_after_run(outcome.exit_code == 0&& outcome.mode == LaunchMode::Session&& outcome.interactive_session+ && !outcome.degraded&& interactive_terminal&& !custom_executable}@@ -601,6 +607,42 @@ async fn run_once_with_wiring(}let may_adopt_native_session = args.new_workstream.is_none() && !force_fresh;let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ // Probe before any server work: a homelab down for maintenance must+ // downgrade (or, with --require-server, fail) in ~2s, not after a+ // TCP-level timeout on the prepare POST. Any HTTP answer counts as+ // reachable — including 404/405 from a server older than /healthz.+ let require_server = args.require_server || config.run.require_server;+ if let ServerProbe::Unreachable(probe_error) = probe_server(&endpoint).await {+ if require_server {+ // Fail closed exactly like the prepare below would: same+ // augmented diagnosis, same "the agent was not started" context.+ let url = endpoint.build_url("/workstream/runs");+ return Err(augment_connect_error(probe_error, &endpoint, &url)+ .context("opening managed workstream; the agent was not started"));+ }+ return run_degraded_offline(+ config,+ DegradedLaunch {+ endpoint: &endpoint,+ cwd: &repository.cwd,+ home: &home,+ harness: provisional_harness,+ executable: executable.clone(),+ native_args: &native_args,+ force_fresh,+ yolo_modes,+ jail_plan: &jail_plan,+ ai_jail: ai_jail.as_deref(),+ jail_facts: &jail_facts,+ no_autowire,+ child_env: &child_env,+ run_env: &run_env,+ wire_overrides,+ },+ probe_error,+ )+ .await;+ }let prepare = PrepareManagedRunRequest {workspace: workspace.clone(),project: project.clone(),@@ -723,8 +765,7 @@ async fn run_once_with_wiring(&jail_plan,ai_jail.as_deref(),&jail_facts,- &endpoint,- &run_path,+ Some((&endpoint, &run_path)),&interrupted_before_spawn,).await@@ -934,6 +975,7 @@ async fn run_once_with_wiring(&wire_env,&wire_child_env,&repository.cwd,+ false,);}// A Kiro v3 resume that dropped `KIRO_HOME` runs against the default store.@@ -1197,17 +1239,45 @@ async fn run_once_with_wiring(let checkpoint = inspect_repository(&repository.cwd).map(|identity| identity.checkpoint).unwrap_or(repository.checkpoint);- let imported = acquired_try!(- import_batches(- &endpoint,- &run_path,- transcript,- checkpoint,- Some(exit_code),- &privacy,- )- .await- );+ let imported = match import_batches(+ &endpoint,+ &run_path,+ transcript,+ checkpoint,+ Some(exit_code),+ &privacy,+ )+ .await+ {+ Ok(imported) => imported,+ // The child has already exited; an unreachable server must not turn+ // its exit code into an error. The transcript is not recorded, so say+ // how to repair it once the server is back. Protocol-level failures+ // (a live server's 4xx, an unparsable body) keep the hard fail: they+ // need an operator, not a server restart.+ Err(error) if is_unreachable_error(&error) => {+ eprintln!(+ "{}",+ offline_import_warning(+ harness,+ native_session_id.as_deref(),+ &workspace,+ &project,+ &error,+ )+ );+ interrupt_task.abort();+ return Ok(RunOutcome {+ exit_code,+ harness,+ interactive_session,+ mode: plan.mode,+ workstream_name: prepared.workstream_name,+ degraded: false,+ });+ }+ Err(error) => acquired_try!(Err(error)),+ };// Sessions whose id was unknown at launch (a fresh Codex session, say) are// linked by the finish request above, so record their store here.@@ -1262,18 +1332,255 @@ async fn run_once_with_wiring(interactive_session,mode: plan.mode,workstream_name: prepared.workstream_name,+ degraded: false,})}/// How long finalizing may hold up the harness's exit code.const FINALIZE_TIMEOUT: Duration = Duration::from_secs(30);+/// Everything the local half of [`run_once_with_wiring`] resolved before the+/// server probe: the inputs a degraded (server-unreachable) launch still has.+struct DegradedLaunch<'a> {+ endpoint: &'a ServerEndpoint,+ cwd: &'a Path,+ home: &'a Path,+ harness: ManagedHarness,+ executable: Option<OsString>,+ native_args: &'a [OsString],+ force_fresh: bool,+ yolo_modes: YoloModes,+ jail_plan: &'a JailPlan,+ ai_jail: Option<&'a Path>,+ jail_facts: &'a JailHostFacts,+ no_autowire: bool,+ child_env: &'a EffectiveChildEnv,+ run_env: &'a [(String, String)],+ wire_overrides: &'a super::run_autowire::WireOverrides,+}++/// Launch the harness without the server: warn loudly, do no server work at+/// all, and return the child's exit code. See `docs/managed-workstreams.md`+/// ("Degraded offline launches") for the exact lost/kept contract.+async fn run_degraded_offline(+ config: &Config,+ launch: DegradedLaunch<'_>,+ probe_error: reqwest::Error,+) -> Result<RunOutcome> {+ eprintln!(+ "{}",+ offline_launch_warning(+ launch.endpoint,+ launch.harness,+ config.hook_spool.max_attempts,+ probe_error,+ )+ );+ let interrupted = CancellationToken::new();+ let interrupt_task = tokio::spawn(capture_interrupts(interrupted.clone()));+ let outcome = degraded_launch(config, &launch, &interrupted).await;+ interrupt_task.abort();+ outcome+}++async fn degraded_launch(+ config: &Config,+ launch: &DegradedLaunch<'_>,+ interrupted: &CancellationToken,+) -> Result<RunOutcome> {+ // No lease exists, so there is no mutual exclusion against another+ // launcher in this checkout. The launch therefore never adopts or resumes+ // a session implicitly — only an explicit native session selector+ // resumes, because the user named the session themselves and no+ // arbitration is needed. Everything else starts a fresh session.+ let (mut plan, _) = build_preflighted_launch_plan(+ launch.harness,+ launch.executable.clone(),+ launch.native_args.to_vec(),+ None,+ launch.force_fresh,+ launch.home,+ launch.cwd,+ launch.child_env,+ )?;+ // The `--yolo` warning and ai-jail offer still apply; a degraded launch+ // just has no prepared lease for the re-exec to release.+ confirm_yolo_and_maybe_reexec(+ launch.jail_plan,+ launch.ai_jail,+ launch.jail_facts,+ None,+ interrupted,+ )+ .await?;+ if launch.yolo_modes.yolo {+ // Same Kiro caveat as the online path: v3 has no verified dangerous+ // mode, so the wrapper maps nothing there and says so.+ if launch.harness == ManagedHarness::KiroV3+ || launch.harness == ManagedHarness::Kiro && kiro_selects_non_default_engine(&plan.args)+ {+ eprintln!(+ "ai-memory: --yolo maps to no verified flag on the selected Kiro engine \+ (v3 replaced --trust-all-tools with permissions.yaml); launching without it"+ );+ }+ apply_yolo(launch.harness, &mut plan.args);+ }+ if launch.yolo_modes.claude_true_yolo && launch.harness == ManagedHarness::Claude {+ apply_claude_true_yolo(launch.harness, &mut plan.args);+ }+ let launch_env = |name: &str| launch.child_env.get(name).map(OsStr::to_os_string);+ // Auto-wire keeps the hook install (it is local and idempotent, and+ // capture must spool offline) but skips the MCP registration — pointing+ // the harness at a server that just proved unreachable would degrade+ // every later start for no recall. The unwritten sentinel lets the next+ // online launch complete the wiring.+ if config.run_autowire && !launch.no_autowire {+ let wire_env = autowire_env(launch.harness, launch.run_env, &plan.args, &launch_env);+ let wire_child_env = launch.child_env.with_additional_overrides(&wire_env);+ super::run_autowire::ensure_wired_with_env(+ config,+ launch.harness,+ launch.wire_overrides,+ &wire_env,+ &wire_child_env,+ launch.cwd,+ true,+ );+ }+ let executable_search = launch.child_env.executable_search();+ let program = resolve_program(&plan.program, executable_search)+ .unwrap_or_else(|| plan.program.clone().into());+ let mut command = Command::new(&program);+ launch.child_env.apply_to_tokio(&mut command);+ command.args(&plan.args).current_dir(launch.cwd);+ // No AI_MEMORY_RUN_ID / AI_MEMORY_WORKSTREAM_ID: no run exists on the+ // server, and the SessionEnd hook appends `managed_run` when the run id+ // is set — attributing the offline session to a run that never happened.+ // Removed explicitly: a launcher itself started under a managed run would+ // otherwise leak its own (now stale) ids into the offline child.+ // AI_MEMORY_HOOK_URL stays so the hooks spool against the right server.+ command+ .env_remove("AI_MEMORY_RUN_ID")+ .env_remove("AI_MEMORY_WORKSTREAM_ID")+ .env("AI_MEMORY_HOOK_URL", launch.endpoint.build_url(""))+ .stdin(Stdio::inherit())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit());+ for name in blank_home_overrides(launch.harness, &launch_env) {+ command.env_remove(name);+ }+ let child = command.spawn().map_err(|spawn_error| {+ let spawn_message = spawn_error.to_string();+ anyhow!(spawn_message).context(format!(+ "starting managed {} executable {}",+ launch.harness.as_str(),+ plan.program.to_string_lossy()+ ))+ })?;+ let mut child = child;+ let status = child.wait().await.context("waiting for managed harness")?;+ let exit_code = status.code().unwrap_or(1);+ let spool = super::hook_spool::spool_health(&super::hook_spool::spool_dir(&config.data_dir));+ eprintln!(+ "ai-memory: this run was not recorded on the server; {}",+ spooled_events_note(&spool)+ );+ Ok(RunOutcome {+ exit_code,+ harness: launch.harness,+ interactive_session: is_interactive_session_invocation(launch.harness, launch.native_args),+ mode: plan.mode,+ workstream_name: "(offline)".to_string(),+ degraded: true,+ })+}++/// The one-line account of what remains in the local hook spool after a+/// degraded run, mirroring `ai-memory status`'s offline-spool phrasing.+fn spooled_events_note(spool: &super::hook_spool::SpoolHealth) -> String {+ match spool.pending {+ 0 => "no hook events remain spooled locally".to_string(),+ 1 => format!(+ "1 hook event remains spooled locally (oldest {})",+ super::status::spool_age_line(spool.oldest_age_ms),+ ),+ pending => format!(+ "{pending} hook events remain spooled locally (oldest {})",+ super::status::spool_age_line(spool.oldest_age_ms),+ ),+ }+}++/// The loud one-time warning a degraded launch prints: what is lost, what+/// still works, and how the local spool is bounded. Reuses+/// [`augment_connect_error`]'s diagnosis so the operator sees the same+/// server-URL explanation a hard failure would print.+fn offline_launch_warning(+ endpoint: &ServerEndpoint,+ harness: ManagedHarness,+ spool_max_attempts: u32,+ probe_error: reqwest::Error,+) -> String {+ let diagnosis = augment_connect_error(probe_error, endpoint, &endpoint.build_url(""));+ format!(+ "ai-memory: WARNING: the ai-memory server at {} is unreachable — launching {} \+ WITHOUT server support.\n {diagnosis:#}\n Lost this run: no workstream lease or \+ cross-harness context, no transcript import, no handoff delivery.\n Still works: \+ lifecycle hooks spool events locally and drain when the server returns; an existing \+ MCP registration degrades to no-recall rather than blocking the session.\n Spooled \+ events are dropped after {} failed drain passes, 7 days, or the 10,000-file spool \+ cap (set AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS=0 for a planned outage). Pass \+ --require-server to fail instead of degrading.",+ endpoint.url,+ harness.as_str(),+ spool_max_attempts,+ )+}++/// The warning printed when the server became unreachable after the child+/// exited, so its transcript could not be imported: the child's exit code is+/// preserved and the run is repairable by hand once the server returns.+fn offline_import_warning(+ harness: ManagedHarness,+ native_session_id: Option<&str>,+ workspace: &str,+ project: &str,+ error: &anyhow::Error,+) -> String {+ let repair = match native_session_id {+ Some(session) => format!(+ "ai-memory finalize-session --agent {} --reopen --session-id {} --workspace {} --project {}",+ harness.agent_kind().as_str(),+ SessionId::from_native(session),+ super::render_shared::shell_quote(workspace),+ super::render_shared::shell_quote(project),+ ),+ None => "ai-memory finalize-session (see --help)".to_string(),+ };+ format!(+ "ai-memory: warning: {error:#}; the transcript was not imported and the orphaned lease \+ will expire automatically within 90 seconds. The harness exit code is preserved. \+ Repair it once the server is back with `{repair}`."+ )+}++/// Whether a managed-run request failed because the server could not be+/// reached at all (connect error or timeout) rather than answering with a+/// protocol-level failure. Only the former may be downgraded to a warning+/// after the child has exited: an answered error needs an operator, while an+/// unreachable one only needs the server back.+fn is_unreachable_error(error: &anyhow::Error) -> bool {+ let answered = error+ .chain()+ .any(|cause| cause.downcast_ref::<ServerResponseError>().is_some());+ let transport = error+ .chain()+ .any(|cause| cause.downcast_ref::<reqwest::Error>().is_some());+ !answered && transport+}+/// Finalizes the run's own session when the harness has no native session-end-/// hook, which would otherwise leave it open until a manual-/// `ai-memory finalize-session` (#941). The harness has exited, so the session-/// is over for this run.-/// Returns the stored session id and the ids finalized, or `None` when there-/// is nothing to do.async fn finalize_hookless_session(config: &Config,harness: ManagedHarness,@@ -1735,12 +2042,13 @@ fn jail_summary(toggles: &[JailToggleChoice], project_config: bool) -> String {/// the user declined the ai-jail offer) or, on accepting the offer and the/// checklist, cancels this process's already-prepared managed run and re-execs/// the original invocation under `ai-jail` — which never returns on success.+/// `lease` is the prepared run to release before that re-exec; a degraded+/// offline launch passes `None` (it holds no lease).async fn confirm_yolo_and_maybe_reexec(plan: &JailPlan,ai_jail: Option<&Path>,facts: &JailHostFacts,- endpoint: &ServerEndpoint,- run_path: &str,+ lease: Option<(&ServerEndpoint, &str)>,interrupted: &CancellationToken,) -> Result<()> {if !plan.warn {@@ -1791,8 +2099,10 @@ async fn confirm_yolo_and_maybe_reexec(// The re-exec replaces this process (or, off Unix, this process exits// once the child does), so its own prepared lease must be released here// rather than left to the 90s orphan timeout — the jailed re-run opens- // its own workstream cleanly.- cancel_managed_run_after_failure(endpoint, run_path).await;+ // its own workstream cleanly. A degraded launch holds no lease.+ if let Some((endpoint, run_path)) = lease {+ cancel_managed_run_after_failure(endpoint, run_path).await;+ }Err(exec_under_ai_jail(ai_jail,&support,@@ -3436,6 +3746,7 @@ mod tests {use super::*;use crate::cli::{Cli, Command as CliCommand};+ use crate::commands::run_autowire::WireOverrides;fn plan(warn: bool, mode: JailMode) -> JailPlan {JailPlan { warn, mode }@@ -3880,6 +4191,7 @@ mod tests {fresh: true,force_unlock: false,no_autowire: true,+ require_server: false,profile: Some("work".into()),env: vec![("MODEL_HOME".into(), "custom".into())],env_file: None,@@ -3962,6 +4274,7 @@ mod tests {interactive_session: true,mode: LaunchMode::Session,workstream_name: "research".into(),+ degraded: false,};assert!(apply_after_run_action(@@ -3990,6 +4303,7 @@ mod tests {interactive_session: true,mode: LaunchMode::Session,workstream_name: "research".into(),+ degraded: false,};assert!(apply_after_run_action(@@ -4010,6 +4324,7 @@ mod tests {interactive_session: true,mode: LaunchMode::Session,workstream_name: "research".into(),+ degraded: false,};assert!(should_offer_after_run(&outcome, true, false));assert!(!should_offer_after_run(&outcome, false, false));@@ -5497,6 +5812,7 @@ mod tests {fresh: false,force_unlock: false,no_autowire: true,+ require_server: false,profile: Some("missing".into()),env: Vec::new(),env_file: None,@@ -5761,6 +6077,7 @@ mod tests {fresh: false,force_unlock: false,no_autowire: true,+ require_server: false,profile: Some("work".into()),env: vec![("CLAUDE_CONFIG_DIR".to_string(), "/from/cli".to_string())],env_file: Some(env_file.clone()),@@ -5791,6 +6108,480 @@ mod tests {server.abort();}+ // ----------------------------------------------------------------+ // Degraded offline launches (server unreachable)+ // ----------------------------------------------------------------++ /// A loopback address that nothing listens on: bind, capture, release.+ /// Rebinding races exist but are vanishingly rare under a test load.+ async fn closed_port_url() -> String {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ drop(listener);+ format!("http://{address}")+ }++ fn repo_hooks() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")+ }++ /// A fake Claude executable: captures its environment and argv, writes+ /// the (empty-session) transcript the launcher waits for, and exits with+ /// `code`.+ #[cfg(unix)]+ fn capture_env_claude(repo: &Path, home: &Path, code: i32) -> PathBuf {+ use std::os::unix::fs::PermissionsExt as _;+ let script = repo.join("capture-harness");+ let transcripts = home+ .join(".claude/projects")+ .join(repo.to_string_lossy().replace('/', "-"));+ std::fs::create_dir_all(&transcripts).unwrap();+ std::fs::write(+ &script,+ format!(+ "#!/bin/sh\nenv > \"$CAPTURED_ENV\"\nprintf '%s\\n' \"$@\" > \"$CAPTURED_ARGS\"\n\+ while [ $# -gt 0 ]; do\n\+ if [ \"$1\" = --session-id ]; then\n\+ printf '{{\"sessionId\":\"%s\",\"cwd\":\"%s\"}}\\n' \"$2\" '{repo}' > '{dir}'/\"$2\".jsonl\n\+ fi\nshift\ndone\nexit {code}\n",+ repo = repo.display(),+ dir = transcripts.display(),+ ),+ )+ .unwrap();+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ script+ }++ /// The common offline-launch fixture: temp home/data/repo, a config whose+ /// server URL points at a closed port, and RunArgs pinned to the fake+ /// Claude executable.+ #[cfg(unix)]+ async fn offline_run_fixture(code: i32) -> (tempfile::TempDir, Config, RunArgs) {+ let temp = tempfile::tempdir().unwrap();+ let home = temp.path().join("home");+ let repo = temp.path().join("repo");+ std::fs::create_dir_all(&home).unwrap();+ std::fs::create_dir_all(&repo).unwrap();+ let script = capture_env_claude(&repo, &home, code);++ let mut config = Config::load(None, Some(temp.path().join("data"))).unwrap();+ config.data_dir = temp.path().join("data");+ config.home_dir = Some(home.to_string_lossy().into_owned());+ config.server_url = closed_port_url().await;+ config.run_autowire = false;++ let args = RunArgs {+ workspace: Some("ws".into()),+ project: Some("proj".into()),+ workstream: None,+ new_workstream: None,+ executable: Some(script),+ yolo: false,+ true_yolo: false,+ jail: None,+ no_jail: true,+ fresh: false,+ force_unlock: false,+ no_autowire: true,+ require_server: false,+ profile: None,+ env: Vec::new(),+ env_file: None,+ harness: Some(RunHarnessChoice::Claude),+ native_args: Vec::new(),+ };+ (temp, config, args)+ }++ /// The degraded launch spawns the child without any server, propagates+ /// its exact exit code, strips the run/workstream attribution ids from+ /// its environment, and still points its hooks at the configured server.+ #[cfg(unix)]+ #[tokio::test]+ async fn offline_launch_spawns_the_child_and_propagates_its_exit_code() {+ let (temp, config, mut args) = offline_run_fixture(7).await;+ let captured_env = temp.path().join("captured-env");+ let captured_args = temp.path().join("captured-args");+ args.env = vec![+ (+ "CAPTURED_ENV".to_string(),+ captured_env.display().to_string(),+ ),+ (+ "CAPTURED_ARGS".to_string(),+ captured_args.display().to_string(),+ ),+ ];++ let exit = run_from_with_wiring(+ &config,+ args,+ &temp.path().join("repo"),+ &WireOverrides::default(),+ )+ .await+ .expect("a degraded launch still runs the harness");++ assert_eq!(exit, 7, "the child's exit code is returned, not an error");+ let child_env_text = std::fs::read_to_string(&captured_env).unwrap();+ assert!(+ !child_env_text+ .lines()+ .any(|line| line.starts_with("AI_MEMORY_RUN_ID=")),+ "no run id may be attributed offline:\n{child_env_text}"+ );+ assert!(+ !child_env_text+ .lines()+ .any(|line| line.starts_with("AI_MEMORY_WORKSTREAM_ID=")),+ "no workstream id may be attributed offline:\n{child_env_text}"+ );+ assert!(+ child_env_text+ .lines()+ .any(|line| line.starts_with("AI_MEMORY_HOOK_URL=")),+ "the hook URL still points at the configured server:\n{child_env_text}"+ );+ }++ /// Without a server there is no lease, so no mutual exclusion: only an+ /// explicit native session selector resumes; a bare launch starts fresh.+ #[cfg(unix)]+ #[tokio::test]+ async fn offline_launch_resumes_only_with_an_explicit_session_selector() {+ let (temp, config, args) = offline_run_fixture(0).await;+ let repo = temp.path().join("repo");+ let captured_args =+ |name: &str| std::fs::read_to_string(temp.path().join(name)).unwrap_or_default();+ let run = |native_args: Vec<OsString>| async {+ let mut args = args.clone();+ args.native_args = native_args;+ args.env = vec![+ (+ "CAPTURED_ENV".to_string(),+ temp.path()+ .join(format!("env-{}", args.native_args.len()))+ .display()+ .to_string(),+ ),+ (+ "CAPTURED_ARGS".to_string(),+ temp.path()+ .join(format!("args-{}", args.native_args.len()))+ .display()+ .to_string(),+ ),+ ];+ run_from_with_wiring(&config, args, &repo, &WireOverrides::default()).await+ };++ run(Vec::new()).await.expect("bare offline launch");+ let bare = captured_args("args-0");+ assert!(+ bare.contains("--session-id"),+ "a bare offline launch starts a fresh session: {bare}"+ );++ run(vec![+ OsString::from("--resume"),+ OsString::from("explicit-session"),+ ])+ .await+ .expect("explicit-selector offline launch");+ let resumed = captured_args("args-2");+ assert!(+ resumed.contains("--resume")+ && resumed.contains("explicit-session")+ && !resumed.contains("--session-id"),+ "an explicit selector still resumes: {resumed}"+ );+ }++ /// Offline auto-wire keeps the hook install (capture must spool locally)+ /// but registers no MCP entry for the dead server and writes no sentinel.+ #[cfg(unix)]+ #[tokio::test]+ async fn offline_launch_wires_hooks_but_no_mcp_and_no_sentinel() {+ let (temp, mut config, mut args) = offline_run_fixture(0).await;+ config.run_autowire = true;+ let data = temp.path().join("data");+ let hooks_file = data.join("claude-settings.json");+ std::fs::create_dir_all(&data).unwrap();+ std::fs::write(&hooks_file, "{}").unwrap();+ let mcp_file = data.join("claude.json");+ std::fs::write(&mcp_file, r#"{"existing":"keep"}"#).unwrap();+ let overrides = crate::commands::run_autowire::WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(hooks_file.clone()),+ mcp_config_file: Some(mcp_file.clone()),+ ..Default::default()+ };+ args.no_autowire = false;+ // Keep the capture env names of the fixture off this launch.+ args.env.clear();++ run_from_with_wiring(&config, args, &temp.path().join("repo"), &overrides)+ .await+ .expect("offline launch with wiring");++ let hooks_json = std::fs::read_to_string(&hooks_file).unwrap();+ assert!(+ hooks_json.contains("ai-memory") || hooks_json.contains("ai_memory"),+ "hooks are still wired offline: {hooks_json}"+ );+ let mcp_json = std::fs::read_to_string(&mcp_file).unwrap();+ assert!(+ !mcp_json.contains("ai-memory"),+ "no dead-server MCP registration may be written: {mcp_json}"+ );+ assert!(+ std::fs::read_dir(crate::commands::run_autowire::autowire_state_dir(&data))+ .map(|entries| entries.count())+ .unwrap_or(0)+ == 0,+ "an offline half-wiring must not gate the next online launch"+ );+ }++ /// `--require-server` restores the fail-closed behavior with the same+ /// augmented diagnosis — including "the agent was not started" — and the+ /// harness never runs.+ #[cfg(unix)]+ #[tokio::test]+ async fn require_server_restores_the_fail_closed_error() {+ let (temp, config, mut args) = offline_run_fixture(0).await;+ args.require_server = true;++ let error = run_from_with_wiring(+ &config,+ args,+ &temp.path().join("repo"),+ &WireOverrides::default(),+ )+ .await+ .expect_err("require-server must fail closed");+ assert!(+ error.to_string().contains("the agent was not started"),+ "outer context matches the prepare failure: {error}"+ );+ let full = format!("{error:#}");+ assert!(+ full.contains("could not reach")+ && full.contains("/workstream/runs")+ && full.contains(&config.server_url),+ "the augmented connect diagnosis is reused verbatim: {full}"+ );+ assert!(+ !temp.path().join("repo").join("capture-harness").exists()+ || std::fs::read_to_string(temp.path().join("captured-args")).is_err(),+ "the harness must not run"+ );+ }++ /// A `config.toml`-level `run.require_server` behaves like the flag.+ #[cfg(unix)]+ #[tokio::test]+ async fn config_require_server_also_fails_closed() {+ let (temp, mut config, args) = offline_run_fixture(0).await;+ config.run.require_server = true;++ let error = run_from_with_wiring(+ &config,+ args,+ &temp.path().join("repo"),+ &WireOverrides::default(),+ )+ .await+ .expect_err("config require_server must fail closed");+ assert!(+ format!("{error:#}").contains("the agent was not started"),+ "{error:#}"+ );+ }++ /// The degraded-launch warning names everything the operator needs: the+ /// server URL, what is lost, what still works (spool + no-recall MCP),+ /// the bounded retention, and the opt-outs.+ #[tokio::test]+ async fn offline_launch_warning_names_the_tradeoffs() {+ let url = closed_port_url().await;+ let endpoint = ServerEndpoint::from_config_resolving_auth(&Config {+ server_url: url,+ ..Config::load(None, None).unwrap()+ })+ .await;+ let ServerProbe::Unreachable(error) = probe_server(&endpoint).await else {+ panic!("closed port is unreachable");+ };+ let warning = offline_launch_warning(&endpoint, ManagedHarness::Claude, 8, error);++ assert!(warning.contains(&endpoint.url), "{warning}");+ assert!(warning.contains("could not reach"), "{warning}");+ assert!(warning.contains("Lost this run"), "{warning}");+ assert!(warning.contains("Still works"), "{warning}");+ assert!(warning.contains("spool"), "{warning}");+ assert!(warning.contains("no-recall"), "{warning}");+ assert!(warning.contains("8 failed drain passes"), "{warning}");+ assert!(+ warning.contains("AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS=0"),+ "{warning}"+ );+ assert!(warning.contains("--require-server"), "{warning}");+ }++ #[test]+ fn spooled_events_note_matches_the_status_phrasing() {+ use crate::commands::hook_spool::SpoolHealth;+ assert_eq!(+ spooled_events_note(&SpoolHealth::default()),+ "no hook events remain spooled locally"+ );+ let note = spooled_events_note(&SpoolHealth {+ pending: 3,+ oldest_age_ms: Some(45_000),+ retries_total: 1,+ });+ assert_eq!(note, "3 hook events remain spooled locally (oldest 45s)");+ let one = spooled_events_note(&SpoolHealth {+ pending: 1,+ oldest_age_ms: Some(0),+ retries_total: 0,+ });+ assert_eq!(one, "1 hook event remains spooled locally (oldest 0s)");+ }++ #[tokio::test]+ async fn unreachable_errors_are_transport_errors_not_server_answers() {+ let url = closed_port_url().await;+ let endpoint = ServerEndpoint::from_config_resolving_auth(&Config {+ server_url: url,+ ..Config::load(None, None).unwrap()+ })+ .await;+ let transport =+ post_json::<_, FinishManagedRunResponse>(&endpoint, "/workstream/runs/x/finish", &())+ .await+ .expect_err("closed port");+ assert!(is_unreachable_error(&transport));++ let answered = crate::http_client::server_response_error_for_test(+ reqwest::Method::POST,+ "/workstream/runs/x/finish",+ reqwest::StatusCode::BAD_REQUEST,+ "{\"error\":\"bad\"}".to_owned(),+ )+ .context("persisting the managed transcript; the native process has already exited");+ assert!(!is_unreachable_error(&answered));+ }++ #[test]+ fn offline_import_warning_points_at_finalize_session() {+ let warning = offline_import_warning(+ ManagedHarness::Claude,+ Some("session-123"),+ "ws",+ "proj",+ &anyhow!("connection refused"),+ );+ assert!(warning.contains("exit code is preserved"), "{warning}");+ assert!(+ warning.contains(&format!(+ "ai-memory finalize-session --agent claude-code --reopen --session-id {}",+ SessionId::from_native("session-123")+ )),+ "{warning}"+ );+ assert!(+ warning.contains("--workspace ws --project proj"),+ "{warning}"+ );++ let generic = offline_import_warning(+ ManagedHarness::Crush,+ None,+ "ws",+ "proj",+ &anyhow!("timed out"),+ );+ assert!(+ generic.contains("finalize-session (see --help)"),+ "{generic}"+ );+ }++ /// A server that dies between prepare and finish: the child's exit code+ /// survives, the unrecorded run is reported, and no error propagates.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_mid_run_outage_after_the_child_exits_keeps_the_exit_code() {+ let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);+ let trigger = shutdown_tx.clone();+ let app = Router::new()+ .route(+ "/workstream/runs",+ post(|| async {+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: Some(AgentKind::ClaudeCode),+ native_session_id: None,+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ manifest_warning: None,+ })+ }),+ )+ .route(+ "/workstream/runs/{run_id}/link",+ post(move || {+ let _ = trigger.send(true);+ async { StatusCode::NO_CONTENT }+ }),+ );+ 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)+ .with_graceful_shutdown(async move {+ let mut rx = shutdown_rx;+ while rx.changed().await.is_ok() {+ if *rx.borrow() {+ break;+ }+ }+ })+ .await+ .unwrap();+ });++ let (temp, mut config, args) = offline_run_fixture(5).await;+ config.server_url = format!("http://{address}");+ // Give the graceful shutdown time to close the listener before the+ // child exits and the finish POSTs begin.+ std::fs::write(+ args.executable.clone().unwrap(),+ std::fs::read_to_string(args.executable.clone().unwrap())+ .unwrap()+ .replace("exit 5", "sleep 1\nexit 5"),+ )+ .unwrap();++ let exit = run_from_with_wiring(+ &config,+ args,+ &temp.path().join("repo"),+ &WireOverrides::default(),+ )+ .await+ .expect("an outage after the child exits is a warning, not an error");+ assert_eq!(exit, 5, "the child's exit code is preserved");+ server.abort();+ }+/// A store mismatch must stop before `/link` and before the harness/// spawns, release the prepared run, and leave the workstream link alone.#[cfg(unix)]@@ -5887,6 +6678,7 @@ mod tests {fresh: false,force_unlock: false,no_autowire: true,+ require_server: false,profile: None,// Pinned so a contributor's own CLAUDE_CONFIG_DIR cannot leak in.env: vec![(@@ -6582,6 +7374,7 @@ mod tests {fresh: false,force_unlock: false,no_autowire: false,+ require_server: false,env: vec![("PATH".into(), executable_dir.display().to_string()),("OPENCODE_MAJOR".into(), "2".into()),@@ -6708,6 +7501,7 @@ mod tests {fresh: false,force_unlock: false,no_autowire: false,+ require_server: false,profile: None,env: Vec::new(),env_file: None,@@ -6989,6 +7783,7 @@ mod tests {fresh: false,force_unlock: false,no_autowire: false,+ require_server: false,profile: None,env,env_file: None,diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 10981bdb..02843141 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -428,6 +428,13 @@ fn wire_installs(config: &Config, targets: WireTargets, overrides: &WireOverride/// `launch_cwd` is the directory the harness is launched in — a `resume` may/// launch into a checkout other than the shell's — and is where a/// `--scope project` Claude Code install is looked for.+///+/// `skip_mcp` serves degraded offline launches: the hook install is local and+/// idempotent, so it still runs (capture must spool offline), but registering+/// an MCP entry pointing at a server that just proved unreachable would bake a+/// dead endpoint into the harness config. The MCP install is skipped and the+/// sentinel is NOT written, so the next online launch completes the wiring+/// instead of the sentinel suppressing it forever.#[cfg(test)]pub(crate) fn ensure_wired_with(config: &Config,@@ -444,6 +451,7 @@ pub(crate) fn ensure_wired_with(run_env,&effective_env,launch_cwd,+ false,);}@@ -454,6 +462,7 @@ pub(crate) fn ensure_wired_with_env(run_env: &[(String, String)],effective_env: &super::run::EffectiveChildEnv,launch_cwd: &Path,+ skip_mcp: bool,) {let Some(targets) = wire_targets_with_env(config,@@ -472,11 +481,21 @@ pub(crate) fn ensure_wired_with_env(let sentinel = targets.sentinel.clone();let project_hooks = targets.project_hooks.clone();- eprintln!(- "ai-memory: first managed launch of {} here — wiring its ai-memory hooks + MCP so \- capture and recall work (disable with --no-autowire or AI_MEMORY_RUN_AUTOWIRE=false).",- harness.as_str()- );+ if skip_mcp {+ eprintln!(+ "ai-memory: first managed launch of {} here while the server is unreachable — \+ wiring its ai-memory hooks (capture spools locally); the MCP registration waits \+ for the next online launch (disable with --no-autowire or \+ AI_MEMORY_RUN_AUTOWIRE=false).",+ harness.as_str()+ );+ } else {+ eprintln!(+ "ai-memory: first managed launch of {} here — wiring its ai-memory hooks + MCP so \+ capture and recall work (disable with --no-autowire or AI_MEMORY_RUN_AUTOWIRE=false).",+ harness.as_str()+ );+ }let mut installs = wire_installs(config, targets, overrides);if let Some(project_file) = project_hooks {@@ -503,33 +522,43 @@ pub(crate) fn ensure_wired_with_env(.mcp.as_ref().and_then(|args| args.config_file.clone());- let mcp_failure = match installs.mcp.take() {- // The sentinel is version-keyed, so this whole step re-runs on every- // upgrade. install-mcp replaces the `ai-memory` entry wholesale, so a- // plain re-run would overwrite a session-aware Claude Code bridge the- // user installed with `install-mcp --session-aware` back to static HTTP,- // silently disabling per_session for their MCP calls. Preserve it, in- // the file this launch would write.- Some(args)- if install_mcp::existing_entry_is_session_aware(- args.client,- args.config_file.as_deref(),- &args.name,- ) =>- {- eprintln!(- "ai-memory: keeping the existing session-aware {} MCP bridge; not \- overwriting it with the static HTTP registration.",- harness.as_str()- );- None- }- Some(args) => {- install_mcp::run_with_opencode_dialect(config, args, installs.opencode_dialect)- .err()- .map(|error| format!("{error:#}"))+ let mcp_failure = if skip_mcp {+ // Degraded offline launch: a registration pointing at the unreachable+ // server would cost the harness its recall until the config was+ // edited by hand. Existing registrations are untouched and degrade to+ // no-recall for this run instead; nothing is planned, so nothing can+ // fail or escape a confinement guard.+ installs.mcp = None;+ None+ } else {+ match installs.mcp.take() {+ // The sentinel is version-keyed, so this whole step re-runs on every+ // upgrade. install-mcp replaces the `ai-memory` entry wholesale, so a+ // plain re-run would overwrite a session-aware Claude Code bridge the+ // user installed with `install-mcp --session-aware` back to static HTTP,+ // silently disabling per_session for their MCP calls. Preserve it, in+ // the file this launch would write.+ Some(args)+ if install_mcp::existing_entry_is_session_aware(+ args.client,+ args.config_file.as_deref(),+ &args.name,+ ) =>+ {+ eprintln!(+ "ai-memory: keeping the existing session-aware {} MCP bridge; not \+ overwriting it with the static HTTP registration.",+ harness.as_str()+ );+ None+ }+ Some(args) => {+ install_mcp::run_with_opencode_dialect(config, args, installs.opencode_dialect)+ .err()+ .map(|error| format!("{error:#}"))+ }+ None => installs.mcp_skipped,}- None => installs.mcp_skipped,};if let Some(reason) = &mcp_failure {eprintln!(@@ -567,8 +596,12 @@ pub(crate) fn ensure_wired_with_env(// install on every launch would nag and churn config. A user who wants a// retry can re-run install-hooks manually or delete this sentinel under// `<data_dir>/autowire-state/`; `ai-memory uninstall` clears them all when- // it removes hooks or MCP.- write_sentinel(&sentinel);+ // it removes hooks or MCP. A degraded offline launch (skip_mcp) is the one+ // exception: its wiring is deliberately half-done, so the sentinel stays+ // unwritten and the next online launch completes the MCP half.+ if !skip_mcp {+ write_sentinel(&sentinel);+ }}/// The `--scope project` Claude Code install covering `launch_cwd`, if any.@@ -1541,6 +1574,83 @@ mod tests {PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")}+ /// The degraded offline wiring contract: hooks are installed (capture must+ /// spool locally), the MCP registration is left alone (a dead endpoint+ /// would be baked into harness config otherwise), and no sentinel is+ /// written, so the next online launch completes the MCP half.+ #[test]+ fn skip_mcp_wires_hooks_only_and_writes_no_sentinel() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let settings = data.path().join("claude-settings.json");+ std::fs::write(&settings, "{}").unwrap();+ let mcp = data.path().join("claude.json");+ std::fs::write(&mcp, r#"{"existingMcpKey":"keep me too"}"#).unwrap();++ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(settings.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+ let effective_env =+ super::super::run::EffectiveChildEnv::with_overrides(&config.runtime_env, &[]);+ ensure_wired_with_env(+ &config,+ ManagedHarness::Claude,+ &overrides,+ &[],+ &effective_env,+ &config.data_dir,+ true,+ );++ let hooks_json = std::fs::read_to_string(&settings).unwrap();+ assert!(+ hooks_json.contains("ai-memory") || hooks_json.contains("ai_memory"),+ "the ai-memory hook must be installed offline: {hooks_json}"+ );+ let mcp_json = std::fs::read_to_string(&mcp).unwrap();+ assert!(+ !mcp_json.contains("ai-memory"),+ "no MCP registration may be written for an unreachable server: {mcp_json}"+ );+ assert!(+ mcp_json.contains("existingMcpKey"),+ "the MCP file must be untouched: {mcp_json}"+ );+ let sentinel = wire_targets(+ &config,+ ManagedHarness::Claude,+ &overrides,+ &[],+ &config.data_dir,+ )+ .unwrap()+ .sentinel;+ assert!(+ !sentinel.exists(),+ "an offline half-wiring must not gate the next online launch"+ );++ // The next online launch completes the wiring and records the attempt.+ ensure_wired_with_env(+ &config,+ ManagedHarness::Claude,+ &overrides,+ &[],+ &effective_env,+ &config.data_dir,+ false,+ );+ assert!(+ std::fs::read_to_string(&mcp).unwrap().contains("ai-memory"),+ "the online completion installs the MCP entry"+ );+ assert!(sentinel.exists(), "the completed wiring is recorded");+ }+/// The load-bearing "won't mess up any harness" guarantee: auto-wire installs/// the harness's hooks + MCP while preserving unrelated user config, and a/// second launch is a clean no-op (no duplication, no churn). Paths arediff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex 4327e9be..111af70e 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -232,6 +232,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {fresh: args.fresh,force_unlock: false,no_autowire: false,+ require_server: false,profile: None,env: Vec::new(),env_file: None,diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rsindex af422507..aa4c6c8c 100644--- a/crates/ai-memory-cli/src/commands/status.rs+++ b/crates/ai-memory-cli/src/commands/status.rs@@ -437,7 +437,7 @@ fn fallback_candidate_line(candidate: &ai_memory_llm::CandidateHealth) -> String/// Render a spool age (ms) as a compact human duration, or `-` when the spool/// holds no events. Allowed to saturate: an operator reading a stuck-spool/// diagnosis wants the magnitude, not sub-second precision.-fn spool_age_line(age_ms: Option<u64>) -> String {+pub(super) fn spool_age_line(age_ms: Option<u64>) -> String {let Some(ms) = age_ms else {return "-".to_string();};diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex 077b0804..89df0382 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -684,6 +684,7 @@ pub struct RuntimeEnv {voyage_api_key: Option<SecretString>,opencode_api_key: Option<SecretString>,hook_spool_max_attempts: Option<String>,+ run_require_server: Option<String>,}impl RuntimeEnv {@@ -741,6 +742,11 @@ impl RuntimeEnv {voyage_api_key: env_secret("VOYAGE_API_KEY"),opencode_api_key: env_secret("OPENCODE_API_KEY"),hook_spool_max_attempts: std::env::var("AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS").ok(),+ // A flat env var (not `AI_MEMORY_RUN__REQUIRE_SERVER`, which+ // figment's `__` split would map onto `run.require_server`) so it+ // reads the same way as `AI_MEMORY_RUN_AUTOWIRE`; applied in+ // `load_with_runtime_env` instead of figment for that reason.+ run_require_server: std::env::var("AI_MEMORY_RUN_REQUIRE_SERVER").ok(),}}@@ -805,6 +811,13 @@ impl RuntimeEnv {self.hook_spool_max_attempts.as_deref()}+ /// Managed-launch fail-closed override captured from the process+ /// environment.+ #[must_use]+ pub fn run_require_server(&self) -> Option<&str> {+ self.run_require_server.as_deref()+ }+#[cfg(test)]pub fn with_host_cwd_for_tests(host_cwd: impl Into<String>) -> Self {Self {@@ -1119,6 +1132,12 @@ impl Default for Config {pub struct RunSettings {/// Persisted env-only launch profiles, selected with `run --profile`.pub profiles: BTreeMap<String, RunProfile>,+ /// Fail a managed launch when the server is unreachable instead of+ /// degrading to a serverless launch (`docs/managed-workstreams.md`).+ /// Off by default; the `--require-server` flag and+ /// `AI_MEMORY_RUN_REQUIRE_SERVER=true` request it per launch or per+ /// environment.+ pub require_server: bool,}/// One named managed-launch preset.@@ -1838,6 +1857,16 @@ fn apply_hook_spool_max_attempts_env(config: &mut Config, raw: Option<&str>) {.unwrap_or(DEFAULT_HOOK_SPOOL_MAX_ATTEMPTS);}+/// `AI_MEMORY_RUN_REQUIRE_SERVER` only ever turns the fail-closed behavior+/// on: an absent, blank, or non-truthy value leaves whatever `config.toml`+/// selected, and only an explicit truthy spelling overrides it to on.+fn apply_run_require_server_env(config: &mut Config, raw: Option<&str>) {+ let Some(raw) = raw else { return };+ if crate::marker::is_truthy(raw) {+ config.run.require_server = true;+ }+}+impl Config {/// Load the merged configuration: defaults → file → env → CLI.///@@ -1921,6 +1950,7 @@ impl Config {.as_deref(),);apply_hook_spool_max_attempts_env(&mut config, runtime_env.hook_spool_max_attempts());+ apply_run_require_server_env(&mut config, runtime_env.run_require_server());// Home is captured once in RuntimeEnv (config-read-path invariant);// threaded to the resolver guard and startup heal so neither reads the@@ -3317,6 +3347,54 @@ mod tests {assert_eq!(overridden.hook_spool.max_attempts, 0);}+ #[test]+ fn run_require_server_config_and_runtime_env() {+ let tmp = TempDir::new().unwrap();+ let config_path = tmp.path().join("config.toml");++ let off = Config::load_with_runtime_env(+ Some(&config_path),+ Some(tmp.path().to_path_buf()),+ RuntimeEnv::default(),+ )+ .unwrap();+ assert!(!off.run.require_server, "off by default");++ std::fs::write(&config_path, "[run]\nrequire_server = true\n").unwrap();+ let from_config = Config::load_with_runtime_env(+ Some(&config_path),+ Some(tmp.path().to_path_buf()),+ RuntimeEnv::default(),+ )+ .unwrap();+ assert!(from_config.run.require_server);++ // The env var only turns it on; it never turns a config-file on back+ // off, and a non-truthy spelling is inert.+ for raw in ["", "false", "no", "0"] {+ let inert = Config::load_with_runtime_env(+ Some(&config_path),+ Some(tmp.path().to_path_buf()),+ RuntimeEnv {+ run_require_server: Some(raw.into()),+ ..RuntimeEnv::default()+ },+ )+ .unwrap();+ assert!(inert.run.require_server, "{raw:?} must stay inert");+ }+ let truthy = Config::load_with_runtime_env(+ Some(&config_path),+ None,+ RuntimeEnv {+ run_require_server: Some("true".into()),+ ..RuntimeEnv::default()+ },+ )+ .unwrap();+ assert!(truthy.run.require_server);+ }+#[test]fn loader_hook_spool_runtime_env_overrides_config() {const CHILD_MARKER: &str = "AI_MEMORY_TEST_HOOK_SPOOL_CONFIG_CHILD";diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex cf8a8796..11860e7d 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -15,6 +15,7 @@ use std::io::{BufWriter, Write as _};#[cfg(unix)]use std::os::unix::fs::OpenOptionsExt as _;use std::path::Path;+use std::time::Duration;use anyhow::{Context, Result};use serde::Serialize;@@ -397,7 +398,7 @@ fn build_url_with_query(/// message that surfaces the resolved server URL. The common case is/// "Connection refused" — typically because the CLI defaulted to/// loopback on a host that has no local server running.-fn augment_connect_error(+pub(crate) fn augment_connect_error(err: reqwest::Error,endpoint: &ServerEndpoint,url: &str,@@ -444,6 +445,46 @@ fn augment_connect_error(}}+/// Outcome of a server reachability probe: did anything answer on the+/// configured endpoint?+#[derive(Debug)]+pub(crate) enum ServerProbe {+ /// The server answered. Any HTTP status counts — a build older than+ /// `/healthz` still answers 404/405, and what the probe needs to know is+ /// that something is listening, not that it is healthy.+ Reachable,+ /// Nothing answered (connect error or timeout). Carries the underlying+ /// reqwest error so callers can reuse [`augment_connect_error`]'s+ /// diagnosis verbatim.+ Unreachable(reqwest::Error),+}++/// How long a reachability probe waits for an answer. Short on purpose: the+/// probe sits on the launch hot path, so an unresponsive host (a homelab down+/// for maintenance) must be classified in ~2s rather than the OS-level TCP+/// timeout a plain request would pay.+const PROBE_TIMEOUT: Duration = Duration::from_secs(2);++/// GET `{origin}{base}/healthz` with a short timeout to decide whether a+/// managed launch may proceed without the server.+///+/// Any HTTP response — 200 or 404/405 from a pre-`/healthz` server — means+/// `Reachable`; only connect errors and timeouts mean `Unreachable`. The+/// probe never inspects the body, so it cannot be wrong about health vs+/// absence, only about presence.+pub(crate) async fn probe_server(endpoint: &ServerEndpoint) -> ServerProbe {+ probe_server_with_timeout(endpoint, PROBE_TIMEOUT).await+}++async fn probe_server_with_timeout(endpoint: &ServerEndpoint, timeout: Duration) -> ServerProbe {+ let client = reqwest::Client::new();+ let url = endpoint.build_url("/healthz");+ match client.get(&url).timeout(timeout).send().await {+ Ok(_) => ServerProbe::Reachable,+ Err(error) => ServerProbe::Unreachable(error),+ }+}+/// POST an empty body to `<endpoint>{path}`, streaming the response to `dest`.////// Intended for routes whose response is binary (e.g. `POST /admin/backup`@@ -495,6 +536,8 @@ fn private_output_file(path: &Path) -> std::io::Result<std::fs::File> {#[cfg(test)]mod tests {+ use std::time::Instant;+use super::*;#[cfg(unix)]@@ -792,6 +835,106 @@ mod tests {assert_eq!(auth, "Bearer tok123");}+ // ----------------------------------------------------------------+ // Server reachability probe+ // ----------------------------------------------------------------++ /// Bind a loopback listener, capture its address, and release it: the+ /// next connection to that address is refused. Rebinding races exist on+ /// loopback but are vanishingly rare under a test load.+ async fn closed_port_endpoint() -> ServerEndpoint {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ drop(listener);+ ServerEndpoint::from_pair(Some(format!("http://{address}")), None)+ }++ #[tokio::test]+ async fn probe_reports_a_closed_port_as_unreachable_with_the_diagnosis() {+ let endpoint = closed_port_endpoint().await;+ let ServerProbe::Unreachable(error) = probe_server(&endpoint).await else {+ panic!("a closed port must be Unreachable");+ };+ let url = endpoint.build_url("/workstream/runs");+ let augmented = augment_connect_error(error, &endpoint, &url);+ let message = format!("{augmented:#}");+ assert!(+ message.contains("could not reach"),+ "the probe error must feed augment_connect_error: {message}"+ );+ assert!(+ message.contains(&endpoint.url),+ "the diagnosis names the resolved server URL: {message}"+ );+ }++ /// A server that answers 404 for `/healthz` (older than the route) is+ /// still reachable: presence, not health, is what the probe decides.+ #[tokio::test]+ async fn probe_reports_any_http_answer_as_reachable() {+ for status in [+ axum::http::StatusCode::OK,+ axum::http::StatusCode::NOT_FOUND,+ axum::http::StatusCode::METHOD_NOT_ALLOWED,+ ] {+ let app =+ axum::Router::new().fallback(axum::routing::get(move || async move { status }));+ 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);++ assert!(matches!(+ probe_server(&endpoint).await,+ ServerProbe::Reachable+ ));++ server.abort();+ }+ }++ /// A listener that accepts but never answers must be given up on within+ /// the probe timeout, not a TCP or default-client timeout.+ #[tokio::test]+ async fn probe_gives_up_within_its_own_timeout() {+ async fn accept_and_hold() -> std::net::SocketAddr {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ tokio::spawn(async move {+ // Accept connections, hold them open, and answer nothing —+ // the streams must outlive the accept so the client's only+ // way out is its own timeout.+ let mut held = Vec::new();+ while let Ok((stream, _)) = listener.accept().await {+ held.push(stream);+ }+ });+ address+ }+ let address = accept_and_hold().await;+ let endpoint = ServerEndpoint::from_pair(Some(format!("http://{address}")), None);++ let started = Instant::now();+ assert!(matches!(+ probe_server_with_timeout(&endpoint, Duration::from_millis(150)).await,+ ServerProbe::Unreachable(_)+ ));+ let elapsed = started.elapsed();+ assert!(elapsed >= Duration::from_millis(150), "gave up too early");+ assert!(+ elapsed < Duration::from_secs(2),+ "the probe timeout, not a transport default, bounds the wait ({elapsed:?})"+ );+ }++ /// The production probe stays bounded by design: a homelab down for+ /// maintenance must be classified in ~2s, never by an OS TCP timeout.+ #[test]+ fn probe_timeout_is_bounded_to_about_two_seconds() {+ assert!(PROBE_TIMEOUT <= Duration::from_secs(2));+ assert!(!PROBE_TIMEOUT.is_zero());+ }+#[tokio::test]async fn from_config_resolving_auth_uses_stored_oidc_for_authorization_header() {let tmp = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex a7283522..626b280d 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -29,6 +29,7 @@ mod removal;mod repo_layout;mod routing_instructions;mod routing_skills;+mod run_offline;mod serve_shutdown;mod server_profiles;mod shutdown_signals;diff --git a/crates/ai-memory-cli/tests/suite/run_offline.rs b/crates/ai-memory-cli/tests/suite/run_offline.rsnew file mode 100644index 00000000..6213609c--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/run_offline.rs@@ -0,0 +1,330 @@+//! End-to-end coverage for degraded offline launches: `ai-memory run` against+//! a closed port (a homelab down for maintenance) must WARN and still launch+//! the harness without the server, `--require-server` must fail closed with+//! the old augmented error, and offline auto-wire must install hooks but no+//! dead-server MCP registration. Unix-only: the fake harness is a shebang+//! script.++#![cfg(unix)]++use std::fs;+use std::os::unix::fs::PermissionsExt as _;+use std::path::{Path, PathBuf};+use std::process::{Output, Stdio};++use axum::{Json, Router, http::StatusCode, routing::post};+use serde_json::json;++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++/// A loopback address nothing listens on: `free_port` binds and releases.+fn closed_port_url() -> String {+ format!("http://127.0.0.1:{}", crate::e2e_support::free_port())+}++fn write_script(path: &Path, body: &str) {+ fs::write(path, format!("#!/bin/sh\n{body}")).unwrap();+ fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();+}++fn host_tool(name: &str) -> PathBuf {+ let path = std::env::var_os("PATH").expect("PATH");+ std::env::split_paths(&path)+ .map(|dir| dir.join(name))+ .find(|candidate| candidate.is_file())+ .unwrap_or_else(|| panic!("{name} on PATH"))+}++struct Fixture {+ _temp: tempfile::TempDir,+ repo: PathBuf,+ home: PathBuf,+ bin: PathBuf,+ claude_ran: PathBuf,+ claude_env: PathBuf,+}++impl Fixture {+ fn new() -> Self {+ let temp = tempfile::tempdir().unwrap();+ let root = temp.path().canonicalize().unwrap();+ let repo = root.join("repo");+ let home = root.join("home");+ let bin = root.join("bin");+ for dir in [&repo, &home, &bin] {+ fs::create_dir_all(dir).unwrap();+ }+ let status = std::process::Command::new("git")+ .arg("-C")+ .arg(&repo)+ .args(["init", "-q"])+ .stdout(Stdio::null())+ .status()+ .unwrap();+ assert!(status.success(), "git init");+ std::os::unix::fs::symlink(host_tool("git"), bin.join("git")).unwrap();++ let claude_ran = root.join("claude-ran.txt");+ let claude_env = root.join("claude-env.txt");+ // The fake harness records its argv and environment and writes the+ // (empty-session) transcript the launcher waits for, so the run+ // finishes instead of waiting out the transcript-flush poll. `set`+ // (a shell builtin) dumps the environment without needing anything+ // else on the replaced PATH.+ let transcripts = home+ .join(".claude/projects")+ .join(repo.to_string_lossy().replace('/', "-"));+ fs::create_dir_all(&transcripts).unwrap();+ write_script(+ &bin.join("claude"),+ &format!(+ "printf '%s\\n' \"$@\" > '{ran}'\nset > '{env_}'\n\+ while [ $# -gt 0 ]; do\n\+ if [ \"$1\" = --session-id ]; then\n\+ printf '{{\"sessionId\":\"%s\",\"cwd\":\"%s\"}}\\n' \"$2\" '{repo}' > '{dir}'/\"$2\".jsonl\n\+ fi\nshift\ndone\nexit 0\n",+ ran = claude_ran.display(),+ env_ = claude_env.display(),+ repo = repo.display(),+ dir = transcripts.display(),+ ),+ );+ Self {+ _temp: temp,+ repo,+ home,+ bin,+ claude_ran,+ claude_env,+ }+ }+}++fn command(fixture: &Fixture, server: &str, args: &[&str]) -> tokio::process::Command {+ let mut command: tokio::process::Command = crate::e2e_support::hermetic(BIN).into();+ for name in ["SSH_AUTH_SOCK", "XDG_CONFIG_HOME", "GH_CONFIG_DIR", "PS1"] {+ command.env_remove(name);+ }+ command+ .args(args)+ .current_dir(&fixture.repo)+ .env("PATH", &fixture.bin)+ .env("HOME", &fixture.home)+ .env("AI_MEMORY_HOME", &fixture.home)+ .env("CLAUDE_CONFIG_DIR", fixture.home.join(".claude"))+ .env("AI_MEMORY_DATA_DIR", fixture.home.join("data"))+ .env("AI_MEMORY_SERVER_URL", server)+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ command+}++async fn run(fixture: &Fixture, server: &str, args: &[&str]) -> Output {+ tokio::time::timeout(+ std::time::Duration::from_secs(30),+ command(fixture, server, args).output(),+ )+ .await+ .expect("ai-memory run finished")+ .expect("spawn ai-memory")+}++fn stderr(output: &Output) -> String {+ String::from_utf8_lossy(&output.stderr).into_owned()+}++/// A closed port downgrades the launch: one loud warning, the harness runs,+/// no run/workstream ids are attributed to the offline child, and the+/// not-recorded line accounts for the (empty) local spool.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn offline_run_launches_the_harness_without_the_server() {+ let fixture = Fixture::new();+ let server = closed_port_url();+ let output = run(&fixture, &server, &["run", "--no-autowire", "claude"]).await;+ assert!(output.status.success(), "{}", stderr(&output));++ let stderr = stderr(&output);+ assert!(+ stderr.contains("WARNING") && stderr.contains("unreachable"),+ "the degraded warning is loud:\n{stderr}"+ );+ assert!(+ stderr.contains(&server),+ "the warning names the server URL:\n{stderr}"+ );+ assert!(+ stderr.contains("not recorded on the server"),+ "the spool account is printed:\n{stderr}"+ );+ assert!(+ stderr.contains("no hook events remain spooled locally"),+ "the empty spool is reported as empty:\n{stderr}"+ );++ assert!(fixture.claude_ran.exists(), "the harness ran:\n{stderr}");+ let child_env = fs::read_to_string(&fixture.claude_env).unwrap();+ assert!(+ !child_env+ .lines()+ .any(|line| line.starts_with("AI_MEMORY_RUN_ID=")+ || line.starts_with("AI_MEMORY_WORKSTREAM_ID=")),+ "no server-run attribution may reach the offline child:\n{child_env}"+ );+ assert!(+ child_env+ .lines()+ .any(|line| line.starts_with("AI_MEMORY_HOOK_URL=")),+ "the hook URL still points at the configured server:\n{child_env}"+ );+}++/// `--require-server` restores the fail-closed behavior: the old augmented+/// connect error (including "the agent was not started"), and the harness+/// never starts.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn require_server_fails_closed_when_offline() {+ let fixture = Fixture::new();+ let server = closed_port_url();+ let output = run(+ &fixture,+ &server,+ &["run", "--no-autowire", "--require-server", "claude"],+ )+ .await;+ assert!(!output.status.success());+ let stderr = stderr(&output);+ assert!(+ stderr.contains("the agent was not started"),+ "the prepare context is preserved:\n{stderr}"+ );+ assert!(+ stderr.contains("could not reach"),+ "the augmented connect diagnosis is reused:\n{stderr}"+ );+ assert!(+ !fixture.claude_ran.exists(),+ "the harness must not run:\n{stderr}"+ );+}++/// Offline auto-wire installs the hooks (capture must spool locally) but+/// registers no MCP entry for the unreachable server and leaves no sentinel,+/// so the next online launch completes the wiring.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn offline_autowire_wires_hooks_but_not_mcp() {+ let fixture = Fixture::new();+ let server = closed_port_url();+ let output = run(&fixture, &server, &["run", "claude"]).await;+ assert!(output.status.success(), "{}", stderr(&output));+ let stderr = stderr(&output);+ assert!(+ stderr.contains("wiring its ai-memory hooks"),+ "the offline wiring is announced:\n{stderr}"+ );+ assert!(+ stderr.contains("MCP registration waits"),+ "the deferred MCP is announced:\n{stderr}"+ );++ let settings = fs::read_to_string(fixture.home.join(".claude/settings.json"))+ .expect("hooks settings written");+ assert!(+ settings.contains("ai-memory") || settings.contains("ai_memory"),+ "hooks are wired offline: {settings}"+ );+ // With CLAUDE_CONFIG_DIR set, the Claude Code MCP target is+ // `<config_dir>/.claude.json`; check both spellings so the assertion+ // cannot pass vacuously.+ for mcp_path in [+ fixture.home.join(".claude.json"),+ fixture.home.join(".claude/.claude.json"),+ ] {+ assert!(+ !mcp_path.exists() || !fs::read_to_string(&mcp_path).unwrap().contains("ai-memory"),+ "no dead-server MCP registration may be written at {}",+ mcp_path.display()+ );+ }+ let state = fixture.home.join("data/autowire-state");+ assert!(+ !state.exists() || fs::read_dir(&state).unwrap().count() == 0,+ "an offline half-wiring must not gate the next online launch"+ );+}++/// The mid-run outage repair path: when the server dies after prepare, the+/// child's exit code survives, the warning points at `finalize-session`, and+/// the recorded exit status stays the child's own. The mock server answers+/// prepare, then closes its listener once the run is linked.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_mid_run_outage_preserves_the_child_exit_code() {+ let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);+ let trigger = shutdown_tx.clone();+ let app = Router::new()+ .route(+ "/workstream/runs",+ post(|| async {+ Json(json!({+ "workstream_id": "12345678-1234-4234-9234-123456789abd",+ "workstream_name": "fixture",+ "run_id": "12345678-1234-4234-9234-123456789abe",+ "resolved_agent": "claude-code",+ "sync_after": 0, "sync_through": 0,+ "may_adopt_existing_session": false,+ }))+ }),+ )+ .route(+ "/workstream/runs/{run_id}/link",+ post(move || {+ let _ = trigger.send(true);+ async { StatusCode::NO_CONTENT }+ }),+ );+ 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)+ .with_graceful_shutdown(async move {+ let mut rx = shutdown_rx;+ while rx.changed().await.is_ok() {+ if *rx.borrow() {+ break;+ }+ }+ })+ .await+ .unwrap();+ });++ let fixture = Fixture::new();+ // Hold the child long enough for the graceful shutdown to close the+ // listener before the finish POSTs begin, then exit 5.+ write_script(+ &fixture.bin.join("claude"),+ &format!(+ "printf '%s\\n' \"$@\" > '{}'\nsleep 1\nexit 5\n",+ fixture.claude_ran.display(),+ ),+ );+ let server_url = format!("http://{address}");+ let output = run(&fixture, &server_url, &["run", "--no-autowire", "claude"]).await;+ assert_eq!(+ output.status.code(),+ Some(5),+ "the child's exit code is preserved, not an ai-memory error:\n{}",+ stderr(&output)+ );+ let stderr = stderr(&output);+ assert!(+ stderr.contains("was not imported"),+ "the outage is reported:\n{stderr}"+ );+ assert!(+ stderr.contains("ai-memory finalize-session"),+ "the repair path is named:\n{stderr}"+ );+ server.abort();+}diff --git a/docs/cookbook.md b/docs/cookbook.mdindex 1880f02e..b6cdc777 100644--- a/docs/cookbook.md+++ b/docs/cookbook.md@@ -378,6 +378,21 @@ ai-memory serve # run the server## When it isn't doing what you expect+- **Server/homelab down**: `ai-memory run` does not need the server to start a+ harness. When the server is unreachable it prints one loud warning and+ launches anyway — hooks keep capturing to the local spool (drained+ automatically when the server returns), an existing MCP registration+ degrades to no-recall for the session, and the child's exit code is+ returned. What you lose for that run is the workstream lease/context,+ transcript import, and handoff delivery; sessions resume only through an+ explicit native selector because no lease means no mutual exclusion. See+ [Degraded offline+ launches](managed-workstreams.md#degraded-offline-launches). To fail instead+ of degrading, pass `--require-server` (or set `run.require_server = true` /+ `AI_MEMORY_RUN_REQUIRE_SERVER=true`). For a planned outage, consider+ `AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS=0` so spooled events are never dropped+ for retry-attempt count.+- **Nothing is being remembered**: hooks may not be installed. `ai-memory run<harness>` installs its hooks + MCP on the first launch per harness,ai-memory version and config home, and again after `ai-memory uninstall`. If that harnessdiff --git a/docs/install.md b/docs/install.mdindex 3194a330..a22ce10d 100644--- a/docs/install.md+++ b/docs/install.md@@ -691,7 +691,9 @@ passes when the server is unreachable. Set `max_attempts = 0` under`[hook_spool]` in `<data_dir>/config.toml` (or set`AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS=0`) to keepretrying until the 7-day age limit or 10,000-file spool cap applies. A positive-value sets the number of failed passes before a drop.+value sets the number of failed passes before a drop. The same bounds apply to+`ai-memory run`'s degraded offline launches, which rely on this spool — see+[Degraded offline launches](managed-workstreams.md#degraded-offline-launches).The built-in timings stay short on agent-facing paths, but high-latency orlarge-backlog instances can raise them with whole-minute runtime env vars in thediff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 9c946d39..6394349e 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -133,7 +133,7 @@ file, and the current checkout remain authoritative.ai-memory run [--workspace NAME] [--project NAME][--workstream NAME | --new NAME] [--executable PATH][--yolo] [--fresh] [--force-unlock] [--profile NAME]- [--env KEY=VALUE]... [--env-file PATH]+ [--env KEY=VALUE]... [--env-file PATH] [--require-server][claude|claude*|codex|opencode|opencode2|pi|crush|omp|kimi|command-code|kiro|grok|antigravity][native arguments...]```@@ -218,8 +218,9 @@ the same marker and repository rules as `run`. `--no-scan` uses saved linksonly, while `--workspace NAME` filters both sources. Stale, retargeted, orscope-mismatched links are skipped and a successful later `run` repairs theentry. If the server is temporarily unavailable, saved links and scan results-remain selectable, but managed `run` still fails closed if it cannot prepare a-workstream before launching the agent.+remain selectable and a launch from the picker degrades exactly like any other+`run` (see [Degraded offline launches](#degraded-offline-launches)) rather+than failing closed; pass `--require-server` to refuse the launch instead.Interactive mode begins with `+ New project`. The launcher accepts a portablelowercase ASCII directory name, builds the marker, instruction routing, and@@ -503,6 +504,58 @@ including on retries of a finished run. This namespace belongs to the server'scheckpoint and extraction-loss events, which it appends when completing anactive run.+## Degraded offline launches++When the ai-memory server is unreachable — a remote homelab down for+maintenance, a VPN that is not up — `ai-memory run` does not abort. It probes+the server first (any HTTP answer counts as reachable, so an older build+without `/healthz` still passes), prints one loud warning naming the server+URL and what the degraded run means, and launches the harness anyway:++- **Lost this run**: no workstream lease or cross-harness context packet, no+ transcript import into the ledger, and no cross-harness handoff delivery.+ Nothing that needs the server runs: no prepare, lease, link, heartbeat,+ context fetch, status check, finish, or import.+- **Still works**: the harness's ai-memory lifecycle hooks (if installed) keep+ capturing — events spool locally and drain automatically when the server+ returns. An existing MCP registration degrades to no-recall for the session+ rather than blocking it (the same principle as `docs/mcp-install.md`'s+ optional-mode entries: an unreachable memory server costs you recall, not+ the session).+- **Sessions**: because no lease exists there is no mutual exclusion against+ another launcher in the same checkout, so a degraded launch never adopts or+ resumes a session implicitly. An explicit native session selector+ (`claude --resume <id>`, `codex continue`, …) still resumes — you named the+ session — and everything else starts a fresh session.+- **Auto-wire**: the first-launch hook install still happens (it is local and+ idempotent, and capture must spool offline), but no MCP entry is registered+ for the now-unreachable server and no completion sentinel is written, so the+ next online launch finishes the wiring. Existing registrations are never+ touched.+- **Attribution**: the child is launched without `AI_MEMORY_RUN_ID` /+ `AI_MEMORY_WORKSTREAM_ID`, so its SessionEnd hook cannot attribute the+ session to a server run that never happened.+- **Exit code**: the child's own exit code is returned; the launch itself is+ not an error.++When the child exits, the launcher prints that the run was not recorded on the+server and how many hook events remain spooled locally (oldest first by age).+Spooled events are bounded: they are dropped after the configured number of+failed drain passes (8 by default), 7 days of age, or the 10,000-file spool+cap. For a planned outage set `AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS=0` to disable+only the attempt-count drops (see `docs/install.md`).++If the server dies *during* a run — after the lease was acquired — the exit+code is still preserved: the unimported transcript is reported as a warning+with the exact `ai-memory finalize-session` command that repairs the record+once the server is back, and the orphaned lease expires on its own within 90+seconds.++To restore the strict behavior (fail with the usual "could not reach …"+diagnosis and never start the agent), pass `--require-server`, set+`run.require_server = true` in `config.toml`, or export+`AI_MEMORY_RUN_REQUIRE_SERVER=true`.+## Native identity privacyNew managed bindings accept the exact original native identity only when it is