Skip to content

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

Rust

feat(run): auto-install a harness's hooks + MCP on first `ai-memory run`

AkitaOnRailsda8d07dcc98e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95fed696..247dc152 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `ai-memory run <harness>` now auto-installs that harness's ai-memory hooks and
+ MCP server the first time it launches the harness, if they are not already
+ wired — so managed launch (the recommended way to start a harness) captures
+ and can query memory without a separate `install-hooks` / `install-mcp` step.
+ It is idempotent and one-time per harness + binary version (a per-agent
+ sentinel under `<data_dir>/autowire-state/`), preserves any unrelated user
+ config the installers touch, runs before the child spawns so the harness picks
+ up the fresh hooks, and is best-effort (a failure warns and the launch still
+ proceeds). Harnesses without installer support (e.g. Crush) are skipped
+ cleanly, and Pi wires hooks but has no MCP client to write. Opt out with
+ `ai-memory run --no-autowire`, `AI_MEMORY_RUN_AUTOWIRE=false`, or
+ `run_autowire = false`. Documented as the preferred launch path ("if in
+ doubt, run with ai-memory").
- Boot-time backfill of pre-hook local history, on by default. When a project's
ai-memory store is brand new (empty), the SessionStart hook triggers a
one-time, bounded import of that project's existing local harness transcripts
diff --git a/README.md b/README.md
index 76e7caa4..ac71ef9b 100644
--- a/README.md
+++ b/README.md
@@ -238,8 +238,12 @@ works out of the box: the "current project" pointer is isolated per caller
by default (v1.39+). See [`docs/auto-scope.md`](docs/auto-scope.md) for the
optional session-aware Claude Code bridge and the details.
-Managed workstreams are optional and add cross-harness *session* continuity
-on top of shared memory:
+**If in doubt, start your harness with `ai-memory run`.** It is the preferred
+way to launch: the first time it runs a harness it auto-installs that harness's
+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 right
+project scope by construction, and it adds cross-harness *session* continuity on
+top of shared memory. Everything is idempotent and one-time per harness.
```bash
ai-memory run claude
@@ -247,6 +251,11 @@ ai-memory run codex --yolo # later: same workstream, different harness
ai-memory continue # resume the newest managed checkout
```
+Auto-wiring is on by default; opt out with `ai-memory run --no-autowire` or
+`AI_MEMORY_RUN_AUTOWIRE=false`. You can still wire agents by hand with
+`install-hooks` / `install-mcp` (e.g. for a harness you never launch through
+`ai-memory run`).
+
`ai-memory uninstall --apply` removes everything ai-memory installed,
and only what it installed. Install commands are idempotent and write
timestamped backups next to any file they touch.
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 7cbf5f58..22f3ac38 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -255,6 +255,12 @@ pub struct RunArgs {
/// resuming or adopting an existing harness session.
#[arg(long)]
pub fresh: bool,
+ /// Skip the one-time auto-install of this harness's ai-memory hooks + MCP.
+ /// Auto-wire is on by default so a managed launch captures without a manual
+ /// `install-hooks`/`install-mcp` step; pass this (or set
+ /// `AI_MEMORY_RUN_AUTOWIRE=false`) to launch without touching harness config.
+ #[arg(long)]
+ pub no_autowire: bool,
/// Agent harness to launch. When omitted, continue the newest managed or
/// checkout-local session among the auto-detected harnesses. Any value
/// starting with `claude` (e.g. `claude-corp`, `claude-personal`) also
diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rs
index 395d839f..61475d27 100644
--- a/crates/ai-memory-cli/src/commands/continue_session.rs
+++ b/crates/ai-memory-cli/src/commands/continue_session.rs
@@ -73,6 +73,7 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {
executable: None,
yolo: args.yolo,
fresh: args.fresh,
+ no_autowire: false,
// Bare mode: `run` resolves the harness that owns the newest
// usable session for this workstream.
harness: None,
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 28098b61..df10d72c 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -1262,7 +1262,7 @@ fn find_grok_project_overlay(cwd: &Path, repo_root: Option<&Path>) -> Option<Pat
.find(|path| path.exists())
}
-fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
+pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
match agent {
AgentChoice::ClaudeCode => Some(McpClient::ClaudeCode),
AgentChoice::Codex => Some(McpClient::Codex),
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index bc164b67..2ee7c88a 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -73,6 +73,7 @@ pub mod restore;
pub mod restore_page;
pub mod resume;
pub mod run;
+pub mod run_autowire;
pub mod search;
pub mod serve;
pub mod setup_agent;
diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rs
index 6a65b672..c75bcaf8 100644
--- a/crates/ai-memory-cli/src/commands/resume.rs
+++ b/crates/ai-memory-cli/src/commands/resume.rs
@@ -162,6 +162,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {
executable: None,
yolo: args.yolo,
fresh: args.fresh,
+ no_autowire: false,
harness,
native_args: Vec::new(),
},
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 62daa83d..5dcce48b 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -90,7 +90,9 @@ pub(super) async fn run_from(config: &Config, args: RunArgs, cwd: &Path) -> Resu
let mut native_args = args.native_args;
let trailing_yolo = remove_wrapper_yolo(&mut native_args);
let trailing_fresh = remove_wrapper_fresh(&mut native_args);
+ let trailing_no_autowire = remove_wrapper_no_autowire(&mut native_args);
let force_fresh = args.fresh || trailing_fresh;
+ let no_autowire = args.no_autowire || trailing_no_autowire;
if automatic_harness && !native_args.is_empty() {
return Err(anyhow!(
"native harness arguments require an explicit harness; try `ai-memory run codex ...`"
@@ -214,6 +216,14 @@ pub(super) async fn run_from(config: &Config, args: RunArgs, cwd: &Path) -> Resu
resolved_harness
};
acquired_try!(ensure_executable_available(harness, executable.as_deref()));
+ // Auto-wire this harness's ai-memory hooks + MCP the first time it launches
+ // here, so managed launch "just works" for capture and recall without a
+ // manual install step. One-time, idempotent, best-effort (it never blocks or
+ // fails the launch); opt out with `--no-autowire` or AI_MEMORY_RUN_AUTOWIRE=false.
+ // Runs before the child spawns so the harness picks up the fresh hooks.
+ if config.run_autowire && !no_autowire {
+ super::run_autowire::ensure_wired(config, harness);
+ }
let native_grok_rules = user_supplied_grok_rules(&native_args);
let (mut plan, orphaned_session) = acquired_try!(build_preflighted_launch_plan(
harness,
@@ -777,6 +787,12 @@ fn remove_wrapper_fresh(args: &mut Vec<OsString>) -> bool {
args.len() != before
}
+fn remove_wrapper_no_autowire(args: &mut Vec<OsString>) -> bool {
+ let before = args.len();
+ args.retain(|arg| arg != OsStr::new("--no-autowire"));
+ args.len() != before
+}
+
fn build_preflighted_launch_plan(
harness: ManagedHarness,
executable: Option<OsString>,
@@ -1996,6 +2012,25 @@ mod tests {
assert_eq!(trailing, ["--model", "opus"].map(OsString::from));
}
+ #[test]
+ fn wrapper_no_autowire_parses_before_or_after_the_harness() {
+ // Before the harness: clap binds it as the wrapper flag.
+ let cli = Cli::try_parse_from(["ai-memory", "run", "--no-autowire", "kimi"]).unwrap();
+ let CliCommand::Run(args) = cli.command else {
+ panic!("expected run command");
+ };
+ assert!(args.no_autowire);
+
+ // After the harness: trailing_var_arg swallows it into native_args, so it
+ // must be extracted rather than forwarded to the harness (which would
+ // reject an unknown flag).
+ let mut trailing = ["--no-autowire", "--model", "opus"]
+ .map(OsString::from)
+ .to_vec();
+ assert!(remove_wrapper_no_autowire(&mut trailing));
+ assert_eq!(trailing, ["--model", "opus"].map(OsString::from));
+ }
+
#[test]
fn missing_linked_session_starts_fresh_but_explicit_selectors_win() {
let temp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rs
new file mode 100644
index 00000000..b77b2af3
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs
@@ -0,0 +1,342 @@
+//! Auto-install a harness's ai-memory hooks + MCP the first time it is launched
+//! through `ai-memory run`.
+//!
+//! Managed launch is the recommended way to start a harness ("if in doubt, run
+//! with ai-memory"), so it should be the path that makes capture *work* without
+//! a separate manual `install-hooks` / `install-mcp` step. Motivating bug: a
+//! user ran `ai-memory run kimi` and nothing was captured because the Kimi hooks
+//! and MCP had never been installed.
+//!
+//! This runs at most once per (harness, binary version): a per-agent sentinel
+//! under `<data_dir>/autowire-state/` keeps the run hot-path fast on every
+//! subsequent launch, while keying on the version means an upgrade re-stages the
+//! fresh hook bundle. Both installs are idempotent (they no-op when already up
+//! to date), and the whole step is best-effort — a failure warns and the harness
+//! still launches. Opt out with `run --no-autowire` or `AI_MEMORY_RUN_AUTOWIRE=false`.
+
+use std::path::{Path, PathBuf};
+
+use ai_memory_workstream::ManagedHarness;
+
+use crate::cli::{AgentChoice, InstallHooksArgs, InstallMcpArgs};
+use crate::config::Config;
+
+use super::{install_hooks, install_mcp};
+
+/// The install-hooks `AgentChoice` for a launchable harness, or `None` for a
+/// harness with no install support (Crush has no `AgentChoice`), which is
+/// skipped cleanly.
+pub(crate) fn agent_choice_for_harness(harness: ManagedHarness) -> Option<AgentChoice> {
+ Some(match harness {
+ ManagedHarness::Claude => AgentChoice::ClaudeCode,
+ ManagedHarness::Codex => AgentChoice::Codex,
+ ManagedHarness::OpenCode => AgentChoice::OpenCode,
+ ManagedHarness::OpenCode2 => AgentChoice::OpenCode2,
+ ManagedHarness::Pi => AgentChoice::Pi,
+ ManagedHarness::Omp => AgentChoice::Omp,
+ ManagedHarness::Kimi => AgentChoice::KimiCode,
+ ManagedHarness::CommandCode => AgentChoice::CommandCode,
+ ManagedHarness::Kiro => AgentChoice::KiroCli,
+ ManagedHarness::KiroV3 => AgentChoice::KiroCliV3,
+ ManagedHarness::Grok => AgentChoice::Grok,
+ ManagedHarness::Antigravity => AgentChoice::AntigravityCli,
+ // No AgentChoice / installer support.
+ ManagedHarness::Crush => return None,
+ })
+}
+
+/// Per-(agent, version) sentinel marking that auto-wire already ran for this
+/// harness on this machine with this binary. Keyed by the agent's stable kebab
+/// name plus the crate version so an upgrade re-wires the fresh hook bundle.
+fn sentinel_path(data_dir: &Path, agent: AgentChoice) -> PathBuf {
+ let name = format!("{}-{}", agent.kind().as_str(), env!("CARGO_PKG_VERSION"));
+ data_dir.join("autowire-state").join(name)
+}
+
+fn write_sentinel(path: &Path) {
+ if let Some(parent) = path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ // Best-effort: a missing sentinel only costs a redundant idempotent re-apply
+ // on the next launch, never wrong behavior.
+ let _ = std::fs::write(path, b"");
+}
+
+/// Test-only path injections so the wiring can be exercised without resolving —
+/// and writing to — the developer's real `$HOME` harness config. In production
+/// every field is `None`, so the installers resolve their real per-agent paths.
+#[derive(Default)]
+pub(crate) struct WireOverrides {
+ /// Source directory of the hook script bundle to stage from.
+ pub hooks_dir: Option<PathBuf>,
+ /// Destination agent hook-config file (else the agent's real path).
+ pub hooks_config_file: Option<PathBuf>,
+ /// Destination agent MCP-config file (else the agent's real path).
+ pub mcp_config_file: Option<PathBuf>,
+}
+
+/// Ensure the launched harness has ai-memory hooks + MCP installed. Best-effort
+/// and one-time; never blocks or fails the launch.
+pub(crate) fn ensure_wired(config: &Config, harness: ManagedHarness) {
+ ensure_wired_with(config, harness, &WireOverrides::default());
+}
+
+pub(crate) fn ensure_wired_with(
+ config: &Config,
+ harness: ManagedHarness,
+ overrides: &WireOverrides,
+) {
+ let Some(agent) = agent_choice_for_harness(harness) else {
+ return;
+ };
+ let sentinel = sentinel_path(&config.data_dir, agent);
+ if sentinel.exists() {
+ return;
+ }
+
+ 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 server_url = Some(config.server_url.clone());
+ let auth_token = config.auth.bearer_token.clone();
+
+ if let Err(error) = install_hooks::run(
+ config,
+ InstallHooksArgs {
+ agent,
+ hooks_dir: overrides.hooks_dir.clone(),
+ server_url: server_url.clone(),
+ auth_token: auth_token.clone(),
+ as_user: None,
+ apply: true,
+ config_file: overrides.hooks_config_file.clone(),
+ project_strategy: None,
+ capture_assistant: false,
+ capture_mode: None,
+ no_capture_prompts: false,
+ capture_prompts: false,
+ profile: None,
+ },
+ ) {
+ eprintln!(
+ "ai-memory: could not auto-install {} hooks ({error:#}); continuing launch. \
+ Wire them manually with `ai-memory install-hooks --agent {} --apply`.",
+ harness.as_str(),
+ agent.kind().as_str()
+ );
+ }
+
+ // Not every hook-capable harness has an MCP client the installer can write
+ // (e.g. Pi bridges MCP through its generated extension); skip those quietly.
+ if let Some(client) = install_hooks::mcp_client_for_agent(agent)
+ && let Err(error) = install_mcp::run(
+ config,
+ InstallMcpArgs {
+ client,
+ server_url,
+ name: "ai-memory".to_string(),
+ auth_token,
+ apply: true,
+ config_file: overrides.mcp_config_file.clone(),
+ session_aware: false,
+ flavor: None,
+ },
+ )
+ {
+ eprintln!(
+ "ai-memory: could not auto-install the {} MCP server ({error:#}); continuing \
+ launch. Wire it manually with `ai-memory install-mcp --client {} --apply`.",
+ harness.as_str(),
+ agent.kind().as_str()
+ );
+ }
+
+ // Record the attempt even on partial failure: re-applying an idempotent
+ // install on every launch would nag and churn config. A user who wants a
+ // retry can re-run install-hooks manually or clear the sentinel.
+ write_sentinel(&sentinel);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_launchable_harness_maps_or_is_deliberately_skipped() {
+ // Crush is the one launchable harness with no installer support.
+ assert!(agent_choice_for_harness(ManagedHarness::Crush).is_none());
+ for harness in [
+ ManagedHarness::Claude,
+ ManagedHarness::Codex,
+ ManagedHarness::OpenCode,
+ ManagedHarness::OpenCode2,
+ ManagedHarness::Pi,
+ ManagedHarness::Omp,
+ ManagedHarness::Kimi,
+ ManagedHarness::CommandCode,
+ ManagedHarness::Kiro,
+ ManagedHarness::KiroV3,
+ ManagedHarness::Grok,
+ ManagedHarness::Antigravity,
+ ] {
+ assert!(
+ agent_choice_for_harness(harness).is_some(),
+ "{harness:?} must map to an AgentChoice for autowire"
+ );
+ }
+ }
+
+ #[test]
+ fn kimi_maps_to_the_kimi_agent_and_client() {
+ let agent = agent_choice_for_harness(ManagedHarness::Kimi).unwrap();
+ assert_eq!(agent.kind().as_str(), "kimi-code");
+ assert!(
+ install_hooks::mcp_client_for_agent(agent).is_some(),
+ "Kimi has an MCP client the installer can write"
+ );
+ }
+
+ #[test]
+ fn pi_wires_hooks_but_has_no_mcp_client() {
+ let agent = agent_choice_for_harness(ManagedHarness::Pi).unwrap();
+ assert!(
+ install_hooks::mcp_client_for_agent(agent).is_none(),
+ "Pi bridges MCP through its extension, not a native mcp.json"
+ );
+ }
+
+ #[test]
+ fn sentinel_is_agent_and_version_specific() {
+ let dir = Path::new("/data");
+ let claude = sentinel_path(dir, AgentChoice::ClaudeCode);
+ let codex = sentinel_path(dir, AgentChoice::Codex);
+ assert_ne!(claude, codex, "different agents get distinct sentinels");
+ assert!(claude.starts_with("/data/autowire-state/"));
+ assert!(
+ claude
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(
+ |n| n.starts_with("claude-code-") && n.ends_with(env!("CARGO_PKG_VERSION"))
+ ),
+ "sentinel keys on agent + version: {claude:?}"
+ );
+ }
+
+ fn test_config(home: &Path, data_dir: &Path) -> Config {
+ let mut config = Config::load(None, Some(home.to_path_buf())).unwrap();
+ config.data_dir = data_dir.to_path_buf();
+ config.run_autowire = true;
+ config
+ }
+
+ fn repo_hooks() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../hooks")
+ }
+
+ /// 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 are
+ /// injected so the test never touches the developer's real `$HOME`.
+ #[test]
+ fn wiring_installs_and_preserves_user_config_then_is_idempotent() {
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let settings = data.path().join("claude-settings.json");
+ std::fs::write(&settings, r#"{"existingUserKey":"keep me"}"#).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()),
+ };
+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides);
+
+ let hooks_json = std::fs::read_to_string(&settings).unwrap();
+ assert!(
+ hooks_json.contains("existingUserKey"),
+ "unrelated user settings must be preserved: {hooks_json}"
+ );
+ assert!(
+ hooks_json.contains("ai-memory") || hooks_json.contains("ai_memory"),
+ "the ai-memory hook must be installed: {hooks_json}"
+ );
+ let mcp_json = std::fs::read_to_string(&mcp).unwrap();
+ assert!(
+ mcp_json.contains("existingMcpKey"),
+ "unrelated MCP config must be preserved: {mcp_json}"
+ );
+ assert!(
+ mcp_json.contains("ai-memory"),
+ "the ai-memory MCP server must be installed: {mcp_json}"
+ );
+ assert!(
+ sentinel_path(&config.data_dir, AgentChoice::ClaudeCode).exists(),
+ "the attempt must be recorded"
+ );
+
+ // Second launch: the sentinel gates it, so the files are byte-identical.
+ let before_hooks = std::fs::read(&settings).unwrap();
+ let before_mcp = std::fs::read(&mcp).unwrap();
+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides);
+ assert_eq!(
+ std::fs::read(&settings).unwrap(),
+ before_hooks,
+ "a gated re-launch must not rewrite hook config"
+ );
+ assert_eq!(
+ std::fs::read(&mcp).unwrap(),
+ before_mcp,
+ "a gated re-launch must not rewrite MCP config"
+ );
+ }
+
+ /// A harness with no installer support (Crush) is skipped before anything is
+ /// written — no config touched, no sentinel churn.
+ #[test]
+ fn unsupported_harness_wires_nothing() {
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let config = test_config(home.path(), data.path());
+ ensure_wired_with(&config, ManagedHarness::Crush, &WireOverrides::default());
+ assert!(
+ !data.path().join("autowire-state").exists(),
+ "an unsupported harness must not create autowire state"
+ );
+ }
+
+ /// A pre-existing sentinel means the harness config is never touched, even if
+ /// the wiring logic were otherwise reached.
+ #[test]
+ fn a_present_sentinel_leaves_config_untouched() {
+ let home = tempfile::tempdir().unwrap();
+ let data = tempfile::tempdir().unwrap();
+ let config = test_config(home.path(), data.path());
+ let sentinel = sentinel_path(&config.data_dir, AgentChoice::ClaudeCode);
+ std::fs::create_dir_all(sentinel.parent().unwrap()).unwrap();
+ std::fs::write(&sentinel, b"").unwrap();
+
+ let settings = data.path().join("claude-settings.json");
+ std::fs::write(&settings, r#"{"existingUserKey":1}"#).unwrap();
+ ensure_wired_with(
+ &config,
+ ManagedHarness::Claude,
+ &WireOverrides {
+ hooks_dir: Some(repo_hooks()),
+ hooks_config_file: Some(settings.clone()),
+ mcp_config_file: None,
+ },
+ );
+ assert_eq!(
+ std::fs::read_to_string(&settings).unwrap(),
+ r#"{"existingUserKey":1}"#,
+ "a present sentinel must short-circuit before any install"
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rs
index aa82d7c8..b3f921d8 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -226,6 +226,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
executable: None,
yolo: args.yolo,
fresh: args.fresh,
+ no_autowire: false,
harness: Some(harness),
native_args: args.native_args,
},
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index f0b33875..adb718e0 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -273,6 +273,14 @@ pub struct Config {
/// off with `AI_MEMORY_BACKFILL_ON_START=false` or `backfill_on_start =
/// false`; `ai-memory backfill` remains available to run it by hand.
pub backfill_on_start: bool,
+ /// On by default. The first time `ai-memory run <harness>` launches a
+ /// harness (per harness + binary version), it auto-installs that harness's
+ /// ai-memory lifecycle hooks and MCP server if they are not already wired,
+ /// so managed launches capture and can query memory without a manual
+ /// `install-hooks` / `install-mcp` step. Idempotent and one-time per
+ /// harness. Turn off with `AI_MEMORY_RUN_AUTOWIRE=false` /
+ /// `run_autowire = false`, or per launch with `ai-memory run --no-autowire`.
+ pub run_autowire: bool,
/// Strip root-level `anyOf`/`oneOf`/`allOf` from MCP tool input
/// schemas (e.g. `memory_read_page`'s "exactly one of path/query"
/// contract) on every `tools/list`, regardless of client or `?flavor=`
@@ -728,6 +736,7 @@ impl Default for Config {
consolidate_on_session_end: false,
capture_assistant: false,
backfill_on_start: true,
+ run_autowire: true,
strip_root_combinators: false,
gemini_safe_schemas: false,
reranker: None,
diff --git a/docs/cookbook.md b/docs/cookbook.md
index f63c4f50..c32f086e 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -104,8 +104,10 @@ ai-memory serve # run the server
## When it isn't doing what you expect
-- **Nothing is being remembered**: hooks may not be installed — `ai-memory
- install-hooks --agent <your-agent> --apply`, and check `ai-memory status`.
+- **Nothing is being remembered**: hooks may not be installed. Easiest fix —
+ start the harness with `ai-memory run <harness>`, which auto-installs its
+ hooks + MCP on first launch; or wire it by hand with `ai-memory install-hooks
+ --agent <your-agent> --apply`. Then check `ai-memory status` / `ai-memory doctor`.
- **Only *some* agents are being remembered**: run `ai-memory doctor`. It lists
every harness that has local sessions in this project and whether the server
captured them — so a harness you rotated in without installing its hook (a
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 3389811a..2e485b97 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -7,6 +7,20 @@ keep their existing ai-memory behavior. There is no global mode toggle and no
`switch` command: using `run` selects the current workstream and transparently
creates or resumes the correct native session for the requested harness.
+**`ai-memory run` is the preferred way to start a harness — "if in doubt, run
+with ai-memory."** Beyond session continuity, the first time it launches a given
+harness it **auto-installs that harness's ai-memory hooks and MCP** if they are
+not already wired, so capture and recall work without a separate `install-hooks`
+/ `install-mcp` step (a common footgun: `ai-memory run kimi` used to capture
+nothing if the Kimi hooks were never installed). Auto-wire is idempotent and
+one-time per harness + binary version, preserves unrelated user config, runs
+before the harness starts so it picks up the fresh hooks, and is best-effort —
+if an install fails it warns and still launches. Harnesses without installer
+support (Crush) are skipped; Pi wires hooks but has no MCP client to write. Turn
+it off with `ai-memory run --no-autowire`, `AI_MEMORY_RUN_AUTOWIRE=false`, or
+`run_autowire = false` in config; manual `install-hooks` / `install-mcp` remain
+available for harnesses you never launch through `run`.
+
The launcher resolves its executable name through `PATH` directly — it does
not go through an interactive shell, so a `claude` defined only as a shell
`alias` in `.bashrc`/`.zshrc` is invisible to it. If you switch Claude