Skip to content

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

Rust

feat(run): warn before --yolo, offer ai-jail, add Claude true-yolo (#983)

AkitaOnRails80888360e2d4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e21d8a17..7171080f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `ai-memory run --yolo` now warns before disarming an agent's safety prompts
+ and, on Linux/macOS, offers to re-run the session inside
+ [ai-jail](https://github.com/akitaonrails/ai-jail) when it is installed.
+ The warning and offer are TTY-gated (stdin and stderr must both be real
+ terminals) and skipped entirely when already running inside ai-jail
+ (detected via the Linux `ai-sandbox` hostname or the macOS `(jail) ` `PS1`
+ prefix), so hook, CI, detached, and piped runs are unaffected. Accepting
+ the ai-jail offer re-execs the original invocation under `ai-jail
+ --network --agent-state <harness> --env <NAME>...` (only already-set
+ credential/config env vars are forwarded); declining `--yolo` itself
+ aborts before the agent spawns. A new opt-in `--true-yolo` flag /
+ `claude_true_yolo` config key additionally silences Claude Code's
+ residual `--dangerously-skip-permissions` prompts (the `rm` timeout and
+ confirmation, and the PowerShell `rm` deny) and forces
+ `--settings '{"permissions":{"defaultMode":"bypassPermissions","ask":[]}}'`;
+ it is a no-op for every other harness. See
+ `docs/design-yolo-safety-ai-jail.md`. (#983)
- `ai-memory repair-backfill-timestamps [--project] [--workspace] [--confirm]
[--json]` and `POST /admin/repair-session-times` correct
`sessions.started_at`/`ended_at` for sessions an older `backfill` imported
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 0fe43784..0e2ab73c 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -284,6 +284,15 @@ pub struct RunArgs {
/// equivalent dangerous-mode option.
#[arg(long)]
pub yolo: bool,
+ /// Claude-only: additionally silence the residual `--dangerously-skip-permissions`
+ /// prompts (rm timeout/confirmation, PowerShell rm deny) and force
+ /// `bypassPermissions` via `--settings`. No-op for every other harness
+ /// (a one-line note is printed instead of being silently ignored).
+ /// Off by default; overrides `[claude_true_yolo]` in config.toml when
+ /// passed. Best paired with ai-jail — see
+ /// `docs/design-yolo-safety-ai-jail.md`.
+ #[arg(long = "true-yolo")]
+ pub true_yolo: bool,
/// Start a new native session in the selected workstream instead of
/// resuming or adopting an existing harness session.
#[arg(long)]
@@ -432,6 +441,9 @@ pub struct ShowArgs {
/// equivalent dangerous-mode option. Forwarded to `run`.
#[arg(long)]
pub yolo: bool,
+ /// Claude-only true-yolo (see `RunArgs::true_yolo`). Forwarded to `run`.
+ #[arg(long = "true-yolo")]
+ pub true_yolo: bool,
/// Start a new native session instead of resuming or adopting an existing
/// harness session. Forwarded to `run`.
#[arg(long)]
@@ -455,6 +467,9 @@ pub struct ContinueArgs {
/// equivalent dangerous-mode option. Forwarded to `run`.
#[arg(long)]
pub yolo: bool,
+ /// Claude-only true-yolo (see `RunArgs::true_yolo`). Forwarded to `run`.
+ #[arg(long = "true-yolo")]
+ pub true_yolo: bool,
/// Start a new native session instead of resuming the linked one.
/// Forwarded to `run`.
#[arg(long)]
@@ -478,6 +493,9 @@ pub struct ResumeArgs {
/// equivalent dangerous-mode option. Forwarded to `run`.
#[arg(long)]
pub yolo: bool,
+ /// Claude-only true-yolo (see `RunArgs::true_yolo`). Forwarded to `run`.
+ #[arg(long = "true-yolo")]
+ pub true_yolo: bool,
/// Start a new native session instead of resuming the linked one.
/// Forwarded to `run`.
#[arg(long)]
diff --git a/crates/ai-memory-cli/src/commands/continue_session.rs b/crates/ai-memory-cli/src/commands/continue_session.rs
index 5c31da92..5e6fd866 100644
--- a/crates/ai-memory-cli/src/commands/continue_session.rs
+++ b/crates/ai-memory-cli/src/commands/continue_session.rs
@@ -72,6 +72,7 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {
new_workstream: None,
executable: None,
yolo: args.yolo,
+ true_yolo: args.true_yolo,
fresh: args.fresh,
no_autowire: false,
env: Vec::new(),
diff --git a/crates/ai-memory-cli/src/commands/resume.rs b/crates/ai-memory-cli/src/commands/resume.rs
index ba9b1c25..f9948122 100644
--- a/crates/ai-memory-cli/src/commands/resume.rs
+++ b/crates/ai-memory-cli/src/commands/resume.rs
@@ -161,6 +161,7 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {
new_workstream: None,
executable: None,
yolo: args.yolo,
+ true_yolo: args.true_yolo,
fresh: args.fresh,
no_autowire: false,
env: Vec::new(),
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 91e7f340..7922f723 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -12,14 +12,16 @@ use ai_memory_core::{
PrepareManagedRunResponse, SessionId,
};
use ai_memory_workstream::{
- AmbiguousNativeSession, ExportedTranscript, LaunchMode, LaunchPlan, LaunchRoots,
- ManagedHarness, NativeSessionCandidate, allows_native_session_adoption, apply_yolo,
+ AmbiguousNativeSession, ExportedTranscript, FORWARDED_ENV_NAMES, LaunchMode, LaunchPlan,
+ LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_on_path,
+ allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,
build_launch_plan, build_launch_plan_with_env, crush_global_config_path,
- discover_native_session, export_transcript, has_native_session_selector, inspect_repository,
- kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
- kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
- list_native_sessions, native_session_exists, native_session_in_checkout, omp_profile_flag,
- omp_profile_flag_env, store_override_vars, wait_for_transcript_flush,
+ discover_native_session, export_transcript, has_native_session_selector, inside_ai_jail_here,
+ inspect_repository, kiro_explicit_session_id, kiro_harness_from_source_cursor,
+ kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,
+ kiro_v3_resume_uses_default_store, list_native_sessions, native_session_exists,
+ native_session_in_checkout, omp_profile_flag, omp_profile_flag_env, store_override_vars,
+ wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -115,9 +117,10 @@ pub(super) async fn run_from_with_wiring(
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 yolo_requested = args.yolo || trailing_yolo;
let force_fresh = args.fresh || trailing_fresh;
let no_autowire = args.no_autowire || trailing_no_autowire;
- let run_env = resolve_run_env(args.env_file.as_deref(), &args.env)
+ let mut run_env = resolve_run_env(args.env_file.as_deref(), &args.env)
.context("resolving --env/--env-file for the managed run")?;
if automatic_harness && !native_args.is_empty() {
return Err(anyhow!(
@@ -242,6 +245,20 @@ pub(super) async fn run_from_with_wiring(
resolved_harness
};
acquired_try!(ensure_executable_available(harness, executable.as_deref()));
+ // Warn, and offer ai-jail, before any further native-session work — a
+ // yolo re-exec under ai-jail must forward the original argv, not the
+ // resolved launch plan, and restarting cleanly under ai-jail before
+ // session adoption/linking begins keeps that linking simple (#16: this
+ // sits around session-identity resolution, not inside it).
+ acquired_try!(
+ confirm_yolo_and_maybe_reexec(
+ yolo_requested,
+ &endpoint,
+ &run_path,
+ &interrupted_before_spawn,
+ )
+ .await
+ );
let native_grok_rules = user_supplied_grok_rules(&native_args);
let (mut plan, orphaned_session) = acquired_try!(build_preflighted_launch_plan(
harness,
@@ -351,7 +368,7 @@ pub(super) async fn run_from_with_wiring(
),
}
}
- if args.yolo || trailing_yolo {
+ if yolo_requested {
// Kiro's official dangerous mode exists on the v2 engine only
// (`--trust-all-tools`); the v3 engine replaced it with
// permissions.yaml and documents no CLI equivalent, so the wrapper
@@ -366,6 +383,19 @@ pub(super) async fn run_from_with_wiring(
}
apply_yolo(harness, &mut plan.args);
}
+ // Claude-only "true yolo": opt-in, independent of `--yolo` (see
+ // `docs/design-yolo-safety-ai-jail.md` §4). Applied to the same
+ // env/args the child command is built from below.
+ if args.true_yolo || config.claude_true_yolo {
+ if harness == ManagedHarness::Claude {
+ apply_claude_true_yolo(harness, &mut run_env, &mut plan.args);
+ } else if args.true_yolo {
+ eprintln!(
+ "ai-memory: --true-yolo only affects the Claude harness; ignoring it for {}",
+ harness.as_str()
+ );
+ }
+ }
let remove_kiro_home = if harness == ManagedHarness::KiroV3
&& let Some(native_session_id) = plan.expected_session_id.as_deref()
{
@@ -780,6 +810,159 @@ async fn cancel_managed_run_after_failure(endpoint: &ServerEndpoint, run_path: &
}
}
+/// Whether a `--yolo` launch should warn (and offer ai-jail) before spawning
+/// the agent: `--yolo` was actually requested, both `stdin` and `stderr` are
+/// real terminals (mirrors the native-session-picker gate), and we are not
+/// already running inside ai-jail. `jailed` failing open to `false` (see
+/// [`ai_memory_workstream::inside_ai_jail`]) means an undetectable sandbox
+/// still shows the warning rather than silently skipping it.
+fn should_prompt_yolo(yolo: bool, stdin_tty: bool, stderr_tty: bool, jailed: bool) -> bool {
+ yolo && stdin_tty && stderr_tty && !jailed
+}
+
+/// A confirmation line's yes/no verdict: `Enter`/empty, `y`, or `yes`
+/// (case-insensitive) proceed; only an explicit `n`/`no` declines. Anything
+/// else also proceeds — this is a `[Y/n]` prompt, not a strict allowlist.
+fn yolo_decision(confirmed_line: &str) -> bool {
+ !matches!(
+ confirmed_line.trim().to_ascii_lowercase().as_str(),
+ "n" | "no"
+ )
+}
+
+/// The two yes/no answers `read_yolo_confirmation` can return: whether to
+/// proceed with `--yolo` at all, and, only when ai-jail is offered, whether
+/// to re-exec under it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct YoloConfirmation {
+ proceed: bool,
+ jail: bool,
+}
+
+/// Print the `--yolo` warning (docs/design-yolo-safety-ai-jail.md §1), and
+/// the ai-jail offer when available (§2), then read the confirming line(s).
+/// `input`/`output` are injected so the wording and default-yes semantics
+/// are unit-tested without a real terminal.
+fn read_yolo_confirmation(
+ ai_jail_available: bool,
+ input: &mut impl io::BufRead,
+ output: &mut impl io::Write,
+) -> io::Result<YoloConfirmation> {
+ writeln!(
+ output,
+ "⚠ --yolo runs every tool call with no confirmation. An agent can delete"
+ )?;
+ writeln!(
+ output,
+ " files, run any command, and reach the network unsupervised."
+ )?;
+ write!(output, " Proceed? [Y/n] ")?;
+ output.flush()?;
+ let mut line = String::new();
+ input.read_line(&mut line)?;
+ if !yolo_decision(&line) {
+ return Ok(YoloConfirmation {
+ proceed: false,
+ jail: false,
+ });
+ }
+ if !ai_jail_available {
+ return Ok(YoloConfirmation {
+ proceed: true,
+ jail: false,
+ });
+ }
+ write!(
+ output,
+ "ai-jail is installed. Re-run this session inside it? [Y/n] "
+ )?;
+ output.flush()?;
+ let mut jail_line = String::new();
+ input.read_line(&mut jail_line)?;
+ Ok(YoloConfirmation {
+ proceed: true,
+ jail: yolo_decision(&jail_line),
+ })
+}
+
+/// The interactive `--yolo` gate (docs/design-yolo-safety-ai-jail.md). A
+/// no-op outside a real TTY, when `--yolo` was not requested, or when already
+/// inside ai-jail. On confirmation it either returns (unjailed, or the user
+/// declined the ai-jail offer) or, on accepting the offer, cancels this
+/// process's already-prepared managed run and re-execs the original
+/// invocation under `ai-jail` — which never returns on success.
+async fn confirm_yolo_and_maybe_reexec(
+ yolo_requested: bool,
+ endpoint: &ServerEndpoint,
+ run_path: &str,
+ interrupted: &CancellationToken,
+) -> Result<()> {
+ let jailed = inside_ai_jail_here();
+ if !should_prompt_yolo(
+ yolo_requested,
+ io::stdin().is_terminal(),
+ io::stderr().is_terminal(),
+ jailed,
+ ) {
+ return Ok(());
+ }
+ if interrupted.is_cancelled() {
+ return Err(anyhow!("managed run interrupted before the agent started"));
+ }
+ let ai_jail_available = ai_jail_on_path();
+ let confirmation = tokio::task::spawn_blocking(move || {
+ let stdin = io::stdin();
+ let mut stderr = io::stderr();
+ read_yolo_confirmation(ai_jail_available, &mut stdin.lock(), &mut stderr)
+ })
+ .await
+ .context("waiting for the --yolo confirmation")?
+ .context("reading the --yolo confirmation from stdin")?;
+ if !confirmation.proceed {
+ return Err(anyhow!("aborted: --yolo not confirmed"));
+ }
+ if !confirmation.jail {
+ return Ok(());
+ }
+ // 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;
+ let exe = std::env::current_exe()
+ .context("resolving the current executable for the ai-jail re-exec")?;
+ let forwarded: Vec<OsString> = std::env::args_os().skip(1).collect();
+ let present: Vec<&str> = FORWARDED_ENV_NAMES
+ .iter()
+ .copied()
+ .filter(|name| std::env::var_os(name).is_some())
+ .collect();
+ // `--agent-state` is a bare toggle: enable it so the harness's own login
+ // state survives ai-jail's ephemeral private home (ai-jail derives the
+ // per-harness state location from the wrapped `run <harness>` it parses).
+ let jail_args = build_ai_jail_invocation(&exe, &forwarded, &present, true);
+ reexec_under_ai_jail(&jail_args)
+}
+
+/// Replace this process with `ai-jail <jail_args>` on Unix (never returns on
+/// success); elsewhere, spawn it, wait, and exit with its status (also never
+/// returns).
+#[cfg(unix)]
+fn reexec_under_ai_jail(jail_args: &[OsString]) -> Result<()> {
+ use std::os::unix::process::CommandExt as _;
+ let error = std::process::Command::new("ai-jail").args(jail_args).exec();
+ Err(anyhow!("{error}")).context("re-executing under ai-jail")
+}
+
+#[cfg(not(unix))]
+fn reexec_under_ai_jail(jail_args: &[OsString]) -> Result<()> {
+ let status = std::process::Command::new("ai-jail")
+ .args(jail_args)
+ .status()
+ .context("spawning ai-jail")?;
+ std::process::exit(status.code().unwrap_or(1));
+}
+
/// The session this run can prove is its own: the one it launched or resumed,
/// or the one its child linked under the run's id. A concurrent launch in the
/// same checkout cannot link under this run's id, while discovery can only
@@ -1813,6 +1996,101 @@ mod tests {
use super::*;
use crate::cli::{Cli, Command as CliCommand};
+ #[test]
+ fn should_prompt_yolo_requires_yolo_and_both_ttys_and_not_jailed() {
+ assert!(should_prompt_yolo(true, true, true, false));
+ assert!(
+ !should_prompt_yolo(false, true, true, false),
+ "no prompt when --yolo was not requested"
+ );
+ assert!(
+ !should_prompt_yolo(true, false, true, false),
+ "no prompt when stdin is not a TTY"
+ );
+ assert!(
+ !should_prompt_yolo(true, true, false, false),
+ "no prompt when stderr is not a TTY"
+ );
+ assert!(
+ !should_prompt_yolo(true, true, true, true),
+ "no prompt when already inside ai-jail"
+ );
+ }
+
+ #[test]
+ fn yolo_decision_defaults_to_proceed() {
+ assert!(yolo_decision(""), "empty line (bare Enter) proceeds");
+ assert!(yolo_decision("\n"));
+ assert!(yolo_decision("y"));
+ assert!(yolo_decision("Y"));
+ assert!(yolo_decision("yes"));
+ assert!(yolo_decision("YES"));
+ assert!(
+ yolo_decision("whatever"),
+ "an unrecognized line still proceeds (default yes)"
+ );
+ }
+
+ #[test]
+ fn yolo_decision_declines_only_on_explicit_no() {
+ assert!(!yolo_decision("n"));
+ assert!(!yolo_decision("N"));
+ assert!(!yolo_decision("no"));
+ assert!(!yolo_decision("NO\n"));
+ }
+
+ #[test]
+ fn read_yolo_confirmation_default_enter_proceeds_without_jail_offer() {
+ let mut input = Cursor::new(b"\n".to_vec());
+ let mut output = Vec::new();
+ let confirmation = read_yolo_confirmation(false, &mut input, &mut output).unwrap();
+ assert_eq!(
+ confirmation,
+ YoloConfirmation {
+ proceed: true,
+ jail: false
+ }
+ );
+ let printed = String::from_utf8(output).unwrap();
+ assert!(printed.contains("Proceed? [Y/n]"));
+ assert!(!printed.contains("ai-jail is installed"));
+ }
+
+ #[test]
+ fn read_yolo_confirmation_decline_aborts_before_the_jail_offer() {
+ let mut input = Cursor::new(b"n\n".to_vec());
+ let mut output = Vec::new();
+ let confirmation = read_yolo_confirmation(true, &mut input, &mut output).unwrap();
+ assert_eq!(
+ confirmation,
+ YoloConfirmation {
+ proceed: false,
+ jail: false
+ }
+ );
+ let printed = String::from_utf8(output).unwrap();
+ assert!(
+ !printed.contains("ai-jail is installed"),
+ "declining --yolo must never reach the ai-jail offer"
+ );
+ }
+
+ #[test]
+ fn read_yolo_confirmation_offers_ai_jail_and_reads_its_answer() {
+ let mut input = Cursor::new(b"\nn\n".to_vec());
+ let mut output = Vec::new();
+ let confirmation = read_yolo_confirmation(true, &mut input, &mut output).unwrap();
+ assert_eq!(
+ confirmation,
+ YoloConfirmation {
+ proceed: true,
+ jail: false
+ }
+ );
+ let printed = String::from_utf8(output).unwrap();
+ assert!(printed.contains("ai-jail is installed. Re-run this session inside it? [Y/n]"));
+ }
+
#[tokio::test(start_paused = true)]
async fn native_session_choice_interrupt_does_not_wait_for_input() {
let interrupted = CancellationToken::new();
@@ -2686,6 +2964,7 @@ mod tests {
new_workstream: None,
executable: Some(script.clone()),
yolo: false,
+ true_yolo: false,
fresh: false,
no_autowire: true,
env: vec![("CLAUDE_CONFIG_DIR".to_string(), "/from/cli".to_string())],
@@ -3171,6 +3450,7 @@ mod tests {
new_workstream: None,
executable: Some(script.clone()),
yolo: false,
+ true_yolo: false,
fresh: false,
no_autowire: false,
env: Vec::new(),
@@ -3323,6 +3603,7 @@ mod tests {
new_workstream: None,
executable: Some(executable),
yolo: false,
+ true_yolo: false,
fresh: false,
no_autowire: false,
env,
diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rs
index a093c8c4..f0e9a98f 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -225,6 +225,7 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
new_workstream: None,
executable: None,
yolo: args.yolo,
+ true_yolo: args.true_yolo,
fresh: args.fresh,
no_autowire: false,
env: Vec::new(),
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index e0bb216e..06dc6876 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -406,6 +406,17 @@ pub struct Config {
/// per harness and config home. Turn off with `AI_MEMORY_RUN_AUTOWIRE=false` /
/// `run_autowire = false`, or per launch with `ai-memory run --no-autowire`.
pub run_autowire: bool,
+ /// Off by default. When true, a Claude `ai-memory run --yolo` additionally
+ /// applies [`apply_claude_true_yolo`](ai_memory_workstream::apply_claude_true_yolo):
+ /// it disables the residual `rm`-prompt env vars and injects
+ /// `--settings` forcing `bypassPermissions`, so Claude Code stops
+ /// pausing even under `--dangerously-skip-permissions`. No-op for every
+ /// other harness. Best paired with ai-jail (see
+ /// `docs/design-yolo-safety-ai-jail.md`), since it does not widen a
+ /// user's own `deny`/`ask` rules. Set with `AI_MEMORY_CLAUDE_TRUE_YOLO=true`
+ /// or `claude_true_yolo = true` in config.toml; overridden per launch by
+ /// `ai-memory run --true-yolo`.
+ pub claude_true_yolo: 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=`
@@ -949,6 +960,7 @@ impl Default for Config {
capture_assistant: false,
backfill_on_start: true,
run_autowire: true,
+ claude_true_yolo: false,
strip_root_combinators: false,
gemini_safe_schemas: false,
reranker: None,
diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rs
index 0e72cf45..75506c0e 100644
--- a/crates/ai-memory-cli/tests/suite/main.rs
+++ b/crates/ai-memory-cli/tests/suite/main.rs
@@ -27,3 +27,4 @@ mod routing_skills;
mod serve_shutdown;
mod shutdown_signals;
mod upgrade_e2e;
+mod yolo_ai_jail;
diff --git a/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs b/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs
new file mode 100644
index 00000000..4767a325
--- /dev/null
+++ b/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs
@@ -0,0 +1,159 @@
+//! Integration coverage for the `--yolo` ai-jail re-exec contract.
+//!
+//! Unit tests in `ai-memory-workstream::jail` prove the pure argv assembly and
+//! per-OS detection. These tests assert the *cross-tool* contract: the argv
+//! `build_ai_jail_invocation` produces is one the real `ai-jail` binary accepts
+//! and forwards unchanged. The real-`ai-jail` test skips cleanly when ai-jail
+//! (or, on Linux, `bwrap`) is not installed, mirroring the opt-in discipline of
+//! `tests/e2e/handoff_smoke.sh`, so CI without a sandbox stays green.
+
+use std::ffi::OsString;
+use std::path::Path;
+use std::process::Command;
+
+use ai_memory_workstream::build_ai_jail_invocation;
+
+fn forwarded() -> Vec<OsString> {
+ ["run", "claude", "--yolo"]
+ .into_iter()
+ .map(OsString::from)
+ .collect()
+}
+
+/// ai-jail's parser (README "Positional command behavior is sacred") treats the
+/// first positional token as the wrapped program and captures everything after
+/// it verbatim. So every sandbox flag we emit must precede the wrapped exe, and
+/// the token right after the leading flags must be the exe itself — never a
+/// stray value. This is the exact shape a value-taking `--agent-state` would
+/// have broken (it would have made ai-jail run the value as the command).
+#[test]
+fn invocation_puts_all_sandbox_flags_before_the_wrapped_exe() {
+ let exe = Path::new("/usr/local/bin/ai-memory");
+ let argv = build_ai_jail_invocation(
+ exe,
+ &forwarded(),
+ &["AI_MEMORY_SERVER_URL", "ANTHROPIC_API_KEY"],
+ true,
+ );
+ let strs: Vec<String> = argv
+ .iter()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect();
+
+ // The wrapped exe is the first positional; everything before it is a known
+ // sandbox flag (or the value of `--env`), and everything from it on is the
+ // wrapped command.
+ let exe_pos = strs
+ .iter()
+ .position(|s| s == "/usr/local/bin/ai-memory")
+ .expect("wrapped exe present in argv");
+ assert_eq!(
+ &strs[exe_pos..],
+ &["/usr/local/bin/ai-memory", "run", "claude", "--yolo"],
+ "the wrapped command must be forwarded verbatim, right after the exe"
+ );
+
+ // `--agent-state` is a bare toggle: it must be followed by another flag or
+ // the exe, never by a value ai-jail would misread as the command.
+ let agent_state = strs
+ .iter()
+ .position(|s| s == "--agent-state")
+ .expect("agent-state flag");
+ let after = &strs[agent_state + 1];
+ assert!(
+ after.starts_with("--") || after == "/usr/local/bin/ai-memory",
+ "--agent-state must be a bare toggle, but is followed by {after:?}"
+ );
+}
+
+/// `--env` is emitted only for names the caller marked present, one flag per
+/// name, and never with an inline value (ai-jail forwards the host value for a
+/// bare `--env NAME`).
+#[test]
+fn invocation_emits_one_bare_env_flag_per_present_name() {
+ let exe = Path::new("/bin/ai-memory");
+ let argv = build_ai_jail_invocation(exe, &forwarded(), &["CLAUDE_CONFIG_DIR"], false);
+ let strs: Vec<String> = argv
+ .iter()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect();
+ let env_flags = strs.iter().filter(|s| *s == "--env").count();
+ assert_eq!(env_flags, 1);
+ let idx = strs.iter().position(|s| s == "--env").unwrap();
+ assert_eq!(strs[idx + 1], "CLAUDE_CONFIG_DIR");
+ assert!(
+ !strs[idx + 1].contains('='),
+ "forward the name, not name=value"
+ );
+ // agent_state=false → no toggle present.
+ assert!(!strs.iter().any(|s| s == "--agent-state"));
+}
+
+/// Locate `ai-jail` the same way the feature does; `None` ⇒ skip.
+fn ai_jail_path() -> Option<std::path::PathBuf> {
+ if let Some(path) = std::env::var_os("PATH") {
+ for dir in std::env::split_paths(&path) {
+ let candidate = dir.join("ai-jail");
+ if candidate.is_file() {
+ return Some(candidate);
+ }
+ }
+ }
+ let home = std::env::var_os("HOME")?;
+ let candidate = Path::new(&home).join(".local/bin/ai-jail");
+ candidate.is_file().then_some(candidate)
+}
+
+fn have_bwrap() -> bool {
+ std::env::var_os("PATH")
+ .map(|p| std::env::split_paths(&p).any(|d| d.join("bwrap").is_file()))
+ .unwrap_or(false)
+}
+
+/// The real integration check: the argv we build is accepted by the installed
+/// `ai-jail` under `--dry-run` (which prints the sandbox command without
+/// executing), and the wrapped `ai-memory run claude --yolo` survives verbatim.
+/// A malformed invocation — e.g. a value-taking `--agent-state` swallowing the
+/// exe — fails here. Skips when ai-jail (or Linux `bwrap`) is absent.
+#[test]
+fn real_ai_jail_dry_run_accepts_and_forwards_the_invocation() {
+ let Some(ai_jail) = ai_jail_path() else {
+ eprintln!("skipping: ai-jail not installed");
+ return;
+ };
+ if cfg!(target_os = "linux") && !have_bwrap() {
+ eprintln!("skipping: bwrap not installed (Linux ai-jail backend)");
+ return;
+ }
+
+ // Wrap a program that certainly exists, so any failure is about our argv
+ // shape, not an unresolvable command.
+ let exe = std::env::current_exe().expect("test binary path");
+ let argv = build_ai_jail_invocation(&exe, &forwarded(), &["AI_MEMORY_SERVER_URL"], true);
+
+ let output = Command::new(&ai_jail)
+ .arg("--dry-run")
+ .args(&argv)
+ .output()
+ .expect("run ai-jail --dry-run");
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let combined = format!("{stdout}{stderr}");
+
+ assert!(
+ output.status.success(),
+ "ai-jail --dry-run rejected the invocation:\nargv={argv:?}\nstdout={stdout}\nstderr={stderr}"
+ );
+ // The wrapped command must appear intact in the printed plan.
+ for token in ["run", "claude", "--yolo"] {
+ assert!(
+ combined.contains(token),
+ "dry-run plan is missing the wrapped token {token:?}; plan was:\n{combined}"
+ );
+ }
+ assert!(
+ combined.contains(&exe.to_string_lossy().into_owned()),
+ "dry-run plan should name the wrapped ai-memory exe; plan was:\n{combined}"
+ );
+}
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index 2fe960cc..ea71da4e 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -468,6 +468,37 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {
}
}
+/// Opt-in Claude-only "true yolo": on top of [`apply_yolo`]'s
+/// `--dangerously-skip-permissions`, silence the residual prompts Claude Code
+/// still shows (a 2-minute `rm` timeout/confirmation, and the PowerShell `rm`
+/// deny) and force `bypassPermissions` on the argv so CLI-flag precedence
+/// beats a user's own settings.json `defaultMode`. Does not widen a user's
+/// own `deny`/`ask` rules (those union across levels) — see
+/// `docs/design-yolo-safety-ai-jail.md` §4. A no-op for every harness other
+/// than [`ManagedHarness::Claude`]; callers print their own one-line note
+/// when that happens (documented, not silently ignored).
+pub fn apply_claude_true_yolo(
+ harness: ManagedHarness,
+ env: &mut Vec<(String, String)>,
+ args: &mut Vec<OsString>,
+) {
+ if harness != ManagedHarness::Claude {
+ return;
+ }
+ let mut set = |name: &str, value: &str| {
+ env.retain(|(key, _)| key != name);
+ env.push((name.to_string(), value.to_string()));
+ };
+ set("CLAUDE_CODE_DISABLE_DANGEROUS_RM_TIMEOUT", "1");
+ set("CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT", "1");
+ // A no-op off Windows; harmless to set everywhere.
+ set("CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY", "1");
+ args.push(OsString::from("--settings"));
+ args.push(OsString::from(
+ r#"{"permissions":{"defaultMode":"bypassPermissions","ask":[]}}"#,
+ ));
+}
+
/// Whether a native invocation may use ai-memory's one-time adoption prompt.
/// Explicit selectors and utility/ephemeral invocations always pass through.
#[must_use]
@@ -1541,6 +1572,49 @@ mod tests {
.collect()
}
+ #[test]
+ fn apply_claude_true_yolo_sets_env_and_settings_for_claude() {
+ let mut env = vec![("EXISTING".to_string(), "kept".to_string())];
+ let mut args = vec![OsString::from("--model"), OsString::from("opus")];
+ apply_claude_true_yolo(ManagedHarness::Claude, &mut env, &mut args);
+ assert_eq!(
+ env,
+ vec![
+ ("EXISTING".to_string(), "kept".to_string()),
+ (
+ "CLAUDE_CODE_DISABLE_DANGEROUS_RM_TIMEOUT".to_string(),
+ "1".to_string()
+ ),
+ (
+ "CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT".to_string(),
+ "1".to_string()
+ ),
+ (
+ "CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY".to_string(),
+ "1".to_string()
+ ),
+ ]
+ );
+ assert_eq!(
+ strings(&args),
+ [
+ "--model",
+ "opus",
+ "--settings",
+ r#"{"permissions":{"defaultMode":"bypassPermissions","ask":[]}}"#,
+ ]
+ );
+ }
+
+ #[test]
+ fn apply_claude_true_yolo_is_noop_for_other_harnesses() {
+ let mut env = Vec::new();
+ let mut args = vec![OsString::from("--yolo")];
+ apply_claude_true_yolo(ManagedHarness::Codex, &mut env, &mut args);
+ assert!(env.is_empty());
+ assert_eq!(strings(&args), ["--yolo"]);
+ }
+
#[test]
fn claude_generates_then_resumes_native_session() {
let fresh = build_launch_plan(ManagedHarness::Claude, None, vec![], None).unwrap();
diff --git a/crates/ai-memory-workstream/src/jail.rs b/crates/ai-memory-workstream/src/jail.rs
new file mode 100644
index 00000000..b29285a0
--- /dev/null
+++ b/crates/ai-memory-workstream/src/jail.rs
@@ -0,0 +1,300 @@
+//! ai-jail detection and invocation assembly for `ai-memory run --yolo`.
+//!
+//! See `docs/design-yolo-safety-ai-jail.md`. Detection and argv assembly are
+//! pure and dependency-injected so every OS branch and the exact argv shape
+//! are unit-tested without a real sandbox or a real PATH.
+
+use std::ffi::OsString;
+use std::path::{Path, PathBuf};
+
+/// Environment variable names forwarded into ai-jail with `--env NAME`, when
+/// actually set in the current process environment. ai-jail clears the
+/// environment by default and re-adds only what is explicitly named, so a
+/// managed run's server/hook URL and the harness's own credentials would
+/// otherwise be invisible inside the jail.
+pub const FORWARDED_ENV_NAMES: &[&str] = &[
+ "AI_MEMORY_SERVER_URL",
+ "AI_MEMORY_HOOK_URL",
+ "AI_MEMORY_DATA_DIR",
+ "AI_MEMORY_AUTH_TOKEN",
+ "CLAUDE_CONFIG_DIR",
+ "ANTHROPIC_API_KEY",
+ "ANTHROPIC_OAUTH_TOKEN",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "COPILOT_GITHUB_TOKEN",
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENROUTER_API_KEY",
+];
+
+/// Whether `ai-jail` resolves through a `which`-style lookup. `lookup` is
+/// injected so the resolution logic (PATH, `~/.local/bin`) is exercised by
+/// [`ai_jail_on_path`] while this stays a pure predicate for tests.
+#[must_use]
+pub fn ai_jail_installed(lookup: impl Fn(&str) -> Option<PathBuf>) -> bool {
+ lookup("ai-jail").is_some()
+}
+
+/// Real `ai-jail` lookup: `PATH`, falling back to `~/.local/bin/ai-jail`
+/// (ai-jail's own documented install location when it is not on `PATH`).
+#[must_use]
+pub fn ai_jail_on_path() -> bool {
+ ai_jail_installed(resolve_ai_jail)
+}
+
+fn resolve_ai_jail(name: &str) -> Option<PathBuf> {
+ if let Some(path) = std::env::var_os("PATH") {
+ for dir in std::env::split_paths(&path) {
+ let candidate = dir.join(name);
+ if is_executable_file(&candidate) {
+ return Some(candidate);
+ }
+ }
+ }
+ let home = std::env::var_os("HOME")?;
+ let candidate = PathBuf::from(home).join(".local").join("bin").join(name);
+ is_executable_file(&candidate).then_some(candidate)
+}
+
+fn is_executable_file(path: &Path) -> bool {
+ let Ok(metadata) = path.metadata() else {
+ return false;
+ };
+ if !metadata.is_file() {
+ return false;
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ metadata.permissions().mode() & 0o111 != 0
+ }
+ #[cfg(not(unix))]
+ {
+ true
+ }
+}
+
+/// The operating system whose ai-jail "already inside" signal applies.
+/// Taken explicitly (rather than read from `cfg!`) so [`inside_ai_jail`]'s
+/// branches are all reachable from a single-platform test run; the real
+/// caller uses [`current_jail_os`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum JailOs {
+ /// Linux: ai-jail (bwrap) always sets the UTS hostname to `ai-sandbox`.
+ Linux,
+ /// macOS: ai-jail (seatbelt) has no UTS namespace, so it forces `PS1` to
+ /// begin with `(jail) ` instead.
+ MacOs,
+ /// Windows: ai-jail is unsupported; never reports as jailed.
+ Windows,
+}
+
+/// The host's actual OS, for the real (non-test) detection path.
+#[must_use]
+pub const fn current_jail_os() -> JailOs {
+ if cfg!(target_os = "linux") {
+ JailOs::Linux
+ } else if cfg!(target_os = "macos") {
+ JailOs::MacOs
+ } else {
+ JailOs::Windows
+ }
+}
+
+/// Injected signals [`inside_ai_jail`] reads instead of the real process
+/// environment, so detection is testable without a sandbox.
+#[derive(Debug, Clone, Default)]
+pub struct JailEnv {
+ /// The current UTS hostname (Linux signal), e.g. from
+ /// `/proc/sys/kernel/hostname`.
+ pub hostname: Option<String>,
+ /// The current `PS1` value (macOS signal).
+ pub ps1: Option<String>,
+}
+
+/// Whether the process is already running inside ai-jail, per
+/// `docs/design-yolo-safety-ai-jail.md` §3.
+///
+/// Fails open to the safe side: an unrecognized or missing signal returns
+/// `false` (not jailed), so the yolo warning is shown rather than silently
+/// skipped. A false positive is not plausible for either signal by
+/// construction (ai-memory execs directly, not through an interactive
+/// shell); a false negative just repeats the warning inside a real jail,
+/// which is safe.
+#[must_use]
+pub fn inside_ai_jail(env: &JailEnv, os: JailOs) -> bool {
+ match os {
+ JailOs::Linux => env.hostname.as_deref() == Some("ai-sandbox"),
+ JailOs::MacOs => env
+ .ps1
+ .as_deref()
+ .is_some_and(|ps1| ps1.starts_with("(jail) ")),
+ JailOs::Windows => false,
+ }
+}
+
+/// Real "already inside ai-jail" check: reads the Linux hostname file and the
+/// process's own `PS1`, then applies [`inside_ai_jail`] for [`current_jail_os`].
+#[must_use]
+pub fn inside_ai_jail_here() -> bool {
+ let env = JailEnv {
+ hostname: read_linux_hostname(),
+ ps1: std::env::var("PS1").ok(),
+ };
+ inside_ai_jail(&env, current_jail_os())
+}
+
+fn read_linux_hostname() -> Option<String> {
+ if !cfg!(target_os = "linux") {
+ return None;
+ }
+ std::fs::read_to_string("/proc/sys/kernel/hostname")
+ .ok()
+ .map(|value| value.trim().to_string())
+}
+
+/// Build the argument vector for `ai-jail` (excluding the `ai-jail` program
+/// name itself): `--network`, an optional bare `--agent-state` toggle, one
+/// `--env NAME` per already-filtered present name, then the wrapped
+/// executable and its forwarded arguments in order.
+///
+/// `--agent-state` is a boolean toggle in ai-jail (`--agent-state` /
+/// `--no-agent-state`), not a valued flag — it persists the harness's own
+/// credential state across ai-jail's otherwise-ephemeral private home; ai-jail
+/// derives the per-harness state location itself from the wrapped
+/// `ai-memory run <harness>` it parses. `env_names_present` is caller-filtered
+/// (only names actually set in the current environment), keeping this function
+/// pure and independent of the real process environment.
+#[must_use]
+pub fn build_ai_jail_invocation(
+ exe: &Path,
+ forwarded_args: &[OsString],
+ env_names_present: &[&str],
+ agent_state: bool,
+) -> Vec<OsString> {
+ let mut argv = vec![OsString::from("--network")];
+ if agent_state {
+ argv.push(OsString::from("--agent-state"));
+ }
+ for name in env_names_present {
+ argv.push(OsString::from("--env"));
+ argv.push(OsString::from(*name));
+ }
+ argv.push(exe.as_os_str().to_os_string());
+ argv.extend(forwarded_args.iter().cloned());
+ argv
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn strings(args: &[OsString]) -> Vec<String> {
+ args.iter()
+ .map(|value| value.to_string_lossy().into_owned())
+ .collect()
+ }
+
+ #[test]
+ fn ai_jail_installed_true_when_lookup_resolves() {
+ assert!(ai_jail_installed(|name| {
+ assert_eq!(name, "ai-jail");
+ Some(PathBuf::from("/usr/bin/ai-jail"))
+ }));
+ }
+
+ #[test]
+ fn ai_jail_installed_false_when_lookup_misses() {
+ assert!(!ai_jail_installed(|_| None));
+ }
+
+ #[test]
+ fn inside_ai_jail_linux_matches_sandbox_hostname() {
+ let jailed = JailEnv {
+ hostname: Some("ai-sandbox".to_string()),
+ ps1: None,
+ };
+ assert!(inside_ai_jail(&jailed, JailOs::Linux));
+
+ let not_jailed = JailEnv {
+ hostname: Some("dev-box".to_string()),
+ ps1: None,
+ };
+ assert!(!inside_ai_jail(&not_jailed, JailOs::Linux));
+
+ let unknown = JailEnv::default();
+ assert!(!inside_ai_jail(&unknown, JailOs::Linux));
+ }
+
+ #[test]
+ fn inside_ai_jail_macos_matches_ps1_prefix() {
+ let jailed = JailEnv {
+ hostname: None,
+ ps1: Some("(jail) user@host $ ".to_string()),
+ };
+ assert!(inside_ai_jail(&jailed, JailOs::MacOs));
+
+ let not_jailed = JailEnv {
+ hostname: None,
+ ps1: Some("user@host $ ".to_string()),
+ };
+ assert!(!inside_ai_jail(&not_jailed, JailOs::MacOs));
+
+ let unknown = JailEnv::default();
+ assert!(!inside_ai_jail(&unknown, JailOs::MacOs));
+ }
+
+ #[test]
+ fn inside_ai_jail_windows_always_false() {
+ let env = JailEnv {
+ hostname: Some("ai-sandbox".to_string()),
+ ps1: Some("(jail) ".to_string()),
+ };
+ assert!(!inside_ai_jail(&env, JailOs::Windows));
+ }
+
+ #[test]
+ fn build_ai_jail_invocation_assembles_network_env_and_argv_in_order() {
+ let exe = Path::new("/usr/local/bin/ai-memory");
+ let forwarded = vec![
+ OsString::from("run"),
+ OsString::from("claude"),
+ OsString::from("--yolo"),
+ ];
+ let present = ["AI_MEMORY_SERVER_URL", "ANTHROPIC_API_KEY"];
+ let argv = build_ai_jail_invocation(exe, &forwarded, &present, true);
+ assert_eq!(
+ strings(&argv),
+ [
+ "--network",
+ "--agent-state",
+ "--env",
+ "AI_MEMORY_SERVER_URL",
+ "--env",
+ "ANTHROPIC_API_KEY",
+ "/usr/local/bin/ai-memory",
+ "run",
+ "claude",
+ "--yolo",
+ ]
+ );
+ }
+
+ #[test]
+ fn build_ai_jail_invocation_omits_agent_state_when_none() {
+ let exe = Path::new("/usr/local/bin/ai-memory");
+ let argv = build_ai_jail_invocation(exe, &[], &[], false);
+ assert_eq!(strings(&argv), ["--network", "/usr/local/bin/ai-memory"]);
+ }
+
+ #[test]
+ fn build_ai_jail_invocation_only_forwards_present_env_names() {
+ let exe = Path::new("/bin/ai-memory");
+ let argv = build_ai_jail_invocation(exe, &[], &["CLAUDE_CONFIG_DIR"], false);
+ assert_eq!(
+ strings(&argv),
+ ["--network", "--env", "CLAUDE_CONFIG_DIR", "/bin/ai-memory"]
+ );
+ }
+}
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index ae4895a1..e9a0087f 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -1,17 +1,22 @@
//! Read-only native harness adapters used by `ai-memory run`.
mod harness;
+mod jail;
mod repository;
mod transcript;
pub use harness::{
LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,
- apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path, crush_data_dir,
- crush_global_config_path, env_dir_override, has_native_session_selector,
+ apply_claude_true_yolo, apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path,
+ crush_data_dir, crush_global_config_path, env_dir_override, has_native_session_selector,
kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,
kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag, omp_profile_flag_env,
store_override_vars,
};
+pub use jail::{
+ FORWARDED_ENV_NAMES, JailEnv, JailOs, ai_jail_installed, ai_jail_on_path,
+ build_ai_jail_invocation, current_jail_os, inside_ai_jail, inside_ai_jail_here,
+};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 19c8d6cc..013b03a0 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -666,7 +666,7 @@ contradiction_band_max = 0.75 # (lower/upper cosine-similarity edge). The b
# Capture / launch UX (all default-on where noted). Each has an AI_MEMORY_* env
# override (AI_MEMORY_CAPTURE_ASSISTANT / AI_MEMORY_BACKFILL_ON_START /
-# AI_MEMORY_RUN_AUTOWIRE).
+# AI_MEMORY_RUN_AUTOWIRE / AI_MEMORY_CLAUDE_TRUE_YOLO).
capture_assistant = false # server-side opt-in: honor a Claude Code / Codex
# client's sanitized assistant-final-message marker
# on Stop (#196). Client half is baked separately by
@@ -680,6 +680,13 @@ run_autowire = true # `ai-memory run <harness>` auto-installs tha
# hooks + MCP on first launch if missing (idempotent,
# one-time per harness+version+install location).
# Also `--no-autowire`.
+claude_true_yolo = false # opt-in: on a Claude `ai-memory run --yolo`, also
+ # silence the residual `--dangerously-skip-permissions`
+ # prompts (rm timeout/confirmation, PowerShell rm deny)
+ # and force `bypassPermissions` via `--settings`.
+ # Claude-only, no-op for every other harness. Also
+ # `--true-yolo`. See
+ # docs/design-yolo-safety-ai-jail.md.
[decay] # M8 retention params
lambda = 0.02 # ↓ to forget less aggressively (fallback λ)
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 9f4e3d3d..d039e4e7 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -152,6 +152,45 @@ ai-memory run --env CODEX_HOME="$HOME/.codex-work" codex # the dir must exist
See [`managed-workstreams.md`](managed-workstreams.md).
+## Recipe: run an unsupervised agent safely (`--yolo` + ai-jail)
+
+`--yolo` maps to each harness's dangerous-mode flag (Claude Code →
+`--dangerously-skip-permissions`), which runs every tool call with no
+confirmation. `ai-memory run --yolo` adds guardrails around that, gated
+entirely on a real interactive terminal (stdin and stderr both TTYs), so
+scripts, hooks, and CI are never prompted:
+
+```bash
+ai-memory run --yolo claude
+```
+
+- **The warning.** Before the agent spawns, you are asked to confirm:
+ `Enter`/`y`/`yes` proceeds (the default); `n`/`no` aborts before anything
+ launches.
+- **The ai-jail offer.** If [ai-jail](https://github.com/akitaonrails/ai-jail)
+ is on `PATH` (or `~/.local/bin/ai-jail`) and you are not already inside it,
+ a second question offers to re-run the session inside it. Accepting
+ re-execs the original command under `ai-jail --network --agent-state
+ --env <NAME>...`, forwarding only the credential/config
+ environment variables that are already set (server/hook URL,
+ `CLAUDE_CONFIG_DIR`, provider API keys, etc.) — `--network` keeps the
+ loopback ai-memory server reachable while still sandboxing the filesystem.
+ Declining keeps the run unsandboxed (your choice, already warned).
+- **Already inside ai-jail.** Both prompts are skipped and the run proceeds
+ directly — `ai-jail ai-memory run … --yolo` sees no extra friction.
+ Detection is Linux (`ai-sandbox` hostname) / macOS (`PS1` starting with
+ `(jail) `); it fails open (shows the warning) when undetectable, never
+ open to skipping it silently.
+- **Claude "true yolo".** `--dangerously-skip-permissions` alone still pauses
+ Claude Code on `permissions.ask`/`deny` rules and on a 2-minute `rm`
+ confirmation. Opt in with `--true-yolo` (or `claude_true_yolo = true` in
+ `config.toml` / `AI_MEMORY_CLAUDE_TRUE_YOLO=true`) to also silence those —
+ Claude-only, off by default, and best paired with ai-jail since it does not
+ widen your own `deny`/`ask` rules.
+
+See [`design-yolo-safety-ai-jail.md`](design-yolo-safety-ai-jail.md) for the
+full contract.
+
## Recipe: run the server on a Mac
Use the menu bar app when you want one `.app` that starts the server and
diff --git a/docs/design-yolo-safety-ai-jail.md b/docs/design-yolo-safety-ai-jail.md
new file mode 100644
index 00000000..c46c8c08
--- /dev/null
+++ b/docs/design-yolo-safety-ai-jail.md
@@ -0,0 +1,188 @@
+# Design: safer `--yolo` and ai-jail integration
+
+Status: accepted (release/2.5). Tracks the 2.5 feature that makes
+`ai-memory run … --yolo` warn before it disarms an agent's safety prompts,
+offers to run the session inside [ai-jail](https://github.com/akitaonrails/ai-jail)
+when it is installed, and adds an opt-in "true yolo" for Claude Code that
+silences the residual permission pauses `--dangerously-skip-permissions`
+leaves behind.
+
+## Motivation
+
+`--yolo` maps to each harness's dangerous-mode flag (`apply_yolo`;
+Claude → `--dangerously-skip-permissions`). That is a loaded footgun: it runs
+every tool call with no confirmation. Three gaps:
+
+1. **No warning.** A user types `--yolo` and the agent is immediately
+ unsupervised, with no reminder of what that means or a way to back out.
+2. **No sandbox nudge.** ai-jail exists precisely to contain an unsupervised
+ agent, but nothing connects the two — the user must remember to type
+ `ai-jail ai-memory run …` themselves.
+3. **Claude still pauses.** Even with `--dangerously-skip-permissions`, Claude
+ Code still prompts on `permissions.ask`/`deny` rules and on critical-path
+ `rm` (a 2-minute timeout prompt), so an "unattended" yolo run stalls.
+
+## Non-goals
+
+- Changing default (non-`--yolo`) behavior. Everything here is gated on
+ `--yolo`.
+- Modifying ai-jail. Detection uses ai-jail's *existing* observable surface
+ (see "Already inside ai-jail"). No companion change is required.
+- Prompting in any non-interactive path. The warning/offer only appear on a
+ real TTY (hook, CI, detached, and piped runs are untouched).
+
+## The four parts
+
+### 1. Yolo warning prompt (all OSes)
+
+Before `apply_yolo` runs in `run.rs`, when `--yolo` is requested **and** the
+session is interactive (`stdin` and `stderr` are both terminals — the same
+gate the native-session picker already uses) **and** we are not already inside
+ai-jail:
+
+```
+⚠ --yolo runs every tool call with no confirmation. An agent can delete
+ files, run any command, and reach the network unsupervised.
+ Proceed? [Y/n]
+```
+
+Short, glanceable, `Enter` = yes. A `n`/`no` aborts before the agent spawns
+(exit non-zero, nothing launched). EOF/empty ⇒ yes (the default), because a
+bare `Enter` is the common case. This never fires in a non-TTY path, so
+scripts, hooks, and CI keep working unchanged.
+
+### 2. ai-jail detect + offer (Linux/macOS)
+
+If `ai-jail` is on `PATH` (`command -v ai-jail`, fallback `~/.local/bin/ai-jail`)
+and we are not already jailed, the prompt gains a second question:
+
+```
+ai-jail is installed. Re-run this session inside it? [Y/n]
+```
+
+On yes, ai-memory re-execs itself under ai-jail instead of spawning the agent
+directly:
+
+```
+ai-jail --network --agent-state <state> \
+ --env AI_MEMORY_SERVER_URL --env AI_MEMORY_HOOK_URL \
+ --env ANTHROPIC_API_KEY --env CLAUDE_CODE_OAUTH_TOKEN \
+ --env CLAUDE_CONFIG_DIR --env … \
+ <current_exe> run <harness> … --yolo
+```
+
+- **Re-exec**, not a nested spawn: `std::env::current_exe()` + the original
+ `args_os()`. ai-jail forwards the wrapped argv verbatim and already parses
+ `ai-memory run <harness>` (it keeps both the `ai-memory` binary and the
+ native harness visible under its private home), so the nested launch works.
+- **`--network` (not `--allow-host`).** ai-jail only adds `--unshare-net` when
+ network is *off* (`bwrap.rs`: `if !network_enabled { push("--unshare-net") }`),
+ so `--network` shares the host network namespace and the host-side ai-memory
+ server on `127.0.0.1:49374` — which the managed run and the agent's hooks
+ both need — is reachable. Filtered `--allow-host` uses a private netns with a
+ CONNECT proxy for *external* hosts only, so it would cut the loopback server
+ off; we deliberately do not use it. This is soft protection (full egress),
+ which is acceptable: the agent needs outbound network for its own model API
+ regardless, and an agent with no access is useless.
+- **Env passthrough.** ai-jail clears the environment by default and re-adds a
+ minimal allowlist, so `AI_MEMORY_*`, `CLAUDE_CONFIG_DIR`, and provider tokens
+ are **not** inherited. ai-memory forwards the ones it set (server/hook URL,
+ the token vars it already threads) with `--env NAME`. Only names that are
+ actually set in the current environment are forwarded.
+- **`--agent-state`** so the harness's own login/credentials persist across the
+ private home.
+
+If the user declines the ai-jail offer but confirmed `--yolo`, the run
+proceeds unjailed (their choice, already warned).
+
+### 3. Already inside ai-jail (skip the warning, avoid double-wrap)
+
+ai-jail exports **no** dedicated sentinel env var, and we chose not to add one
+(keeps the two projects decoupled). Detection uses ai-jail's existing
+observable surface, per OS:
+
+- **Linux:** ai-jail always sets a fresh UTS namespace with hostname
+ `ai-sandbox` (`bwrap.rs`, unconditional). Read `/proc/sys/kernel/hostname`
+ (or `uname`/`gethostname`) and compare. Reliable.
+- **macOS:** seatbelt has no UTS namespace, so the hostname is unchanged.
+ ai-jail forces `PS1` to begin with `(jail) ` on both backends; on macOS that
+ is the available signal. Weaker (a shell can overwrite `PS1`), but it only
+ ever *suppresses* the warning — a false negative just shows the warning
+ again inside the jail, which is safe; a false positive is unlikely because
+ ai-memory is exec'd directly by ai-jail, not through an interactive shell
+ that would reset `PS1`.
+- **Windows:** ai-jail is unsupported, so this always returns "not jailed";
+ the ai-jail offer is never shown.
+
+When detected as already jailed, both the warning and the ai-jail offer are
+skipped and the run proceeds directly — a user who typed
+`ai-jail ai-memory run … --yolo` sees no extra friction.
+
+### 4. Claude "true yolo" (opt-in, all OSes; recommended only under ai-jail)
+
+`--dangerously-skip-permissions` alone still pauses. Opt-in
+`[run] claude_true_yolo` (config) / `--true-yolo` (flag) additionally, **for
+the Claude harness only**:
+
+- Sets `CLAUDE_CODE_DISABLE_DANGEROUS_RM_TIMEOUT=1`,
+ `CLAUDE_CODE_DISABLE_SUBSTITUTION_RM_PROMPT=1`, and
+ `CLAUDE_CODE_DISABLE_POWERSHELL_CMD_RM_DENY=1` in the child env (the last is a
+ no-op off Windows; harmless to set everywhere). These remove the residual
+ `rm` prompts.
+- Injects `--settings '{"permissions":{"defaultMode":"bypassPermissions","ask":[]}}'`
+ on the Claude argv (CLI-flag precedence sits above user settings). This does
+ not remove a user's own `deny`/`ask` rules (those union across levels), so
+ true-yolo is documented as "best paired with a clean sandbox," i.e. ai-jail.
+
+Off by default. When enabled without ai-jail (and interactive), the warning
+text says so. Only applies to `ManagedHarness::Claude`; a no-op for other
+harnesses (documented, not silently ignored — a one-line note if `--true-yolo`
+is passed with a non-Claude harness).
+
+## OS support matrix
+
+| Concern | Linux | macOS | Windows |
+|---|---|---|---|
+| ai-jail available | bwrap | seatbelt | unsupported → no offer |
+| already-jailed detect | hostname `ai-sandbox` | `PS1` `(jail) ` | always "no" |
+| `--network` loopback reach | shared net ns | profile-allowed | n/a |
+| warning prompt | ✓ | ✓ | ✓ |
+| true-yolo env vars | ✓ | ✓ | ✓ (incl. powershell var) |
+
+## Code shape
+
+- `ai-memory-workstream/src/jail.rs` (new): pure, OS-aware, dependency-injected
+ detection + command construction — `ai_jail_installed(lookup)`,
+ `inside_ai_jail(env, hostname)`, `build_ai_jail_invocation(exe, args, env_names)`.
+ Pure functions so the OS branches and the argv/env assembly are unit-tested
+ without a sandbox.
+- `ai-memory-cli/src/commands/run.rs`: the interactive prompt + orchestration
+ (gate → warn → offer → re-exec or proceed), reusing the existing
+ `is_terminal` gate and a `confirm`-style reader.
+- `ai-memory-cli/src/config.rs`: `[run] claude_true_yolo: bool` (default false).
+- `ai-memory-workstream/src/harness.rs`: `apply_claude_true_yolo(env, args)`
+ next to `apply_yolo`.
+
+## Security considerations
+
+- The warning/offer are **TTY-gated**; no new prompt reaches hook, CI,
+ detached, or piped paths (mirrors the interactive-lock and native-picker
+ gates).
+- Re-exec forwards only environment names that are already set; it introduces
+ no new secret surface and does not log token values.
+- true-yolo is off by default, Claude-only, and documented as sandbox-first.
+- Detection failure fails *open* to the safe side: if we cannot tell we are
+ jailed, we show the warning (never silently skip it).
+
+## Testing
+
+- `jail.rs` unit tests: installed/not (injected lookup), inside/outside per OS
+ (injected env + hostname), invocation assembly (flags, `--env` only for set
+ names, current-exe + argv forwarding).
+- `run.rs`: prompt gate is off without a TTY; decline aborts before launch;
+ already-jailed skips the prompt; the ai-jail offer is absent when ai-jail is
+ not found.
+- `harness.rs`: `apply_claude_true_yolo` sets the three env vars + the
+ `--settings` arg for Claude and is a no-op for other harnesses.
+- CHANGELOG `### Added` (minor); support-matrix + cookbook updated in the same
+ change.
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index d84fdac7..3b788c97 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -22,6 +22,7 @@
| Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory-pi.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. |
| Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |
| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command Code, both incompatible Kiro CLI engines, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](managed-workstreams.md). |
+| `--yolo` safety + ai-jail | Linux/macOS; Windows partial | `ai-memory run --yolo` warns before it disarms an agent's permission prompts and, on Linux/macOS, offers to re-exec the session inside [ai-jail](https://github.com/akitaonrails/ai-jail) when it is installed (`--network`, forwarding only already-set credential/config env vars). Both prompts are skipped on a non-interactive stdin/stderr and when already detected inside ai-jail. Windows gets the warning but never the ai-jail offer (ai-jail is Linux/macOS-only). Opt-in `--true-yolo` / `claude_true_yolo` additionally silences Claude Code's residual `rm`-prompt env vars and forces `bypassPermissions`, on every OS, Claude only. See [`docs/design-yolo-safety-ai-jail.md`](design-yolo-safety-ai-jail.md). |
| Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |
| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). |