Skip to content

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

Rust

feat(run): choose ai-jail toggles with --jail[=LIST], --no-jail, and a checklist

AkitaOnRails7e0ec6589953
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d4ee52a5..67512b49 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added `ai-memory run --jail[=TOGGLES]` and `--no-jail`, and an interactive
+ checklist after the `--yolo` ai-jail offer, to choose which ai-jail
+ credentials and capabilities the jailed session gets. Bare `--jail` re-runs
+ inside ai-jail without asking, using smart defaults: every credential present
+ on the host (`~/.config/gh`, `~/.aws`, `~/.kube`, `~/.config/gcloud`,
+ `~/.docker/config.json`), SSH when `origin` is an SSH remote, and worktree
+ metadata in a linked worktree; host capabilities (`docker`, `gpu`,
+ `display`, `pictures`, `tailscale`) stay off. `--jail=github,aws,no-mise`
+ enables exactly the listed toggles (`all` and `none` also work), works
+ without `--yolo` and in scripts, and fails instead of running unjailed when
+ ai-jail is not usable. Only toggles the installed ai-jail advertises in its
+ `--help` are offered or passed; the credential mounts need ai-jail 2.5.0.
+ ai-jail's security switches (`seccomp`, `landlock`, `private-home`, …) are
+ never accepted. `--no-jail` skips the offer while keeping the `--yolo`
+ warning. A project `.ai-jail` in the launch directory replaces the checklist
+ and the bare-`--jail` defaults (ai-jail loads it under its own trust rules;
+ `--jail=…` still applies on top), and every jailed re-run now passes
+ `--no-save-config`, so ai-jail no longer writes ai-memory's `--network` /
+ `--agent-state` / credential flags into the repository's `.ai-jail`.
+
### Fixed
- Fixed the shell and PowerShell session-start hooks for Claude Code, Codex,
Cursor, Gemini CLI, OpenCode, Command Code, Devin, and Antigravity CLI not
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 89eefcda..2c897037 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -298,6 +298,29 @@ pub struct RunArgs {
/// `docs/design-yolo-safety-ai-jail.md`.
#[arg(long = "true-yolo")]
pub true_yolo: bool,
+ /// Re-run this session inside ai-jail without asking. Bare `--jail` uses
+ /// the smart defaults (credentials present on this host, SSH for an SSH
+ /// `origin`, worktree metadata in a linked worktree); `--jail=LIST` enables
+ /// exactly the comma-separated ai-jail toggles listed (`github`, `aws`,
+ /// `ssh`, `gpu`, `docker`, …; `no-X` forces one off; `all`; `none`). A
+ /// project `.ai-jail` in the launch directory replaces the smart defaults
+ /// (a list still applies on top). Fails when ai-jail is not usable here;
+ /// ignored inside ai-jail. Wrapper-owned
+ /// like `--yolo`, never forwarded to the harness. See
+ /// `docs/design-yolo-safety-ai-jail.md`.
+ #[arg(
+ long,
+ value_name = "TOGGLES",
+ num_args = 0..=1,
+ require_equals = true,
+ default_missing_value = "",
+ conflicts_with = "no_jail"
+ )]
+ pub jail: Option<String>,
+ /// Never re-run inside ai-jail: skips the `--yolo` ai-jail offer (the
+ /// `--yolo` warning itself still shows).
+ #[arg(long)]
+ pub no_jail: bool,
/// Start a new native session in the selected workstream instead of
/// resuming or adopting an existing harness session.
#[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 5e6fd866..f5a75533 100644
--- a/crates/ai-memory-cli/src/commands/continue_session.rs
+++ b/crates/ai-memory-cli/src/commands/continue_session.rs
@@ -73,6 +73,8 @@ pub async fn run(config: &Config, args: ContinueArgs) -> Result<i32> {
executable: None,
yolo: args.yolo,
true_yolo: args.true_yolo,
+ jail: None,
+ no_jail: false,
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 f9948122..be4d5612 100644
--- a/crates/ai-memory-cli/src/commands/resume.rs
+++ b/crates/ai-memory-cli/src/commands/resume.rs
@@ -162,6 +162,8 @@ pub async fn run(config: &Config, args: ResumeArgs) -> Result<i32> {
executable: None,
yolo: args.yolo,
true_yolo: args.true_yolo,
+ jail: None,
+ no_jail: false,
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 c2fb8870..01a064fe 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -12,15 +12,17 @@ use ai_memory_core::{
PrepareManagedRunResponse, SessionId,
};
use ai_memory_workstream::{
- AmbiguousNativeSession, ExportedTranscript, FORWARDED_ENV_NAMES, LaunchMode, LaunchPlan,
- LaunchRoots, ManagedHarness, NativeSessionCandidate, 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, 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, usable_ai_jail_here, wait_for_transcript_flush,
+ AmbiguousNativeSession, ExportedTranscript, FORWARDED_ENV_NAMES, JailChecklistItem,
+ JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode, LaunchPlan,
+ LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,
+ allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,
+ build_launch_plan, build_launch_plan_with_env, checked_choices, crush_global_config_path,
+ discover_native_session, export_transcript, has_native_session_selector, inside_ai_jail_here,
+ inspect_repository, jail_checklist, jail_toggle, 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,
+ parse_jail_toggles, store_override_vars, usable_ai_jail_here, wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
use tokio::process::Command;
@@ -124,6 +126,8 @@ pub(super) async fn run_from_with_wiring(
let trailing_true_yolo = remove_wrapper_true_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 trailing_jail = remove_wrapper_jail(&mut native_args);
+ let jail_request = jail_request(args.jail, args.no_jail, trailing_jail)?;
let yolo_modes = yolo_modes(
args.yolo || trailing_yolo,
args.true_yolo || trailing_true_yolo,
@@ -167,14 +171,55 @@ pub(super) async fn run_from_with_wiring(
// another — the same repository split in two.
let (workspace, project) =
resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
+ let interactive = io::stdin().is_terminal() && io::stderr().is_terminal();
+ // Inside ai-jail every jail flag is moot (no nesting), so neither the
+ // binary lookup nor its errors apply there.
+ let jailed = inside_ai_jail_here();
+ let ai_jail = if jailed { None } else { usable_ai_jail_here() };
+ let jail_facts = JailHostFacts::here(&repository);
+ let jail_plan = jail_decision(
+ &jail_request,
+ jailed,
+ yolo_requested,
+ interactive,
+ ai_jail.is_some(),
+ jail_facts.project_config,
+ )?;
+ // An explicit `--jail` re-runs before any managed run is prepared: the
+ // jailed process opens its own, so preparing one out here would only be
+ // cancelled again.
+ if let (JailMode::Explicit(spec), Some(ai_jail)) = (&jail_plan.mode, &ai_jail) {
+ let support = ai_jail_support(ai_jail)
+ .with_context(|| format!("reading the toggles {} supports", ai_jail.display()))?;
+ // With a project `.ai-jail` nothing is pre-checked, so a bare
+ // `--jail` defers to that file while a listed toggle still overrides it.
+ let toggles = parse_jail_toggles(spec, &jail_checklist(&jail_facts, &support), &support)?;
+ if jail_plan.warn {
+ let confirmation = tokio::task::spawn_blocking(|| {
+ read_yolo_confirmation(false, &mut io::stdin().lock(), &mut io::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"));
+ }
+ }
+ return Err(exec_under_ai_jail(
+ ai_jail,
+ &support,
+ &toggles,
+ jail_facts.project_config,
+ ));
+ }
let may_adopt_native_session = args.new_workstream.is_none() && !force_fresh;
let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
let prepare = PrepareManagedRunRequest {
workspace: workspace.clone(),
project: project.clone(),
cwd: repository.cwd.to_string_lossy().into_owned(),
- repo_fingerprint: repository.repo_fingerprint,
- worktree_fingerprint: repository.worktree_fingerprint,
+ repo_fingerprint: repository.repo_fingerprint.clone(),
+ worktree_fingerprint: repository.worktree_fingerprint.clone(),
agent: provisional_harness.agent_kind(),
automatic_harness,
available_agents: unique_auto_agents(&auto_candidates),
@@ -184,7 +229,6 @@ pub(super) async fn run_from_with_wiring(
};
let interrupted_before_spawn = CancellationToken::new();
let interrupt_task = tokio::spawn(capture_interrupts(interrupted_before_spawn.clone()));
- let interactive = io::stdin().is_terminal() && io::stderr().is_terminal();
let prepared = prepare_managed_run(&endpoint, &prepare, interactive, &interrupted_before_spawn)
.await
.context("opening managed workstream; the agent was not started");
@@ -265,7 +309,9 @@ pub(super) async fn run_from_with_wiring(
// sits around session-identity resolution, not inside it).
acquired_try!(
confirm_yolo_and_maybe_reexec(
- yolo_requested,
+ &jail_plan,
+ ai_jail.as_deref(),
+ &jail_facts,
&endpoint,
&run_path,
&interrupted_before_spawn,
@@ -817,14 +863,130 @@ 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
+/// What the invocation asked for about ai-jail
+/// (docs/design-yolo-safety-ai-jail.md §5).
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum JailRequest {
+ /// Neither flag: the interactive `--yolo` offer.
+ Unspecified,
+ /// `--no-jail`.
+ Never,
+ /// `--jail` (empty list: smart defaults) or `--jail=LIST`.
+ Explicit(String),
+}
+
+/// `--jail`/`--no-jail` found among the native arguments (after the harness).
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+struct TrailingJail {
+ jail: Option<String>,
+ no_jail: bool,
+}
+
+/// Strip `--jail`, `--jail=LIST`, and `--no-jail` from the native arguments,
+/// like `--yolo`: they are wrapper flags and must never reach the harness. The
+/// last `--jail` wins, matching clap's handling before the harness name.
+fn remove_wrapper_jail(args: &mut Vec<OsString>) -> TrailingJail {
+ let mut found = TrailingJail::default();
+ args.retain(|arg| {
+ let Some(arg) = arg.to_str() else {
+ return true;
+ };
+ if arg == "--no-jail" {
+ found.no_jail = true;
+ return false;
+ }
+ if arg == "--jail" {
+ found.jail = Some(String::new());
+ return false;
+ }
+ if let Some(list) = arg.strip_prefix("--jail=") {
+ found.jail = Some(list.to_owned());
+ return false;
+ }
+ true
+ });
+ found
+}
+
+/// Merge the clap-parsed flags with any found after the harness name. The
+/// trailing `--jail` is later in argv, so it wins over a leading one.
+fn jail_request(
+ jail: Option<String>,
+ no_jail: bool,
+ trailing: TrailingJail,
+) -> Result<JailRequest> {
+ let jail = trailing.jail.or(jail);
+ let no_jail = no_jail || trailing.no_jail;
+ match (jail, no_jail) {
+ (Some(_), true) => Err(anyhow!("--jail and --no-jail cannot be used together")),
+ (Some(list), false) => Ok(JailRequest::Explicit(list)),
+ (None, true) => Ok(JailRequest::Never),
+ (None, false) => Ok(JailRequest::Unspecified),
+ }
+}
+
+/// How this launch treats ai-jail.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum JailMode {
+ /// Run unjailed (or already jailed): no question, no re-exec.
+ Stay,
+ /// After the `--yolo` warning, ask "Re-run inside it?" and, on yes, show
+ /// the toggle checklist — unless a project `.ai-jail` owns the toggles.
+ Offer {
+ /// Whether to show the checklist (no project `.ai-jail`).
+ checklist: bool,
+ },
+ /// Re-exec now with this toggle list, without asking.
+ Explicit(String),
+}
+
+/// Whether to show the `--yolo` warning, and what to do about ai-jail.
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct JailPlan {
+ warn: bool,
+ mode: JailMode,
+}
+
+/// The pure decision table behind `--jail`/`--no-jail`/`--yolo`
+/// (docs/design-yolo-safety-ai-jail.md §5). Inside ai-jail nothing applies (no
+/// nesting, no warning). Otherwise the `--yolo` warning shows whenever `--yolo`
+/// runs interactively; an explicit `--jail` re-execs even non-interactively
+/// (that is how scripts get a jailed run) and fails rather than silently
+/// running unjailed when ai-jail is not usable; without either flag, the offer
+/// is only made interactively, after the warning, when ai-jail is usable. A
+/// project `.ai-jail` (`project_config`) replaces the checklist: ai-jail loads
+/// that file itself, so the offer re-execs with no toggles of ours.
+fn jail_decision(
+ request: &JailRequest,
+ jailed: bool,
+ yolo: bool,
+ interactive: bool,
+ usable: bool,
+ project_config: bool,
+) -> Result<JailPlan> {
+ if jailed {
+ return Ok(JailPlan {
+ warn: false,
+ mode: JailMode::Stay,
+ });
+ }
+ let warn = yolo && interactive;
+ let mode = match request {
+ JailRequest::Never => JailMode::Stay,
+ JailRequest::Explicit(_) if !usable => {
+ return Err(anyhow!(
+ "--jail: ai-jail is not usable on this host (it needs `ai-jail` plus its sandbox \
+ backend, bwrap on Linux or sandbox-exec on macOS, and does not run on Windows); \
+ refusing to run unjailed — drop --jail to run without it"
+ ));
+ }
+ JailRequest::Explicit(list) => JailMode::Explicit(list.clone()),
+ JailRequest::Unspecified if warn && usable => JailMode::Offer {
+ checklist: !project_config,
+ },
+ JailRequest::Unspecified => JailMode::Stay,
+ };
+ Ok(JailPlan { warn, mode })
}
/// A confirmation line's yes/no verdict: `Enter`/empty, `y`, or `yes`
@@ -892,39 +1054,202 @@ fn read_yolo_confirmation(
})
}
-/// 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.
+/// Invalid checklist answers tolerated before giving up. Aborting is the safe
+/// end: guessing could mount credentials the user meant to leave out.
+const CHECKLIST_MAX_INVALID: usize = 3;
+
+/// One checklist answer's effect on the marks.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum ChecklistAnswer {
+ /// Empty line: accept as marked.
+ Accept,
+ /// Marks changed; show the list again.
+ Changed,
+ /// Not understood; nothing changed.
+ Invalid(String),
+}
+
+/// Apply one checklist line: empty accepts, `all`/`none` set every mark, and
+/// row numbers (separated by spaces or commas) flip those rows. A line with
+/// any bad number changes nothing.
+fn apply_checklist_answer(line: &str, checked: &mut [bool]) -> ChecklistAnswer {
+ let answer = line.trim().to_ascii_lowercase();
+ match answer.as_str() {
+ "" => return ChecklistAnswer::Accept,
+ "all" | "none" => {
+ checked.fill(answer == "all");
+ return ChecklistAnswer::Changed;
+ }
+ _ => {}
+ }
+ let mut rows = Vec::new();
+ for token in answer
+ .split([' ', ',', '\t'])
+ .filter(|token| !token.is_empty())
+ {
+ match token.parse::<usize>() {
+ Ok(row) if (1..=checked.len()).contains(&row) => rows.push(row - 1),
+ _ => {
+ return ChecklistAnswer::Invalid(format!(
+ "`{token}` is not a row number between 1 and {}; press Enter to accept, or type numbers, `all`, or `none`",
+ checked.len()
+ ));
+ }
+ }
+ }
+ for row in rows {
+ checked[row] = !checked[row];
+ }
+ ChecklistAnswer::Changed
+}
+
+fn render_checklist(
+ items: &[JailChecklistItem],
+ checked: &[bool],
+ output: &mut impl io::Write,
+) -> io::Result<()> {
+ writeln!(
+ output,
+ "Enable in the jail (Enter = as marked; numbers flip, e.g. \"2 4\"; \"all\" / \"none\"):"
+ )?;
+ let width = items
+ .iter()
+ .map(|item| item.toggle.label.chars().count())
+ .max()
+ .unwrap_or(0);
+ for (index, (item, on)) in items.iter().zip(checked).enumerate() {
+ let mark = if *on { 'x' } else { ' ' };
+ writeln!(
+ output,
+ " [{mark}] {}) {:<width$} {}",
+ index + 1,
+ item.toggle.label,
+ item.toggle.note
+ )?;
+ }
+ write!(output, "> ")?;
+ output.flush()
+}
+
+/// The interactive toggle checklist (docs/design-yolo-safety-ai-jail.md §5),
+/// line-based with injected `input`/`output` like [`read_yolo_confirmation`].
+/// Enter or EOF accepts the marks; the result enables every checked row.
+fn read_jail_checklist(
+ items: &[JailChecklistItem],
+ input: &mut impl io::BufRead,
+ output: &mut impl io::Write,
+) -> io::Result<Vec<JailToggleChoice>> {
+ let mut checked: Vec<bool> = items.iter().map(|item| item.checked).collect();
+ let mut invalid = 0;
+ loop {
+ render_checklist(items, &checked, output)?;
+ let mut line = String::new();
+ if input.read_line(&mut line)? == 0 {
+ writeln!(output)?;
+ break;
+ }
+ match apply_checklist_answer(&line, &mut checked) {
+ ChecklistAnswer::Accept => break,
+ ChecklistAnswer::Changed => {}
+ ChecklistAnswer::Invalid(message) => {
+ invalid += 1;
+ writeln!(output, "{message}")?;
+ if invalid >= CHECKLIST_MAX_INVALID {
+ return Err(io::Error::other(
+ "too many unrecognized answers to the ai-jail checklist",
+ ));
+ }
+ }
+ }
+ }
+ let marked: Vec<JailChecklistItem> = items
+ .iter()
+ .zip(checked)
+ .map(|(item, checked)| JailChecklistItem {
+ toggle: item.toggle,
+ checked,
+ })
+ .collect();
+ Ok(checked_choices(&marked))
+}
+
+/// The one-line account of what the jailed re-run enables, grouped the way
+/// the risk differs: credentials the agent can use, host capabilities, and
+/// toggles forced off — and whether the project `.ai-jail` supplies the rest.
+fn jail_summary(toggles: &[JailToggleChoice], project_config: bool) -> String {
+ let labels = |kind: JailToggleKind| -> Vec<&'static str> {
+ toggles
+ .iter()
+ .filter(|choice| choice.enable)
+ .filter_map(|choice| jail_toggle(choice.stem))
+ .filter(|toggle| toggle.kind == kind)
+ .map(|toggle| toggle.label)
+ .collect()
+ };
+ let mut parts = Vec::new();
+ for (heading, kind) in [
+ ("credentials", JailToggleKind::Credential),
+ ("capabilities", JailToggleKind::Capability),
+ ] {
+ let names = labels(kind);
+ if !names.is_empty() {
+ parts.push(format!("{heading}: {}", names.join(", ")));
+ }
+ }
+ let off: Vec<String> = toggles
+ .iter()
+ .filter(|choice| !choice.enable)
+ .map(JailToggleChoice::flag)
+ .collect();
+ if !off.is_empty() {
+ parts.push(format!("forced off: {}", off.join(" ")));
+ }
+ if project_config {
+ parts.push("plus the project .ai-jail".to_owned());
+ }
+ if parts.is_empty() {
+ "ai-memory: re-running inside ai-jail with no extra mounts".to_owned()
+ } else {
+ format!(
+ "ai-memory: re-running inside ai-jail ({})",
+ parts.join("; ")
+ )
+ }
+}
+
+/// The post-prepare `--yolo` gate (docs/design-yolo-safety-ai-jail.md). A
+/// no-op unless `plan.warn`. On confirmation it either returns (unjailed, or
+/// 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.
async fn confirm_yolo_and_maybe_reexec(
- yolo_requested: bool,
+ plan: &JailPlan,
+ ai_jail: Option<&Path>,
+ facts: &JailHostFacts,
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,
- ) {
+ if !plan.warn {
return Ok(());
}
if interrupted.is_cancelled() {
return Err(anyhow!("managed run interrupted before the agent started"));
}
- // Resolved once: `None` (Windows, ai-jail absent, or its sandbox backend
- // absent) suppresses the offer entirely, and `Some` is the exact binary
- // the re-exec runs.
- let ai_jail = usable_ai_jail_here();
+ // `jail_decision` only offers when ai-jail resolved, and `ai_jail` is the
+ // exact binary the re-exec runs. An explicit `--jail` re-exec'd earlier
+ // and never reaches here.
+ let (ai_jail, show_checklist) = match plan.mode {
+ JailMode::Offer { checklist } => (ai_jail, checklist),
+ JailMode::Stay | JailMode::Explicit(_) => (None, false),
+ };
let ai_jail_available = ai_jail.is_some();
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)
+ read_yolo_confirmation(
+ ai_jail_available,
+ &mut io::stdin().lock(),
+ &mut io::stderr(),
+ )
})
.await
.context("waiting for the --yolo confirmation")?
@@ -935,13 +1260,49 @@ async fn confirm_yolo_and_maybe_reexec(
let (true, Some(ai_jail)) = (confirmation.jail, ai_jail) else {
return Ok(());
};
+ let support = ai_jail_support(ai_jail)
+ .with_context(|| format!("reading the toggles {} supports", ai_jail.display()))?;
+ let items = jail_checklist(facts, &support);
+ // A project `.ai-jail` owns the toggles: ai-jail loads it itself, so no
+ // checklist and no flags of ours.
+ let toggles = if !show_checklist || items.is_empty() {
+ Vec::new()
+ } else {
+ tokio::task::spawn_blocking(move || {
+ read_jail_checklist(&items, &mut io::stdin().lock(), &mut io::stderr())
+ })
+ .await
+ .context("waiting for the ai-jail checklist")?
+ .context("reading the ai-jail checklist from stdin")?
+ };
// 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")?;
+ Err(exec_under_ai_jail(
+ ai_jail,
+ &support,
+ &toggles,
+ facts.project_config,
+ ))
+}
+
+/// Re-exec the original invocation under `ai_jail` with `toggles`, after the
+/// one-line summary. Returns only on failure.
+fn exec_under_ai_jail(
+ ai_jail: &Path,
+ support: &JailSupport,
+ toggles: &[JailToggleChoice],
+ project_config: bool,
+) -> anyhow::Error {
+ let exe = match std::env::current_exe() {
+ Ok(exe) => exe,
+ Err(error) => {
+ return anyhow!(error)
+ .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()
@@ -951,8 +1312,18 @@ async fn confirm_yolo_and_maybe_reexec(
// `--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(&ai_jail, &jail_args)
+ // `--no-save-config` keeps ai-jail from writing these transient flags into
+ // the project `.ai-jail` (see `build_ai_jail_invocation`).
+ let jail_args = build_ai_jail_invocation(
+ &exe,
+ &forwarded,
+ &present,
+ true,
+ support.supports("no-save-config"),
+ toggles,
+ );
+ eprintln!("{}", jail_summary(toggles, project_config));
+ reexec_under_ai_jail(ai_jail, &jail_args)
}
/// Replace this process with `<ai_jail> <jail_args>` on Unix (never returns
@@ -960,19 +1331,18 @@ async fn confirm_yolo_and_maybe_reexec(
/// never returns). `ai_jail` is the path [`usable_ai_jail_here`] resolved,
/// never a bare name re-resolved through `PATH`.
#[cfg(unix)]
-fn reexec_under_ai_jail(ai_jail: &Path, jail_args: &[OsString]) -> Result<()> {
+fn reexec_under_ai_jail(ai_jail: &Path, jail_args: &[OsString]) -> anyhow::Error {
use std::os::unix::process::CommandExt as _;
let error = std::process::Command::new(ai_jail).args(jail_args).exec();
- Err(anyhow!("{error}")).with_context(|| format!("re-executing under {}", ai_jail.display()))
+ anyhow!(error).context(format!("re-executing under {}", ai_jail.display()))
}
#[cfg(not(unix))]
-fn reexec_under_ai_jail(ai_jail: &Path, jail_args: &[OsString]) -> Result<()> {
- let status = std::process::Command::new(ai_jail)
- .args(jail_args)
- .status()
- .with_context(|| format!("spawning {}", ai_jail.display()))?;
- std::process::exit(status.code().unwrap_or(1));
+fn reexec_under_ai_jail(ai_jail: &Path, jail_args: &[OsString]) -> anyhow::Error {
+ match std::process::Command::new(ai_jail).args(jail_args).status() {
+ Ok(status) => std::process::exit(status.code().unwrap_or(1)),
+ Err(error) => anyhow!(error).context(format!("spawning {}", ai_jail.display())),
+ }
}
/// The session this run can prove is its own: the one it launched or resumed,
@@ -2149,24 +2519,308 @@ mod tests {
use super::*;
use crate::cli::{Cli, Command as CliCommand};
+ fn plan(warn: bool, mode: JailMode) -> JailPlan {
+ JailPlan { warn, mode }
+ }
+
+ /// The full decision table: request × jailed × yolo × interactive ×
+ /// usable × project `.ai-jail`. `interactive` stands for "stdin and stderr
+ /// are both TTYs".
+ #[test]
+ fn jail_decision_table() {
+ use JailMode::{Explicit, Offer, Stay};
+ let unspecified = JailRequest::Unspecified;
+ let never = JailRequest::Never;
+ let defaults = JailRequest::Explicit(String::new());
+ let listed = JailRequest::Explicit("gpu,ssh".to_owned());
+ let requests = [&unspecified, &never, &defaults, &listed];
+
+ // Already inside ai-jail: nothing applies, not even an unusable --jail.
+ for request in requests {
+ for (yolo, interactive, usable, project) in [
+ (true, true, true, false),
+ (true, true, true, true),
+ (true, true, false, false),
+ (false, false, false, true),
+ (true, false, true, false),
+ ] {
+ assert_eq!(
+ jail_decision(request, true, yolo, interactive, usable, project).unwrap(),
+ plan(false, Stay),
+ "{request:?} inside the jail"
+ );
+ }
+ }
+
+ for project in [false, true] {
+ let decide = |request: &JailRequest, yolo, interactive, usable| {
+ jail_decision(request, false, yolo, interactive, usable, project).unwrap()
+ };
+ // Neither flag: the offer needs yolo, a TTY, and a usable ai-jail;
+ // the warning needs yolo and a TTY. A project `.ai-jail` replaces
+ // the checklist and nothing else.
+ assert_eq!(
+ decide(&unspecified, true, true, true),
+ plan(
+ true,
+ Offer {
+ checklist: !project
+ }
+ ),
+ "project .ai-jail = {project}"
+ );
+ assert_eq!(decide(&unspecified, true, true, false), plan(true, Stay));
+ assert_eq!(decide(&unspecified, true, false, true), plan(false, Stay));
+ assert_eq!(decide(&unspecified, false, true, true), plan(false, Stay));
+
+ // --no-jail: never jail, but the --yolo warning still shows.
+ assert_eq!(decide(&never, true, true, true), plan(true, Stay));
+ assert_eq!(decide(&never, true, false, true), plan(false, Stay));
+ assert_eq!(decide(&never, false, true, true), plan(false, Stay));
+
+ // --jail / --jail=LIST: re-exec without the question, with or
+ // without --yolo, interactive or not; the warning still shows for
+ // yolo + TTY. (What a project file does to the toggles is
+ // `jail_checklist`'s job: nothing pre-checked.)
+ for (request, list) in [(&defaults, ""), (&listed, "gpu,ssh")] {
+ let explicit = || Explicit(list.to_owned());
+ assert_eq!(decide(request, true, true, true), plan(true, explicit()));
+ assert_eq!(decide(request, true, false, true), plan(false, explicit()));
+ assert_eq!(decide(request, false, true, true), plan(false, explicit()));
+ assert_eq!(decide(request, false, false, true), plan(false, explicit()));
+ for (yolo, interactive) in [(true, true), (false, false)] {
+ let error = jail_decision(request, false, yolo, interactive, false, project)
+ .unwrap_err();
+ assert!(
+ error.to_string().contains("ai-jail is not usable"),
+ "an unusable ai-jail must fail, never run unjailed: {error}"
+ );
+ }
+ }
+ }
+ }
+
#[test]
- fn should_prompt_yolo_requires_yolo_and_both_ttys_and_not_jailed() {
- assert!(should_prompt_yolo(true, true, true, false));
+ fn jail_request_merges_leading_and_trailing_flags() {
+ let none = TrailingJail::default();
+ assert_eq!(
+ jail_request(None, false, none.clone()).unwrap(),
+ JailRequest::Unspecified
+ );
+ assert_eq!(
+ jail_request(None, true, none.clone()).unwrap(),
+ JailRequest::Never
+ );
+ assert_eq!(
+ jail_request(Some(String::new()), false, none.clone()).unwrap(),
+ JailRequest::Explicit(String::new())
+ );
+ let trailing = TrailingJail {
+ jail: Some("gpu".to_owned()),
+ no_jail: false,
+ };
+ assert_eq!(
+ jail_request(Some("aws".to_owned()), false, trailing.clone()).unwrap(),
+ JailRequest::Explicit("gpu".to_owned()),
+ "the later (trailing) --jail wins"
+ );
+ assert!(jail_request(None, true, trailing).is_err());
+ let trailing_no = TrailingJail {
+ jail: None,
+ no_jail: true,
+ };
+ let error = jail_request(Some(String::new()), false, trailing_no).unwrap_err();
+ assert!(error.to_string().contains("cannot be used together"));
+ }
+
+ fn parse_run(argv: &[&str]) -> RunArgs {
+ let CliCommand::Run(args) = Cli::try_parse_from(argv).unwrap().command else {
+ panic!("expected run command");
+ };
+ args
+ }
+
+ /// Bare `--jail` must not eat the harness name, and every spelling must
+ /// be a wrapper flag whether clap sees it (before the harness) or it lands
+ /// in `native_args` (after a native argument) — never reaching the harness.
+ #[test]
+ fn jail_flags_are_wrapper_flags_in_either_position() {
+ let bare = parse_run(&["ai-memory", "run", "--jail", "claude"]);
+ assert_eq!(bare.jail.as_deref(), Some(""));
+ assert!(matches!(bare.harness, Some(RunHarnessChoice::Claude)));
+ assert!(bare.native_args.is_empty());
+
+ let listed = parse_run(&["ai-memory", "run", "--jail=gpu,ssh", "claude"]);
+ assert_eq!(listed.jail.as_deref(), Some("gpu,ssh"));
+ assert!(matches!(listed.harness, Some(RunHarnessChoice::Claude)));
+
+ let never = parse_run(&["ai-memory", "run", "--no-jail", "claude"]);
+ assert!(never.no_jail && never.jail.is_none());
+
assert!(
- !should_prompt_yolo(false, true, true, false),
- "no prompt when --yolo was not requested"
+ Cli::try_parse_from(["ai-memory", "run", "--jail", "--no-jail", "claude"]).is_err(),
+ "clap rejects both flags together"
);
+
+ let swallowed = parse_run(&[
+ "ai-memory",
+ "run",
+ "claude",
+ "--model",
+ "opus",
+ "--jail=github,no-mise",
+ "--worktree",
+ ]);
assert!(
- !should_prompt_yolo(true, false, true, false),
- "no prompt when stdin is not a TTY"
+ swallowed.jail.is_none(),
+ "clap leaves it in the native argv"
+ );
+ let mut native = swallowed.native_args;
+ assert_eq!(
+ remove_wrapper_jail(&mut native),
+ TrailingJail {
+ jail: Some("github,no-mise".to_owned()),
+ no_jail: false
+ }
+ );
+ assert_eq!(
+ native,
+ ["--model", "opus", "--worktree"].map(OsString::from),
+ "only the wrapper flag is stripped; the harness's own --worktree stays"
);
+
+ for (flag, expected) in [
+ (
+ "--jail",
+ TrailingJail {
+ jail: Some(String::new()),
+ no_jail: false,
+ },
+ ),
+ (
+ "--jail=",
+ TrailingJail {
+ jail: Some(String::new()),
+ no_jail: false,
+ },
+ ),
+ (
+ "--no-jail",
+ TrailingJail {
+ jail: None,
+ no_jail: true,
+ },
+ ),
+ ] {
+ let mut native =
+ parse_run(&["ai-memory", "run", "claude", "--model", "opus", flag]).native_args;
+ assert_eq!(remove_wrapper_jail(&mut native), expected, "{flag}");
+ assert_eq!(native, ["--model", "opus"].map(OsString::from), "{flag}");
+ }
+ }
+
+ fn checklist_items() -> Vec<JailChecklistItem> {
+ ["github", "aws", "ssh", "docker"]
+ .into_iter()
+ .map(|stem| JailChecklistItem {
+ toggle: jail_toggle(stem).unwrap(),
+ checked: matches!(stem, "github" | "aws"),
+ })
+ .collect()
+ }
+
+ fn run_checklist(input: &str) -> (io::Result<Vec<String>>, String) {
+ let mut output = Vec::new();
+ let result = read_jail_checklist(
+ &checklist_items(),
+ &mut Cursor::new(input.as_bytes().to_vec()),
+ &mut output,
+ )
+ .map(|choices| choices.iter().map(JailToggleChoice::flag).collect());
+ (result, String::from_utf8(output).unwrap())
+ }
+
+ #[test]
+ fn checklist_enter_and_eof_accept_the_smart_defaults() {
+ let (enter, printed) = run_checklist("\n");
+ assert_eq!(enter.unwrap(), ["--github", "--aws"]);
+ assert!(printed.contains("Enable in the jail (Enter = as marked"));
+ assert!(printed.contains("[x] 1) GitHub CLI credentials"));
+ assert!(printed.contains("[x] 2) AWS credentials"));
+ assert!(printed.contains("[ ] 3) SSH keys + agent"));
+ assert!(printed.contains("[ ] 4) Docker socket"));
+ assert!(printed.contains("⚠ grants host root"));
+ let (eof, _) = run_checklist("");
+ assert_eq!(eof.unwrap(), ["--github", "--aws"]);
+ }
+
+ #[test]
+ fn checklist_numbers_flip_rows_and_all_none_set_every_row() {
+ let (flipped, printed) = run_checklist("2 4\n\n");
+ assert_eq!(flipped.unwrap(), ["--github", "--docker"]);
assert!(
- !should_prompt_yolo(true, true, false, false),
- "no prompt when stderr is not a TTY"
+ printed.contains("[ ] 2) AWS credentials") && printed.contains("[x] 4) Docker socket"),
+ "the list is shown again after a flip:\n{printed}"
+ );
+ let (commas, _) = run_checklist("1,3\n\n");
+ assert_eq!(commas.unwrap(), ["--aws", "--ssh"]);
+ let (all, _) = run_checklist("all\n\n");
+ assert_eq!(all.unwrap(), ["--github", "--aws", "--ssh", "--docker"]);
+ let (none, _) = run_checklist("NONE\n\n");
+ assert_eq!(none.unwrap(), Vec::<String>::new());
+ let (none_then_one, _) = run_checklist("none\n3\n");
+ assert_eq!(none_then_one.unwrap(), ["--ssh"]);
+ }
+
+ #[test]
+ fn checklist_reprompts_on_invalid_input_and_gives_up_after_a_bound() {
+ let (recovered, printed) = run_checklist("9\nyes\n2\n\n");
+ assert_eq!(
+ recovered.unwrap(),
+ ["--github"],
+ "invalid lines change nothing; the later valid flip applies"
);
+ assert!(printed.contains("`9` is not a row number between 1 and 4"));
+ assert!(printed.contains("`yes` is not a row number"));
+ // `2 9` is rejected whole: row 2 must not flip.
+ let (partial, _) = run_checklist("2 9\n\n");
+ assert_eq!(partial.unwrap(), ["--github", "--aws"]);
+
+ let (gave_up, _) = run_checklist("x\nx\nx\n\n");
assert!(
- !should_prompt_yolo(true, true, true, true),
- "no prompt when already inside ai-jail"
+ gave_up.is_err(),
+ "repeated garbage aborts rather than guessing what to mount"
+ );
+ }
+
+ #[test]
+ fn jail_summary_groups_credentials_capabilities_and_forced_off() {
+ let choice = |stem, enable| JailToggleChoice { stem, enable };
+ assert_eq!(
+ jail_summary(
+ &[
+ choice("github", true),
+ choice("gpu", true),
+ choice("ssh", true),
+ choice("mise", false),
+ ],
+ false
+ ),
+ "ai-memory: re-running inside ai-jail (credentials: GitHub CLI credentials, \
+ SSH keys + agent; capabilities: GPU devices; forced off: --no-mise)"
+ );
+ assert_eq!(
+ jail_summary(&[], false),
+ "ai-memory: re-running inside ai-jail with no extra mounts"
+ );
+ assert_eq!(
+ jail_summary(&[], true),
+ "ai-memory: re-running inside ai-jail (plus the project .ai-jail)"
+ );
+ assert_eq!(
+ jail_summary(&[choice("gpu", true)], true),
+ "ai-memory: re-running inside ai-jail (capabilities: GPU devices; plus the \
+ project .ai-jail)"
);
}
@@ -3414,6 +4068,8 @@ mod tests {
executable: Some(script.clone()),
yolo: false,
true_yolo: false,
+ jail: None,
+ no_jail: false,
fresh: false,
no_autowire: true,
env: vec![("CLAUDE_CONFIG_DIR".to_string(), "/from/cli".to_string())],
@@ -3900,6 +4556,8 @@ mod tests {
executable: Some(script.clone()),
yolo: false,
true_yolo: false,
+ jail: None,
+ no_jail: false,
fresh: false,
no_autowire: false,
env: Vec::new(),
@@ -4053,6 +4711,8 @@ mod tests {
executable: Some(executable),
yolo: false,
true_yolo: false,
+ jail: None,
+ no_jail: 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 9fd9fa82..e64b664b 100644
--- a/crates/ai-memory-cli/src/commands/show.rs
+++ b/crates/ai-memory-cli/src/commands/show.rs
@@ -226,6 +226,8 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {
executable: None,
yolo: args.yolo,
true_yolo: args.true_yolo,
+ jail: None,
+ no_jail: false,
fresh: args.fresh,
no_autowire: false,
env: Vec::new(),
diff --git a/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs b/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs
new file mode 100644
index 00000000..d8378546
--- /dev/null
+++ b/crates/ai-memory-cli/tests/suite/jail_toggles_e2e.rs
@@ -0,0 +1,698 @@
+//! End-to-end coverage for `ai-memory run --jail[=…]` / `--no-jail` through
+//! the built binary (docs/design-yolo-safety-ai-jail.md §5).
+//!
+//! Each test puts fake `ai-jail`, `bwrap`, and `claude` executables on a temp
+//! `PATH`, runs the real `ai-memory run` in a temp git repository with a temp
+//! `HOME`, and points it at a local mock server that records every request.
+//! The fake `ai-jail` answers `--help` with a chosen help text (so support
+//! detection sees either a 2.4.1- or a 2.5.0-style binary) and otherwise
+//! writes its argv, one argument per line, to a file — the exact invocation
+//! `ai-memory` exec'd. Unix-only: the fakes are shebang scripts and the
+//! re-exec is a real `exec`.
+
+#![cfg(unix)]
+
+use std::fs;
+use std::os::unix::fs::PermissionsExt as _;
+use std::path::{Path, PathBuf};
+use std::process::{Output, Stdio};
+use std::sync::{Arc, Mutex};
+
+use ai_memory_workstream::inside_ai_jail_here;
+use axum::{Json, Router, http::StatusCode, routing::post};
+use serde_json::json;
+
+const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");
+
+/// Toggle lines of ai-jail 2.4.1's `--help`: no credential mounts.
+const HELP_2_4_1: &str = "\
+ --no-gpu / --gpu Disable/enable GPU device passthrough (Linux only)
+ --no-docker / --docker Disable/enable Docker socket passthrough (grants host root; default: off)
+ --tailscale / --no-tailscale Enable/disable Tailscale socket passthrough (default: off)
+ --no-display / --display Disable/enable X11/Wayland passthrough (Linux only)
+ --network / --no-network Enable/disable unrestricted network access (default: off)
+ --agent-state / --no-agent-state
+ --save-config / --no-save-config
+ --worktree / --no-worktree Enable/disable linked Git worktree metadata passthrough
+ --no-mise / --mise Disable/enable mise integration
+ --ssh / --no-ssh Share ~/.ssh read-only + forward SSH_AUTH_SOCK (default: off)
+ --pictures / --no-pictures Share ~/Pictures read-only (default: off)
+";
+
+/// What ai-jail 2.5.0 adds.
+const HELP_2_5_0_EXTRA: &str = "\
+ --github / --no-github Enable/disable read-only ~/.config/gh mount
+ --aws / --no-aws Enable/disable read-only ~/.aws mount
+ --kube / --no-kube Enable/disable read-only ~/.kube mount
+ --gcloud / --no-gcloud Enable/disable read-only ~/.config/gcloud
+ --docker-config / --no-docker-config
+ --no-toolchains / --toolchains Disable/enable dev-toolchain cache
+";
+
+struct Fixture {
+ _temp: tempfile::TempDir,
+ repo: PathBuf,
+ home: PathBuf,
+ bin: PathBuf,
+ jail_argv: PathBuf,
+ claude_ran: PathBuf,
+}
+
+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"))
+}
+
+fn git(repo: &Path, args: &[&str]) {
+ let status = std::process::Command::new("git")
+ .arg("-C")
+ .arg(repo)
+ .args(args)
+ .stdout(Stdio::null())
+ .status()
+ .unwrap();
+ assert!(status.success(), "git {args:?}");
+}
+
+impl Fixture {
+ /// `help` is what the fake `ai-jail --help` prints; `with_bwrap` decides
+ /// whether ai-jail counts as usable; `origin` is the repo's remote.
+ fn new(help: &str, with_bwrap: bool, origin: Option<&str>) -> 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();
+ }
+ git(&repo, &["init", "-q"]);
+ if let Some(origin) = origin {
+ git(&repo, &["remote", "add", "origin", origin]);
+ }
+ let help_file = root.join("ai-jail-help.txt");
+ fs::write(&help_file, help).unwrap();
+ let jail_argv = root.join("ai-jail-argv.txt");
+ let claude_ran = root.join("claude-ran.txt");
+ write_script(
+ &bin.join("ai-jail"),
+ &format!(
+ "if [ \"$1\" = --help ]; then cat '{}'; exit 0; fi\nprintf '%s\\n' \"$@\" > '{}'\n",
+ help_file.display(),
+ jail_argv.display()
+ ),
+ );
+ if with_bwrap {
+ write_script(&bin.join("bwrap"), "exit 0\n");
+ }
+ // `PATH` is this directory alone, so a host `bwrap` cannot make
+ // ai-jail usable behind the test's back; link in the two host tools
+ // the run itself needs.
+ for tool in ["git", "cat"] {
+ std::os::unix::fs::symlink(host_tool(tool), bin.join(tool)).unwrap();
+ }
+ // The fake harness also writes the (empty-session) transcript the
+ // launcher waits for, so an unjailed run finishes at once instead of
+ // waiting out the transcript-flush poll.
+ 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}'\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\n\
+ shift\n\
+ done\n",
+ ran = claude_ran.display(),
+ repo = repo.display(),
+ dir = transcripts.display(),
+ ),
+ );
+ Self {
+ _temp: temp,
+ repo,
+ home,
+ bin,
+ jail_argv,
+ claude_ran,
+ }
+ }
+
+ fn jail_argv(&self) -> Option<Vec<String>> {
+ fs::read_to_string(&self.jail_argv)
+ .ok()
+ .map(|text| text.lines().map(str::to_owned).collect())
+ }
+}
+
+/// A mock ai-memory server: `POST /workstream/runs` opens a run, `…/finish`
+/// acknowledges it, everything else answers 204. Every request path is
+/// recorded.
+async fn mock_server() -> (String, Arc<Mutex<Vec<String>>>, tokio::task::JoinHandle<()>) {
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let observed = requests.clone();
+ let app = Router::new().fallback(post(move |uri: axum::http::Uri| {
+ let observed = observed.clone();
+ async move {
+ observed.lock().unwrap().push(uri.path().to_owned());
+ if uri.path() == "/workstream/runs" {
+ (
+ StatusCode::OK,
+ 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,
+ })),
+ )
+ } else if uri.path().ends_with("/finish") {
+ (
+ StatusCode::OK,
+ Json(json!({"imported_events": 0, "latest_sequence": 0})),
+ )
+ } else {
+ (StatusCode::NO_CONTENT, Json(json!(null)))
+ }
+ }
+ }));
+ 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() });
+ (format!("http://{address}"), requests, server)
+}
+
+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()
+}
+
+/// Split the recorded ai-jail argv at `--`: (sandbox flags, wrapped command).
+fn split_at_separator(argv: &[String]) -> (&[String], &[String]) {
+ let separator = argv
+ .iter()
+ .position(|arg| arg == "--")
+ .expect("`--` separates the sandbox flags from the wrapped command");
+ (&argv[..separator], &argv[separator + 1..])
+}
+
+/// The toggles in the sandbox flags: everything after the `--network
+/// --agent-state --no-save-config` baseline and its `--env NAME` pairs. The
+/// baseline is asserted on every exec: without `--no-save-config` ai-jail
+/// would write these flags into the repository's `.ai-jail`.
+fn toggles(flags: &[String]) -> Vec<String> {
+ assert_eq!(
+ &flags[..3],
+ ["--network", "--agent-state", "--no-save-config"],
+ "{flags:?}"
+ );
+ let mut rest = &flags[3..];
+ while rest.first().is_some_and(|flag| flag == "--env") {
+ rest = &rest[2..];
+ }
+ rest.to_vec()
+}
+
+fn exe() -> String {
+ Path::new(BIN)
+ .canonicalize()
+ .unwrap()
+ .to_string_lossy()
+ .into_owned()
+}
+
+/// A sandboxed test run would see itself as already jailed, where every jail
+/// flag is (correctly) ignored.
+fn skip_inside_ai_jail() -> bool {
+ let jailed = inside_ai_jail_here();
+ if jailed {
+ eprintln!("skipping: already inside ai-jail, where --jail is ignored by design");
+ }
+ jailed
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn jail_list_reexecs_under_ai_jail_with_exactly_the_listed_toggles() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let (server, requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &["run", "--no-autowire", "claude", "--jail=gpu,ssh"],
+ )
+ .await;
+ assert!(output.status.success(), "{}", stderr(&output));
+ let argv = fixture
+ .jail_argv()
+ .unwrap_or_else(|| panic!("ai-jail was never exec'd:\n{}", stderr(&output)));
+ let (flags, wrapped) = split_at_separator(&argv);
+ assert!(
+ flags
+ .windows(2)
+ .any(|pair| pair == ["--env", "AI_MEMORY_SERVER_URL"]),
+ "the server URL is forwarded into the jail: {flags:?}"
+ );
+ assert_eq!(toggles(flags), ["--gpu", "--ssh"]);
+ assert_eq!(
+ wrapped,
+ [
+ exe().as_str(),
+ "run",
+ "--no-autowire",
+ "claude",
+ "--jail=gpu,ssh"
+ ],
+ "the original invocation is wrapped verbatim after `--`"
+ );
+ assert!(
+ stderr(&output).contains("capabilities: GPU devices"),
+ "{}",
+ stderr(&output)
+ );
+ assert!(
+ !fixture.claude_ran.exists(),
+ "the harness never runs outside"
+ );
+ assert!(
+ requests.lock().unwrap().is_empty(),
+ "an explicit --jail re-execs before opening a managed run: {:?}",
+ requests.lock().unwrap()
+ );
+ handle.abort();
+}
+
+/// Bare `--jail` takes the smart defaults: credentials present in `$HOME`
+/// that the installed ai-jail supports, plus SSH for an SSH `origin`.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn bare_jail_uses_the_smart_defaults() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let help = format!("{HELP_2_4_1}{HELP_2_5_0_EXTRA}");
+ let fixture = Fixture::new(&help, true, Some("[email protected]:example/repo.git"));
+ for dir in [".aws", ".ssh"] {
+ fs::create_dir_all(fixture.home.join(dir)).unwrap();
+ }
+ let (server, requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &["run", "--jail", "--no-autowire", "claude"],
+ )
+ .await;
+ assert!(output.status.success(), "{}", stderr(&output));
+ let argv = fixture.jail_argv().expect("ai-jail exec'd");
+ let (flags, wrapped) = split_at_separator(&argv);
+ assert_eq!(
+ toggles(flags),
+ ["--aws", "--ssh"],
+ "absent credentials and opt-in capabilities stay off"
+ );
+ assert_eq!(wrapped[1..], ["run", "--jail", "--no-autowire", "claude"]);
+ assert!(requests.lock().unwrap().is_empty());
+ handle.abort();
+}
+
+/// A project `.ai-jail` that asks for dangerous things. Its contents are
+/// irrelevant to ai-memory (never read); ai-jail applies its own trust rules.
+const DANGEROUS_PROJECT_CONFIG: &str = "docker = true\ngithub = true\nagent_state = true\n";
+
+/// Bare `--jail` with a project `.ai-jail` defers to the file: none of the
+/// smart defaults this host would otherwise get (`--aws`, `--ssh`) and
+/// nothing the file asks for (`--docker`) is passed — only the baseline.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn bare_jail_with_a_project_ai_jail_passes_no_toggles() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let help = format!("{HELP_2_4_1}{HELP_2_5_0_EXTRA}");
+ let fixture = Fixture::new(&help, true, Some("[email protected]:example/repo.git"));
+ for dir in [".aws", ".ssh"] {
+ fs::create_dir_all(fixture.home.join(dir)).unwrap();
+ }
+ fs::write(fixture.repo.join(".ai-jail"), DANGEROUS_PROJECT_CONFIG).unwrap();
+ let (server, requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &["run", "--jail", "--no-autowire", "claude"],
+ )
+ .await;
+ assert!(output.status.success(), "{}", stderr(&output));
+ let argv = fixture.jail_argv().expect("ai-jail exec'd");
+ let (flags, wrapped) = split_at_separator(&argv);
+ assert_eq!(toggles(flags), Vec::<String>::new());
+ assert_eq!(
+ wrapped,
+ [exe().as_str(), "run", "--jail", "--no-autowire", "claude"]
+ );
+ assert!(
+ stderr(&output).contains("plus the project .ai-jail"),
+ "{}",
+ stderr(&output)
+ );
+ assert!(requests.lock().unwrap().is_empty());
+ handle.abort();
+}
+
+/// An explicit list still applies on top of a project `.ai-jail` (CLI flags
+/// override config in ai-jail).
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn jail_list_overrides_a_project_ai_jail() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ fs::write(fixture.repo.join(".ai-jail"), DANGEROUS_PROJECT_CONFIG).unwrap();
+ let (server, _requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &["run", "--jail=gpu,no-docker", "--no-autowire", "claude"],
+ )
+ .await;
+ assert!(output.status.success(), "{}", stderr(&output));
+ let argv = fixture.jail_argv().expect("ai-jail exec'd");
+ let (flags, _) = split_at_separator(&argv);
+ assert_eq!(toggles(flags), ["--gpu", "--no-docker"]);
+ handle.abort();
+}
+
+/// `--jail` must never fall back to an unjailed run: no sandbox backend means
+/// ai-jail is unusable, so the launch fails before anything starts.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn jail_fails_closed_when_ai_jail_is_not_usable() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, false, None);
+ let (server, requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &["run", "--jail", "--no-autowire", "claude"],
+ )
+ .await;
+ assert!(!output.status.success());
+ assert!(
+ stderr(&output).contains("ai-jail is not usable on this host"),
+ "{}",
+ stderr(&output)
+ );
+ assert!(fixture.jail_argv().is_none());
+ assert!(!fixture.claude_ran.exists(), "never runs unjailed");
+ assert!(requests.lock().unwrap().is_empty());
+ handle.abort();
+}
+
+/// A toggle the installed ai-jail lacks is an error naming the release that
+/// has it — never passed through for an older ai-jail to reject.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn jail_rejects_a_toggle_the_installed_ai_jail_lacks() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let (server, requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &["run", "--jail=gpu,github", "--no-autowire", "claude"],
+ )
+ .await;
+ assert!(!output.status.success());
+ assert!(
+ stderr(&output).contains("needs ai-jail 2.5.0 or newer"),
+ "{}",
+ stderr(&output)
+ );
+ assert!(fixture.jail_argv().is_none());
+ assert!(!fixture.claude_ran.exists());
+ assert!(requests.lock().unwrap().is_empty());
+
+ let reserved = run(
+ &fixture,
+ &server,
+ &["run", "--jail=no-seccomp", "--no-autowire", "claude"],
+ )
+ .await;
+ assert!(!reserved.status.success());
+ assert!(
+ stderr(&reserved).contains("not available through ai-memory; run ai-jail directly"),
+ "{}",
+ stderr(&reserved)
+ );
+ assert!(fixture.jail_argv().is_none());
+ handle.abort();
+}
+
+/// `--no-jail` runs the harness directly even where ai-jail is usable, and
+/// never hands the flag to the harness.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn no_jail_runs_the_harness_without_ai_jail() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let (server, requests, handle) = mock_server().await;
+ let output = run(
+ &fixture,
+ &server,
+ &[
+ "run",
+ "--no-autowire",
+ "claude",
+ "--model",
+ "opus",
+ "--no-jail",
+ ],
+ )
+ .await;
+ assert!(output.status.success(), "{}", stderr(&output));
+ assert!(
+ fixture.claude_ran.exists(),
+ "the harness ran:\n{}",
+ stderr(&output)
+ );
+ let harness_args = fs::read_to_string(&fixture.claude_ran).unwrap();
+ assert!(
+ !harness_args.contains("jail"),
+ "--no-jail is a wrapper flag: {harness_args}"
+ );
+ assert!(fixture.jail_argv().is_none(), "ai-jail must not be invoked");
+ assert_eq!(
+ requests.lock().unwrap().first().map(String::as_str),
+ Some("/workstream/runs"),
+ "the unjailed run opens its managed run as usual"
+ );
+ handle.abort();
+}
+
+/// With a real terminal, `--yolo --no-jail` still shows the warning but never
+/// the ai-jail offer. Without `--no-jail` the offer would read the closed
+/// stdin as its default "yes" and exec the fake ai-jail, so this bites.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn yolo_no_jail_warns_without_offering_ai_jail_on_a_terminal() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let (server, _requests, handle) = mock_server().await;
+ let output = terminal_run(
+ &fixture,
+ &server,
+ "run --no-autowire --yolo --no-jail claude",
+ "y\n",
+ )
+ .await;
+ assert!(
+ output.contains("--yolo runs every tool call"),
+ "the yolo warning still shows:\n{output}"
+ );
+ assert!(
+ !output.contains("ai-jail is installed"),
+ "--no-jail suppresses the offer:\n{output}"
+ );
+ assert!(fixture.jail_argv().is_none());
+ assert!(fixture.claude_ran.exists(), "{output}");
+ handle.abort();
+}
+
+/// The control for the test above: the same terminal run without `--no-jail`
+/// is offered ai-jail, takes the default yes, and (no checklist rows on an
+/// empty `$HOME` beyond the opt-in capabilities, accepted as marked) execs it.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn yolo_offer_then_checklist_execs_ai_jail_on_a_terminal() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ let (server, requests, handle) = mock_server().await;
+ let output = terminal_run(
+ &fixture,
+ &server,
+ "run --no-autowire --yolo claude",
+ "y\ny\n2\n\n",
+ )
+ .await;
+ assert!(output.contains("ai-jail is installed"), "{output}");
+ assert!(output.contains("Enable in the jail"), "{output}");
+ let argv = fixture
+ .jail_argv()
+ .unwrap_or_else(|| panic!("ai-jail exec'd:\n{output}"));
+ let (flags, _) = split_at_separator(&argv);
+ assert_eq!(
+ toggles(flags),
+ ["--gpu"],
+ "row 2 (GPU) was flipped on; the rest stay as marked"
+ );
+ assert!(!fixture.claude_ran.exists());
+ let requests = requests.lock().unwrap();
+ assert_eq!(
+ requests.as_slice(),
+ [
+ "/workstream/runs",
+ "/workstream/runs/12345678-1234-4234-9234-123456789abe/cancel"
+ ],
+ "accepting the offer cancels the prepared run before the re-exec"
+ );
+ handle.abort();
+}
+
+/// With a project `.ai-jail` the offer re-execs straight away: no checklist
+/// (a repository must not be able to steer it) and no toggles of ours, even
+/// though the file asks for `docker`. The input holds a "2" that would flip
+/// GPU on if a checklist were wrongly shown.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn yolo_offer_skips_the_checklist_for_a_project_ai_jail() {
+ if skip_inside_ai_jail() {
+ return;
+ }
+ let fixture = Fixture::new(HELP_2_4_1, true, None);
+ fs::write(fixture.repo.join(".ai-jail"), DANGEROUS_PROJECT_CONFIG).unwrap();
+ let (server, _requests, handle) = mock_server().await;
+ let output = terminal_run(
+ &fixture,
+ &server,
+ "run --no-autowire --yolo claude",
+ "y\ny\n2\n\n",
+ )
+ .await;
+ assert!(output.contains("ai-jail is installed"), "{output}");
+ assert!(
+ !output.contains("Enable in the jail"),
+ "no checklist with a project .ai-jail:\n{output}"
+ );
+ let argv = fixture
+ .jail_argv()
+ .unwrap_or_else(|| panic!("ai-jail exec'd:\n{output}"));
+ let (flags, _) = split_at_separator(&argv);
+ assert_eq!(toggles(flags), Vec::<String>::new(), "{output}");
+ assert!(!flags.iter().any(|flag| flag == "--docker"));
+ handle.abort();
+}
+
+/// Run `ai-memory <args>` under `script` so stdin and stderr are a real
+/// terminal, feed `input`, and return everything the terminal showed.
+#[cfg(any(target_os = "linux", target_os = "macos"))]
+async fn terminal_run(fixture: &Fixture, server: &str, args: &str, input: &str) -> String {
+ use tokio::io::AsyncWriteExt as _;
+ let runner = fixture.home.join("runner.sh");
+ fs::write(&runner, format!("exec \"$JAIL_E2E_BINARY\" {args}\n")).unwrap();
+ let mut command = command(fixture, server, &[]);
+ let script = PathBuf::from("/usr/bin/script");
+ let command = command.as_std_mut();
+ let mut terminal = std::process::Command::new(&script);
+ terminal.env_clear();
+ #[cfg(target_os = "macos")]
+ terminal.args(["-q", "/dev/null", "/bin/sh"]).arg(&runner);
+ #[cfg(target_os = "linux")]
+ terminal
+ .args(["-qec", "exec /bin/sh \"$JAIL_E2E_RUNNER\"", "/dev/null"])
+ .env("JAIL_E2E_RUNNER", &runner);
+ for (key, value) in command.get_envs() {
+ if let Some(value) = value {
+ terminal.env(key, value);
+ }
+ }
+ for key in ["TERM", "USER", "LOGNAME"] {
+ if let Some(value) = std::env::var_os(key) {
+ terminal.env(key, value);
+ }
+ }
+ terminal
+ .env("HOME", &fixture.home)
+ .env("JAIL_E2E_BINARY", BIN)
+ .current_dir(&fixture.repo)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ let mut child = tokio::process::Command::from(terminal)
+ .spawn()
+ .expect("script provides a pseudo-terminal");
+ let mut stdin = child.stdin.take().unwrap();
+ stdin.write_all(input.as_bytes()).await.unwrap();
+ stdin.flush().await.unwrap();
+ // Keep stdin open briefly so `script` forwards the lines before EOF.
+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;
+ drop(stdin);
+ let output = tokio::time::timeout(std::time::Duration::from_secs(30), child.wait_with_output())
+ .await
+ .expect("terminal run finished")
+ .expect("wait for script");
+ format!(
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ )
+}
diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rs
index 88974be6..c422f05b 100644
--- a/crates/ai-memory-cli/tests/suite/main.rs
+++ b/crates/ai-memory-cli/tests/suite/main.rs
@@ -17,6 +17,7 @@ mod external_capture_powershell;
mod external_capture_ts;
mod hook_drain;
mod hook_payload;
+mod jail_toggles_e2e;
mod marker_scope;
mod message_e2e;
mod packaging;
diff --git a/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs b/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs
index ae047170..43ce97e4 100644
--- a/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs
+++ b/crates/ai-memory-cli/tests/suite/yolo_ai_jail.rs
@@ -12,7 +12,10 @@ use std::ffi::OsString;
use std::path::Path;
use std::process::Command;
-use ai_memory_workstream::{build_ai_jail_invocation, usable_ai_jail_here};
+use ai_memory_workstream::{
+ JAIL_TOGGLES, JailToggleChoice, ai_jail_support, build_ai_jail_invocation, parse_jail_toggles,
+ usable_ai_jail_here,
+};
fn forwarded() -> Vec<OsString> {
["run", "claude", "--yolo"]
@@ -35,6 +38,8 @@ fn invocation_puts_all_sandbox_flags_before_the_wrapped_exe() {
&forwarded(),
&["AI_MEMORY_SERVER_URL", "ANTHROPIC_API_KEY"],
true,
+ true,
+ &[],
);
let strs: Vec<String> = argv
.iter()
@@ -76,7 +81,8 @@ fn invocation_puts_all_sandbox_flags_before_the_wrapped_exe() {
#[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 argv =
+ build_ai_jail_invocation(exe, &forwarded(), &["CLAUDE_CONFIG_DIR"], false, false, &[]);
let strs: Vec<String> = argv
.iter()
.map(|a| a.to_string_lossy().into_owned())
@@ -97,13 +103,26 @@ fn invocation_emits_one_bare_env_flag_per_present_name() {
/// executing it) over the argv built for `forwarded`, wrapping this test binary
/// so any failure is about the argv shape rather than an unresolvable command.
/// `None` ⇒ the feature would not offer ai-jail on this host, so skip.
-fn real_dry_run(forwarded: &[OsString]) -> Option<(std::process::Output, String, String)> {
+fn real_dry_run(
+ forwarded: &[OsString],
+ toggles: &[JailToggleChoice],
+) -> Option<(std::process::Output, String, String)> {
let Some(ai_jail) = usable_ai_jail_here() else {
eprintln!("skipping: ai-jail is not usable here (absent, no sandbox backend, or Windows)");
return None;
};
let exe = std::env::current_exe().expect("test binary path");
- let argv = build_ai_jail_invocation(&exe, forwarded, &["AI_MEMORY_SERVER_URL"], true);
+ let no_save_config = ai_jail_support(&ai_jail)
+ .expect("ai-jail --help")
+ .supports("no-save-config");
+ let argv = build_ai_jail_invocation(
+ &exe,
+ forwarded,
+ &["AI_MEMORY_SERVER_URL"],
+ true,
+ no_save_config,
+ toggles,
+ );
let output = Command::new(&ai_jail)
.arg("--dry-run")
.args(&argv)
@@ -123,7 +142,7 @@ fn real_dry_run(forwarded: &[OsString]) -> Option<(std::process::Output, String,
/// exe — fails here.
#[test]
fn real_ai_jail_dry_run_accepts_and_forwards_the_invocation() {
- let Some((output, combined, exe)) = real_dry_run(&forwarded()) else {
+ let Some((output, combined, exe)) = real_dry_run(&forwarded(), &[]) else {
return;
};
assert!(
@@ -181,7 +200,7 @@ fn real_ai_jail_dry_run_forwards_child_flags_that_collide_with_its_own() {
.into_iter()
.map(OsString::from)
.collect();
- let Some((output, combined, _)) = real_dry_run(&forwarded) else {
+ let Some((output, combined, _)) = real_dry_run(&forwarded, &[]) else {
return;
};
assert!(
@@ -193,3 +212,69 @@ fn real_ai_jail_dry_run_forwards_child_flags_that_collide_with_its_own() {
"the child's --env value must be forwarded verbatim; plan was:\n{combined}"
);
}
+
+/// Every toggle the installed ai-jail advertises in its real `--help`, parsed
+/// through `--jail=…`'s own parser: on 2.4.1 that exercises `--ssh`, `--gpu`,
+/// `--docker`, …; on 2.5.0+ the credential mounts and `--toolchains` too.
+/// The real ai-jail must accept the whole invocation with every one of them
+/// placed before the `--`.
+#[test]
+fn real_ai_jail_dry_run_accepts_every_supported_toggle() {
+ let Some(ai_jail) = usable_ai_jail_here() else {
+ eprintln!("skipping: ai-jail is not usable here (absent, no sandbox backend, or Windows)");
+ return;
+ };
+ let support = ai_jail_support(&ai_jail).expect("ai-jail --help");
+ let supported: Vec<&str> = JAIL_TOGGLES
+ .iter()
+ .map(|toggle| toggle.stem)
+ .filter(|stem| support.supports(stem))
+ .collect();
+ assert!(
+ supported.contains(&"ssh")
+ && supported.contains(&"gpu")
+ && support.supports("no-save-config"),
+ "every ai-jail since 2.4.1 advertises --ssh, --gpu and --no-save-config: {supported:?}"
+ );
+ let toggles = parse_jail_toggles(&supported.join(","), &[], &support)
+ .expect("every advertised toggle parses");
+ assert_eq!(toggles.len(), supported.len());
+ let Some((output, combined, exe)) = real_dry_run(&forwarded(), &toggles) else {
+ return;
+ };
+ assert!(
+ output.status.success(),
+ "ai-jail --dry-run rejected the toggles {supported:?}:\n{combined}"
+ );
+ assert!(combined.contains(&exe), "plan was:\n{combined}");
+
+ // And the forced-off spelling of each is accepted too.
+ let negated: Vec<String> = supported.iter().map(|stem| format!("no-{stem}")).collect();
+ let toggles = parse_jail_toggles(&negated.join(","), &[], &support).unwrap();
+ let Some((output, combined, _)) = real_dry_run(&forwarded(), &toggles) else {
+ return;
+ };
+ assert!(
+ output.status.success(),
+ "ai-jail --dry-run rejected the negated toggles:\n{combined}"
+ );
+}
+
+/// Why support detection is load-bearing: the real ai-jail rejects a flag it
+/// does not know, so passing a 2.5.0 credential flag to an older ai-jail would
+/// abort the launch instead of being ignored.
+#[test]
+fn real_ai_jail_rejects_an_unknown_toggle() {
+ let Some(ai_jail) = usable_ai_jail_here() else {
+ eprintln!("skipping: ai-jail is not usable here (absent, no sandbox backend, or Windows)");
+ return;
+ };
+ let output = Command::new(&ai_jail)
+ .args(["--dry-run", "--ai-memory-not-a-toggle", "--", "/bin/true"])
+ .output()
+ .expect("run ai-jail --dry-run");
+ assert!(
+ !output.status.success(),
+ "ai-jail accepted an unknown flag; support detection would be moot"
+ );
+}
diff --git a/crates/ai-memory-workstream/src/jail.rs b/crates/ai-memory-workstream/src/jail.rs
index 740e84f4..72e7af44 100644
--- a/crates/ai-memory-workstream/src/jail.rs
+++ b/crates/ai-memory-workstream/src/jail.rs
@@ -174,10 +174,553 @@ fn read_linux_hostname() -> Option<String> {
.map(|value| value.trim().to_string())
}
+/// Whether a toggle mounts a credential the agent can then use, or grants a
+/// host capability.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum JailToggleKind {
+ /// Mounts secrets (read-only) into the jail.
+ Credential,
+ /// Exposes a host device, socket, or directory.
+ Capability,
+}
+
+/// How a toggle's checklist visibility and smart default are computed
+/// (docs/design-yolo-safety-ai-jail.md §5).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ToggleRule {
+ /// Shown, and pre-checked, only when this path under `$HOME` exists —
+ /// the exact path ai-jail mounts, so a checked box always mounts something.
+ CredentialAt(&'static str),
+ /// Shown when `~/.ssh` exists or an agent socket is set; pre-checked only
+ /// for an SSH-style `origin`, the one case `git push` needs it.
+ Ssh,
+ /// Shown unchecked; `linux_only` hides it where ai-jail ignores it.
+ OptIn { linux_only: bool },
+ /// Shown, pre-checked, only in a linked worktree: without its metadata
+ /// mounted writable the agent cannot commit there.
+ LinkedWorktree,
+ /// Accepted from `--jail=…`, never shown in the checklist.
+ CliOnly,
+}
+
+/// One ai-jail `--<stem>` / `--no-<stem>` toggle ai-memory can pass through.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct JailToggle {
+ /// The ai-jail flag without its dashes, e.g. `docker-config`.
+ pub stem: &'static str,
+ /// Short checklist label.
+ pub label: &'static str,
+ /// One-line checklist note.
+ pub note: &'static str,
+ /// Credential or capability.
+ pub kind: JailToggleKind,
+ /// An ai-jail release known to accept the flag, named when the installed
+ /// one does not.
+ pub since: &'static str,
+ rule: ToggleRule,
+}
+
+impl JailToggle {
+ /// Whether the interactive checklist can show this toggle at all.
+ #[must_use]
+ pub const fn in_checklist(&self) -> bool {
+ !matches!(self.rule, ToggleRule::CliOnly)
+ }
+}
+
+/// First ai-jail release with the credential mounts and `--toolchains`.
+const CREDENTIAL_MOUNTS_SINCE: &str = "2.5.0";
+/// Oldest release this table was verified against; the remaining toggles all
+/// exist there.
+const BASE_TOGGLES_SINCE: &str = "2.4.1";
+
+const fn toggle(
+ stem: &'static str,
+ label: &'static str,
+ note: &'static str,
+ kind: JailToggleKind,
+ since: &'static str,
+ rule: ToggleRule,
+) -> JailToggle {
+ JailToggle {
+ stem,
+ label,
+ note,
+ kind,
+ since,
+ rule,
+ }
+}
+
+/// Every ai-jail toggle `ai-memory run --jail` accepts, in checklist order.
+pub const JAIL_TOGGLES: &[JailToggle] = {
+ use JailToggleKind::{Capability, Credential};
+ use ToggleRule::{CliOnly, CredentialAt, LinkedWorktree, OptIn, Ssh};
+ const CRED: &str = CREDENTIAL_MOUNTS_SINCE;
+ const BASE: &str = BASE_TOGGLES_SINCE;
+ &[
+ toggle(
+ "github",
+ "GitHub CLI credentials",
+ "~/.config/gh, read-only",
+ Credential,
+ CRED,
+ CredentialAt(".config/gh"),
+ ),
+ toggle(
+ "aws",
+ "AWS credentials",
+ "~/.aws, read-only",
+ Credential,
+ CRED,
+ CredentialAt(".aws"),
+ ),
+ toggle(
+ "kube",
+ "Kubernetes credentials",
+ "~/.kube, read-only",
+ Credential,
+ CRED,
+ CredentialAt(".kube"),
+ ),
+ toggle(
+ "gcloud",
+ "Google Cloud credentials",
+ "~/.config/gcloud, read-only",
+ Credential,
+ CRED,
+ CredentialAt(".config/gcloud"),
+ ),
+ toggle(
+ "docker-config",
+ "Docker registry credentials",
+ "~/.docker/config.json, read-only",
+ Credential,
+ CRED,
+ CredentialAt(".docker/config.json"),
+ ),
+ toggle(
+ "ssh",
+ "SSH keys + agent",
+ "~/.ssh read-only + SSH_AUTH_SOCK; needed for git over SSH",
+ Credential,
+ BASE,
+ Ssh,
+ ),
+ toggle(
+ "worktree",
+ "Linked worktree metadata",
+ "writable, so the agent can commit here",
+ Capability,
+ BASE,
+ LinkedWorktree,
+ ),
+ toggle(
+ "docker",
+ "Docker socket",
+ "⚠ grants host root",
+ Capability,
+ BASE,
+ OptIn { linux_only: false },
+ ),
+ toggle(
+ "gpu",
+ "GPU devices",
+ "/dev/dri, /dev/nvidia*",
+ Capability,
+ BASE,
+ OptIn { linux_only: true },
+ ),
+ toggle(
+ "display",
+ "X11/Wayland display",
+ "GUI apps and the clipboard",
+ Capability,
+ BASE,
+ OptIn { linux_only: true },
+ ),
+ toggle(
+ "pictures",
+ "Pictures folder",
+ "~/Pictures, read-only",
+ Capability,
+ BASE,
+ OptIn { linux_only: false },
+ ),
+ toggle(
+ "tailscale",
+ "Tailscale socket",
+ "reach your tailnet",
+ Capability,
+ BASE,
+ OptIn { linux_only: false },
+ ),
+ toggle("audio", "Host audio", "", Capability, BASE, CliOnly),
+ toggle("x11", "X11 socket", "", Capability, BASE, CliOnly),
+ toggle(
+ "host-shm",
+ "Host shared memory",
+ "",
+ Capability,
+ BASE,
+ CliOnly,
+ ),
+ toggle(
+ "terminal-passthrough",
+ "Terminal passthrough",
+ "",
+ Capability,
+ BASE,
+ CliOnly,
+ ),
+ toggle(
+ "update-check",
+ "Update check",
+ "",
+ Capability,
+ BASE,
+ CliOnly,
+ ),
+ toggle("mise", "mise integration", "", Capability, BASE, CliOnly),
+ toggle(
+ "toolchains",
+ "Toolchain caches",
+ "",
+ Capability,
+ CRED,
+ CliOnly,
+ ),
+ ]
+};
+
+/// The table entry for `stem`.
+#[must_use]
+pub fn jail_toggle(stem: &str) -> Option<&'static JailToggle> {
+ JAIL_TOGGLES.iter().find(|toggle| toggle.stem == stem)
+}
+
+/// ai-jail switches `--jail=…` refuses: each weakens the sandbox itself
+/// (`private-home`, `lockdown`, `landlock`, `seccomp`, `rlimits`,
+/// `systemd-user`, `inherit-env`, `macos-host-ipc`, `browser`, the audit
+/// log) or is set by ai-memory (`network`, `agent-state`, `save-config`). Whoever needs one
+/// runs ai-jail directly.
+const RESERVED_JAIL_FLAGS: &[&str] = &[
+ "private-home",
+ "lockdown",
+ "landlock",
+ "seccomp",
+ "rlimits",
+ "systemd-user",
+ "inherit-env",
+ "macos-host-ipc",
+ "network",
+ "agent-state",
+ "browser",
+ "audit-log",
+ "audit-show",
+ "audit-verify",
+ "save-config",
+];
+
+/// The flags the installed ai-jail advertises in its `--help`.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct JailSupport {
+ flags: std::collections::BTreeSet<String>,
+}
+
+impl JailSupport {
+ /// Collect every `--flag` token from ai-jail's help text. Tokens split on
+ /// whitespace and `/` (ai-jail prints `--ssh / --no-ssh`) and compare
+ /// exactly, so `--docker-config` never counts as `--docker` or back.
+ #[must_use]
+ pub fn from_help(help: &str) -> Self {
+ let flags = help
+ .split(|c: char| c.is_whitespace() || c == '/')
+ .filter(|token| token.starts_with("--") && token.len() > 2)
+ .map(str::to_owned)
+ .collect();
+ Self { flags }
+ }
+
+ /// Whether the installed ai-jail accepts `--<stem>`.
+ #[must_use]
+ pub fn supports(&self, stem: &str) -> bool {
+ self.flags.contains(&format!("--{stem}"))
+ }
+}
+
+/// Run `<ai_jail> --help` once and read which toggles it accepts. An older
+/// ai-jail rejects an unknown flag outright, so ai-memory only ever passes
+/// flags listed here.
+pub fn ai_jail_support(ai_jail: &Path) -> std::io::Result<JailSupport> {
+ let output = std::process::Command::new(ai_jail)
+ .arg("--help")
+ .stdin(std::process::Stdio::null())
+ .output()?;
+ let mut help = String::from_utf8_lossy(&output.stdout).into_owned();
+ help.push('\n');
+ help.push_str(&String::from_utf8_lossy(&output.stderr));
+ Ok(JailSupport::from_help(&help))
+}
+
+/// Host facts the toggle defaults read, injected so they are unit-testable
+/// without the real home directory, environment, or repository.
+#[derive(Debug, Clone)]
+pub struct JailHostFacts {
+ /// Host OS; Linux-only toggles are hidden elsewhere.
+ pub os: JailOs,
+ /// `$HOME` as ai-jail sees it (the credential mounts are relative to it).
+ pub home: Option<PathBuf>,
+ /// Whether `SSH_AUTH_SOCK` is set.
+ pub ssh_agent: bool,
+ /// The repository's `origin` URL.
+ pub origin_url: Option<String>,
+ /// Whether the cwd is a linked git worktree.
+ pub linked_worktree: bool,
+ /// Whether the invocation directory holds a project `.ai-jail`. ai-jail
+ /// loads that file itself, under its own trust rules (a project file may
+ /// disable capabilities but never enable credentials), so its presence
+ /// alone hands the toggles to it: nothing is pre-checked and the
+ /// interactive checklist is skipped. Only presence is probed — the
+ /// contents are untrusted and never read, so a repository cannot steer
+ /// the defaults through it.
+ pub project_config: bool,
+}
+
+impl JailHostFacts {
+ /// Facts for this host and the given repository. The project-config probe
+ /// reads the process's own working directory, which the re-exec inherits
+ /// and is where ai-jail looks; the global `~/.ai-jail` is deliberately
+ /// ignored (ai-jail writes it for its own status-bar preferences).
+ #[must_use]
+ pub fn here(repository: &crate::RepositoryIdentity) -> Self {
+ Self {
+ project_config: std::env::current_dir().is_ok_and(|dir| dir.join(".ai-jail").is_file()),
+ os: current_jail_os(),
+ home: std::env::var_os("HOME").map(PathBuf::from),
+ ssh_agent: std::env::var_os("SSH_AUTH_SOCK").is_some_and(|sock| !sock.is_empty()),
+ origin_url: repository.origin_url.clone(),
+ linked_worktree: repository.linked_worktree,
+ }
+ }
+
+ fn home_has(&self, relative: &str) -> bool {
+ self.home
+ .as_deref()
+ .is_some_and(|home| home.join(relative).exists())
+ }
+}
+
+/// Whether `url` reaches its remote over SSH: `ssh://…` (and the `git+ssh`
+/// spellings) or scp-style `user@host:path`.
+#[must_use]
+fn is_ssh_remote(url: &str) -> bool {
+ let url = url.trim();
+ if let Some((scheme, _)) = url.split_once("://") {
+ return matches!(
+ scheme.to_ascii_lowercase().as_str(),
+ "ssh" | "git+ssh" | "ssh+git"
+ );
+ }
+ url.split_once(':')
+ .is_some_and(|(host, _)| host.contains('@') && !host.contains('/'))
+}
+
+/// One visible checklist row with its smart default.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct JailChecklistItem {
+ /// The toggle shown.
+ pub toggle: &'static JailToggle,
+ /// Pre-checked state: what pressing Enter enables.
+ pub checked: bool,
+}
+
+/// The checklist rows for this host: toggles the installed ai-jail supports,
+/// that apply on this OS and, for credentials, exist on this host — each with
+/// its smart default (docs/design-yolo-safety-ai-jail.md §5).
+#[must_use]
+pub fn jail_checklist(facts: &JailHostFacts, support: &JailSupport) -> Vec<JailChecklistItem> {
+ JAIL_TOGGLES
+ .iter()
+ .filter(|toggle| support.supports(toggle.stem))
+ .filter_map(|toggle| {
+ let (visible, checked) = match toggle.rule {
+ ToggleRule::CredentialAt(path) => {
+ let present = facts.home_has(path);
+ (present, present)
+ }
+ ToggleRule::Ssh => (
+ facts.home_has(".ssh") || facts.ssh_agent,
+ facts.origin_url.as_deref().is_some_and(is_ssh_remote),
+ ),
+ ToggleRule::OptIn { linux_only } => {
+ (!linux_only || facts.os == JailOs::Linux, false)
+ }
+ ToggleRule::LinkedWorktree => (facts.linked_worktree, true),
+ ToggleRule::CliOnly => (false, false),
+ };
+ visible.then_some(JailChecklistItem {
+ toggle,
+ checked: checked && !facts.project_config,
+ })
+ })
+ .collect()
+}
+
+/// One toggle ai-memory passes to ai-jail: `--<stem>` or `--no-<stem>`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct JailToggleChoice {
+ /// The toggle's stem.
+ pub stem: &'static str,
+ /// `true` emits `--<stem>`, `false` emits `--no-<stem>`.
+ pub enable: bool,
+}
+
+impl JailToggleChoice {
+ /// The ai-jail flag this choice emits.
+ #[must_use]
+ pub fn flag(&self) -> String {
+ if self.enable {
+ format!("--{}", self.stem)
+ } else {
+ format!("--no-{}", self.stem)
+ }
+ }
+}
+
+/// The checked rows as choices: what Enter, or a bare `--jail`, enables.
+/// Unchecked rows emit nothing, leaving ai-jail's own default (off for every
+/// checklist toggle) and the user's ai-jail config in charge.
+#[must_use]
+pub fn checked_choices(items: &[JailChecklistItem]) -> Vec<JailToggleChoice> {
+ items
+ .iter()
+ .filter(|item| item.checked)
+ .map(|item| JailToggleChoice {
+ stem: item.toggle.stem,
+ enable: true,
+ })
+ .collect()
+}
+
+/// Why a `--jail=…` toggle list was refused.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum JailToggleError {
+ /// Not a toggle ai-memory knows.
+ Unknown(String),
+ /// A security switch or ai-memory-owned flag (see [`RESERVED_JAIL_FLAGS`]).
+ Reserved(String),
+ /// A known toggle the installed ai-jail does not accept.
+ Unsupported {
+ /// The toggle's stem.
+ stem: &'static str,
+ /// A release known to accept it.
+ since: &'static str,
+ },
+}
+
+impl std::fmt::Display for JailToggleError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Unknown(name) => {
+ let valid: Vec<&str> = JAIL_TOGGLES.iter().map(|toggle| toggle.stem).collect();
+ write!(
+ f,
+ "--jail: unknown toggle `{name}`; valid toggles: {}, plus `all`, `none`, and a `no-` prefix to force one off",
+ valid.join(", ")
+ )
+ }
+ Self::Reserved(name) => write!(
+ f,
+ "--jail: `{name}` is not available through ai-memory; run ai-jail directly"
+ ),
+ Self::Unsupported { stem, since } => write!(
+ f,
+ "--jail: the installed ai-jail does not support --{stem}; it needs ai-jail {since} or newer"
+ ),
+ }
+ }
+}
+
+impl std::error::Error for JailToggleError {}
+
+/// Parse a `--jail=…` list: comma-separated stems, each optionally prefixed
+/// `no-` to force it off, plus `all` (every row of `checklist`) and `none`
+/// (clear everything listed so far). Later entries win, so `all,no-docker`
+/// works. An empty list means the smart defaults; any other list is exactly
+/// what it names — nothing else is enabled.
+pub fn parse_jail_toggles(
+ spec: &str,
+ checklist: &[JailChecklistItem],
+ support: &JailSupport,
+) -> Result<Vec<JailToggleChoice>, JailToggleError> {
+ let items: Vec<&str> = spec
+ .split(',')
+ .map(str::trim)
+ .filter(|item| !item.is_empty())
+ .collect();
+ if items.is_empty() {
+ return Ok(checked_choices(checklist));
+ }
+ let mut choices: Vec<JailToggleChoice> = Vec::new();
+ fn set(choices: &mut Vec<JailToggleChoice>, choice: JailToggleChoice) {
+ choices.retain(|existing| existing.stem != choice.stem);
+ choices.push(choice);
+ }
+ for item in items {
+ let lowered = item.to_ascii_lowercase();
+ match lowered.as_str() {
+ "all" => {
+ for row in checklist {
+ set(
+ &mut choices,
+ JailToggleChoice {
+ stem: row.toggle.stem,
+ enable: true,
+ },
+ );
+ }
+ continue;
+ }
+ "none" => {
+ choices.clear();
+ continue;
+ }
+ _ => {}
+ }
+ let (stem, enable) = match lowered.strip_prefix("no-") {
+ Some(stem) => (stem, false),
+ None => (lowered.as_str(), true),
+ };
+ if RESERVED_JAIL_FLAGS.contains(&stem) {
+ return Err(JailToggleError::Reserved(item.to_owned()));
+ }
+ let Some(toggle) = jail_toggle(stem) else {
+ return Err(JailToggleError::Unknown(item.to_owned()));
+ };
+ if !support.supports(toggle.stem) {
+ return Err(JailToggleError::Unsupported {
+ stem: toggle.stem,
+ since: toggle.since,
+ });
+ }
+ set(
+ &mut choices,
+ JailToggleChoice {
+ stem: toggle.stem,
+ enable,
+ },
+ );
+ }
+ Ok(choices)
+}
+
/// 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, a `--` separator, then the
-/// wrapped executable and its forwarded arguments in order.
+/// name itself): `--network`, an optional bare `--agent-state` toggle, an
+/// optional `--no-save-config`, one `--env NAME` per already-filtered present
+/// name, one `--<stem>` /
+/// `--no-<stem>` per chosen toggle, a `--` separator, then the wrapped
+/// executable and its forwarded arguments in order.
///
/// The `--` is required, not cosmetic. ai-jail refuses one of its own flags
/// appearing after the command (it cannot tell whether
@@ -193,21 +736,38 @@ fn read_linux_hostname() -> Option<String> {
/// `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.
+///
+/// `no_save_config` must be set whenever the installed ai-jail supports it:
+/// on every ordinary run ai-jail otherwise merges its CLI flags into the
+/// project `.ai-jail` and writes it back, so the first jailed run would
+/// persist ai-memory's transient flags (`--network`, `--agent-state`, the
+/// chosen credentials) into the user's repository. Every later run would then
+/// find a project file, skip the checklist, and lose the credential mounts a
+/// project file cannot enable. `toggles` must
+/// already be limited to flags the installed ai-jail accepts
+/// ([`parse_jail_toggles`] / [`jail_checklist`]); they precede the `--` for
+/// the same reason every other sandbox flag does.
#[must_use]
pub fn build_ai_jail_invocation(
exe: &Path,
forwarded_args: &[OsString],
env_names_present: &[&str],
agent_state: bool,
+ no_save_config: bool,
+ toggles: &[JailToggleChoice],
) -> Vec<OsString> {
let mut argv = vec![OsString::from("--network")];
if agent_state {
argv.push(OsString::from("--agent-state"));
}
+ if no_save_config {
+ argv.push(OsString::from("--no-save-config"));
+ }
for name in env_names_present {
argv.push(OsString::from("--env"));
argv.push(OsString::from(*name));
}
+ argv.extend(toggles.iter().map(|toggle| OsString::from(toggle.flag())));
argv.push(OsString::from("--"));
argv.push(exe.as_os_str().to_os_string());
argv.extend(forwarded_args.iter().cloned());
@@ -350,12 +910,13 @@ mod tests {
OsString::from("--yolo"),
];
let present = ["AI_MEMORY_SERVER_URL", "ANTHROPIC_API_KEY"];
- let argv = build_ai_jail_invocation(exe, &forwarded, &present, true);
+ let argv = build_ai_jail_invocation(exe, &forwarded, &present, true, true, &[]);
assert_eq!(
strings(&argv),
[
"--network",
"--agent-state",
+ "--no-save-config",
"--env",
"AI_MEMORY_SERVER_URL",
"--env",
@@ -372,7 +933,7 @@ mod tests {
#[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);
+ let argv = build_ai_jail_invocation(exe, &[], &[], false, false, &[]);
assert_eq!(
strings(&argv),
["--network", "--", "/usr/local/bin/ai-memory"]
@@ -382,7 +943,7 @@ mod tests {
#[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);
+ let argv = build_ai_jail_invocation(exe, &[], &["CLAUDE_CONFIG_DIR"], false, false, &[]);
assert_eq!(
strings(&argv),
[
@@ -410,7 +971,14 @@ mod tests {
"--network",
]
.map(OsString::from);
- let argv = strings(&build_ai_jail_invocation(exe, &forwarded, &[], true));
+ let argv = strings(&build_ai_jail_invocation(
+ exe,
+ &forwarded,
+ &[],
+ true,
+ true,
+ &[],
+ ));
let separator = argv
.iter()
.position(|arg| arg == "--")
@@ -428,6 +996,439 @@ mod tests {
]
);
// Before the separator, only ai-memory's own sandbox flags appear.
- assert_eq!(&argv[..separator], ["--network", "--agent-state"]);
+ assert_eq!(
+ &argv[..separator],
+ ["--network", "--agent-state", "--no-save-config"]
+ );
+ }
+
+ /// The toggle lines of ai-jail 2.4.1's real `--help` (no credential
+ /// mounts, no `--toolchains`).
+ const HELP_2_4_1: &str = "\
+ --private-home / --no-private-home
+ --lockdown / --no-lockdown Enable/disable strict read-only lockdown mode
+ --save-config / --no-save-config
+ --no-gpu / --gpu Disable/enable GPU device passthrough (Linux only)
+ --no-docker / --docker Disable/enable Docker socket passthrough (grants host root; default: off)
+ --tailscale / --no-tailscale Enable/disable Tailscale socket passthrough (default: off)
+ --no-display / --display Disable/enable X11/Wayland passthrough (Linux only)
+ --audio / --no-audio Enable/disable host audio passthrough
+ --network / --no-network Enable/disable unrestricted network access (default: off)
+ --x11 / --no-x11 Enable/disable X11 socket passthrough (default: off)
+ --worktree / --no-worktree Enable/disable linked Git worktree metadata passthrough
+ --no-mise / --mise Disable/enable mise integration
+ --ssh / --no-ssh Share ~/.ssh read-only + forward SSH_AUTH_SOCK (default: off)
+ --pictures / --no-pictures Share ~/Pictures read-only (default: off)
+ --browser[=PROFILE] Use browser isolation profile (hard | soft; default hard)
+";
+
+ /// ai-jail 2.5.0 adds these lines on top of 2.4.1's.
+ const HELP_2_5_0_EXTRA: &str = "\
+ --github / --no-github Enable/disable read-only ~/.config/gh mount
+ --aws / --no-aws Enable/disable read-only ~/.aws mount
+ --kube / --no-kube Enable/disable read-only ~/.kube mount
+ --gcloud / --no-gcloud Enable/disable read-only ~/.config/gcloud
+ --docker-config / --no-docker-config
+ --no-toolchains / --toolchains Disable/enable dev-toolchain cache
+";
+
+ fn support_2_4_1() -> JailSupport {
+ JailSupport::from_help(HELP_2_4_1)
+ }
+
+ fn support_2_5_0() -> JailSupport {
+ JailSupport::from_help(&format!("{HELP_2_4_1}{HELP_2_5_0_EXTRA}"))
+ }
+
+ /// A temp `$HOME` holding exactly `paths` (relative), and no repo facts.
+ fn facts_with(home: &Path, paths: &[&str]) -> JailHostFacts {
+ for path in paths {
+ let full = home.join(path);
+ if path.ends_with(".json") {
+ std::fs::create_dir_all(full.parent().unwrap()).unwrap();
+ std::fs::write(&full, "{}").unwrap();
+ } else {
+ std::fs::create_dir_all(&full).unwrap();
+ }
+ }
+ JailHostFacts {
+ os: JailOs::Linux,
+ home: Some(home.to_path_buf()),
+ ssh_agent: false,
+ origin_url: None,
+ linked_worktree: false,
+ project_config: false,
+ }
+ }
+
+ fn rows(items: &[JailChecklistItem]) -> Vec<(&'static str, bool)> {
+ items
+ .iter()
+ .map(|item| (item.toggle.stem, item.checked))
+ .collect()
+ }
+
+ fn flags(choices: &[JailToggleChoice]) -> Vec<String> {
+ choices.iter().map(JailToggleChoice::flag).collect()
+ }
+
+ #[test]
+ fn toggle_table_has_unique_stems_and_never_lists_a_reserved_flag() {
+ let mut stems: Vec<&str> = JAIL_TOGGLES.iter().map(|toggle| toggle.stem).collect();
+ stems.sort_unstable();
+ let before = stems.len();
+ stems.dedup();
+ assert_eq!(stems.len(), before, "duplicate toggle stem");
+ for reserved in RESERVED_JAIL_FLAGS {
+ assert!(!stems.contains(reserved), "{reserved} must not be a toggle");
+ }
+ let cli_only: Vec<&str> = JAIL_TOGGLES
+ .iter()
+ .filter(|toggle| !toggle.in_checklist())
+ .map(|toggle| toggle.stem)
+ .collect();
+ assert_eq!(
+ cli_only,
+ [
+ "audio",
+ "x11",
+ "host-shm",
+ "terminal-passthrough",
+ "update-check",
+ "mise",
+ "toolchains"
+ ]
+ );
+ let docker = JAIL_TOGGLES.iter().find(|t| t.stem == "docker").unwrap();
+ assert!(docker.note.contains("grants host root"));
+ }
+
+ #[test]
+ fn support_detection_reads_exact_tokens_from_help() {
+ let old = support_2_4_1();
+ assert!(old.supports("ssh") && old.supports("gpu") && old.supports("mise"));
+ assert!(!old.supports("github"), "2.4.1 has no --github");
+ assert!(!old.supports("toolchains"));
+ assert!(old.supports("no-save-config"), "both spellings are tokens");
+ assert!(!JailSupport::from_help("").supports("no-save-config"));
+ let new = support_2_5_0();
+ assert!(new.supports("github") && new.supports("docker-config"));
+ assert!(
+ new.supports("toolchains"),
+ "`--no-toolchains / --toolchains`"
+ );
+
+ // `--docker` and `--docker-config` are distinct tokens either way.
+ let only_config = JailSupport::from_help(" --docker-config / --no-docker-config\n");
+ assert!(only_config.supports("docker-config"));
+ assert!(!only_config.supports("docker"));
+ let only_socket =
+ JailSupport::from_help(" --no-docker / --docker (grants host root)\n");
+ assert!(only_socket.supports("docker"));
+ assert!(!only_socket.supports("docker-config"));
+ // A valued flag's metavar does not make the bare stem supported.
+ assert!(!old.supports("browser"));
+ }
+
+ #[test]
+ fn credentials_are_shown_and_checked_only_when_present() {
+ let home = tempfile::tempdir().unwrap();
+ let facts = facts_with(home.path(), &[".config/gh", ".aws", ".docker/config.json"]);
+ let items = jail_checklist(&facts, &support_2_5_0());
+ let credentials: Vec<_> = rows(&items)
+ .into_iter()
+ .filter(|(stem, _)| ["github", "aws", "kube", "gcloud", "docker-config"].contains(stem))
+ .collect();
+ assert_eq!(
+ credentials,
+ [("github", true), ("aws", true), ("docker-config", true)],
+ "absent ~/.kube and ~/.config/gcloud are hidden"
+ );
+ // A bare `~/.docker` directory is not the registry config ai-jail mounts.
+ let bare = tempfile::tempdir().unwrap();
+ let facts = facts_with(bare.path(), &[".docker"]);
+ assert!(
+ !rows(&jail_checklist(&facts, &support_2_5_0()))
+ .iter()
+ .any(|(stem, _)| *stem == "docker-config")
+ );
+ }
+
+ #[test]
+ fn credentials_are_hidden_when_the_installed_ai_jail_lacks_them() {
+ let home = tempfile::tempdir().unwrap();
+ let facts = facts_with(home.path(), &[".config/gh", ".aws"]);
+ let stems: Vec<_> = rows(&jail_checklist(&facts, &support_2_4_1()))
+ .into_iter()
+ .map(|(stem, _)| stem)
+ .collect();
+ assert!(!stems.contains(&"github") && !stems.contains(&"aws"));
+ assert!(stems.contains(&"docker"), "2.4.1 toggles still show");
+ }
+
+ #[test]
+ fn ssh_shows_with_keys_or_agent_and_defaults_on_only_for_ssh_remotes() {
+ let empty = tempfile::tempdir().unwrap();
+ let mut facts = facts_with(empty.path(), &[]);
+ let ssh = |facts: &JailHostFacts| {
+ rows(&jail_checklist(facts, &support_2_4_1()))
+ .into_iter()
+ .find(|(stem, _)| *stem == "ssh")
+ };
+ assert_eq!(ssh(&facts), None, "no ~/.ssh and no agent: hidden");
+ facts.ssh_agent = true;
+ assert_eq!(ssh(&facts), Some(("ssh", false)), "agent only, no remote");
+
+ let keys = tempfile::tempdir().unwrap();
+ let mut facts = facts_with(keys.path(), &[".ssh"]);
+ for (url, expected) in [
+ ("[email protected]:example/repo.git", true),
+ ("ssh://[email protected]/repo.git", true),
+ ("[email protected]:repo.git", true),
+ ("https://github.com/example/repo.git", false),
+ ("https://[email protected]/repo.git", false),
+ ("/srv/git/repo.git", false),
+ ("file:///srv/git/repo.git", false),
+ ] {
+ facts.origin_url = Some(url.to_owned());
+ assert_eq!(ssh(&facts), Some(("ssh", expected)), "{url}");
+ }
+ }
+
+ #[test]
+ fn worktree_shows_checked_only_in_a_linked_worktree() {
+ let home = tempfile::tempdir().unwrap();
+ let mut facts = facts_with(home.path(), &[]);
+ let worktree = |facts: &JailHostFacts| {
+ rows(&jail_checklist(facts, &support_2_4_1()))
+ .into_iter()
+ .find(|(stem, _)| *stem == "worktree")
+ };
+ assert_eq!(worktree(&facts), None);
+ facts.linked_worktree = true;
+ assert_eq!(worktree(&facts), Some(("worktree", true)));
+ }
+
+ #[test]
+ fn capabilities_default_off_and_linux_only_ones_hide_elsewhere() {
+ let home = tempfile::tempdir().unwrap();
+ let mut facts = facts_with(home.path(), &[]);
+ assert_eq!(
+ rows(&jail_checklist(&facts, &support_2_4_1())),
+ [
+ ("docker", false),
+ ("gpu", false),
+ ("display", false),
+ ("pictures", false),
+ ("tailscale", false)
+ ]
+ );
+ facts.os = JailOs::MacOs;
+ assert_eq!(
+ rows(&jail_checklist(&facts, &support_2_4_1())),
+ [("docker", false), ("pictures", false), ("tailscale", false)]
+ );
+ }
+
+ /// A project `.ai-jail` hands the toggles to ai-jail: nothing is
+ /// pre-checked (so a bare `--jail` passes none), while the rows stay known
+ /// so an explicit `--jail=all` / `--jail=LIST` still overrides the file.
+ #[test]
+ fn project_config_unchecks_every_smart_default_but_keeps_explicit_lists() {
+ let home = tempfile::tempdir().unwrap();
+ let mut facts = facts_with(home.path(), &[".config/gh", ".aws", ".ssh"]);
+ facts.origin_url = Some("[email protected]:example/repo.git".to_owned());
+ facts.linked_worktree = true;
+ let support = support_2_5_0();
+ assert_eq!(
+ flags(&checked_choices(&jail_checklist(&facts, &support))),
+ ["--github", "--aws", "--ssh", "--worktree"],
+ "control: without a project file the defaults are on"
+ );
+
+ facts.project_config = true;
+ let checklist = jail_checklist(&facts, &support);
+ assert!(!checklist.is_empty());
+ assert!(checklist.iter().all(|item| !item.checked));
+ let parse = |spec: &str| flags(&parse_jail_toggles(spec, &checklist, &support).unwrap());
+ assert_eq!(
+ parse(""),
+ Vec::<String>::new(),
+ "bare --jail defers to the file"
+ );
+ assert_eq!(parse("github,gpu"), ["--github", "--gpu"]);
+ assert_eq!(parse("all").len(), checklist.len());
+ }
+
+ #[test]
+ fn save_config_is_owned_by_ai_memory() {
+ let error = parse_jail_toggles("save-config", &[], &support_2_5_0()).unwrap_err();
+ assert_eq!(error, JailToggleError::Reserved("save-config".to_owned()));
+ let error = parse_jail_toggles("no-save-config", &[], &support_2_5_0()).unwrap_err();
+ assert_eq!(
+ error,
+ JailToggleError::Reserved("no-save-config".to_owned())
+ );
+ }
+
+ fn sample_checklist(home: &Path) -> Vec<JailChecklistItem> {
+ let mut facts = facts_with(home, &[".config/gh", ".aws", ".ssh"]);
+ facts.origin_url = Some("https://example.com/repo.git".to_owned());
+ jail_checklist(&facts, &support_2_5_0())
+ }
+
+ #[test]
+ fn toggle_list_parses_stems_negations_all_and_none() {
+ let home = tempfile::tempdir().unwrap();
+ let checklist = sample_checklist(home.path());
+ let support = support_2_5_0();
+ let parse = |spec: &str| flags(&parse_jail_toggles(spec, &checklist, &support).unwrap());
+
+ assert_eq!(parse(""), ["--github", "--aws"], "empty = smart defaults");
+ assert_eq!(
+ parse("gpu, ssh"),
+ ["--gpu", "--ssh"],
+ "exactly what is listed"
+ );
+ assert_eq!(
+ parse("github,aws,no-mise"),
+ ["--github", "--aws", "--no-mise"]
+ );
+ assert_eq!(parse("GPU"), ["--gpu"], "case-insensitive");
+ assert_eq!(parse("gpu,no-gpu"), ["--no-gpu"], "later wins");
+ assert_eq!(
+ parse("all"),
+ [
+ "--github",
+ "--aws",
+ "--ssh",
+ "--docker",
+ "--gpu",
+ "--display",
+ "--pictures",
+ "--tailscale"
+ ],
+ "all = every visible checklist row"
+ );
+ assert_eq!(
+ parse("all,no-docker"),
+ [
+ "--github",
+ "--aws",
+ "--ssh",
+ "--gpu",
+ "--display",
+ "--pictures",
+ "--tailscale",
+ "--no-docker"
+ ]
+ );
+ assert_eq!(parse("none"), Vec::<String>::new());
+ assert_eq!(parse("all,none,toolchains"), ["--toolchains"]);
+ assert_eq!(
+ parse("kube"),
+ ["--kube"],
+ "an absent credential may still be named"
+ );
+ }
+
+ #[test]
+ fn toggle_list_rejects_unknown_and_reserved_names() {
+ let home = tempfile::tempdir().unwrap();
+ let checklist = sample_checklist(home.path());
+ let support = support_2_5_0();
+ let unknown = parse_jail_toggles("gpu,bogus", &checklist, &support).unwrap_err();
+ assert_eq!(unknown, JailToggleError::Unknown("bogus".to_owned()));
+ let message = unknown.to_string();
+ assert!(message.contains("bogus") && message.contains("docker-config"));
+ assert!(message.contains("github") && message.contains("all"));
+
+ for reserved in [
+ "seccomp",
+ "no-seccomp",
+ "landlock",
+ "private-home",
+ "no-private-home",
+ "lockdown",
+ "rlimits",
+ "systemd-user",
+ "inherit-env",
+ "macos-host-ipc",
+ "network",
+ "no-network",
+ "agent-state",
+ "browser",
+ "audit-log",
+ ] {
+ let error = parse_jail_toggles(reserved, &checklist, &support).unwrap_err();
+ assert_eq!(error, JailToggleError::Reserved(reserved.to_owned()));
+ assert!(
+ error
+ .to_string()
+ .contains("not available through ai-memory; run ai-jail directly"),
+ "{error}"
+ );
+ }
+ }
+
+ #[test]
+ fn toggle_list_names_the_ai_jail_release_a_missing_flag_needs() {
+ let home = tempfile::tempdir().unwrap();
+ let checklist = sample_checklist(home.path());
+ let error = parse_jail_toggles("ssh,github", &checklist, &support_2_4_1()).unwrap_err();
+ assert_eq!(
+ error,
+ JailToggleError::Unsupported {
+ stem: "github",
+ since: "2.5.0"
+ }
+ );
+ assert!(error.to_string().contains("ai-jail 2.5.0 or newer"));
+ assert!(parse_jail_toggles("no-toolchains", &checklist, &support_2_4_1()).is_err());
+ assert_eq!(
+ flags(&parse_jail_toggles("ssh,gpu", &checklist, &support_2_4_1()).unwrap()),
+ ["--ssh", "--gpu"]
+ );
+ }
+
+ #[test]
+ fn build_ai_jail_invocation_places_toggles_between_the_baseline_and_separator() {
+ let exe = Path::new("/bin/ai-memory");
+ let toggles = [
+ JailToggleChoice {
+ stem: "gpu",
+ enable: true,
+ },
+ JailToggleChoice {
+ stem: "mise",
+ enable: false,
+ },
+ ];
+ let forwarded = ["run", "claude", "--jail=gpu,no-mise"].map(OsString::from);
+ let argv = strings(&build_ai_jail_invocation(
+ exe,
+ &forwarded,
+ &["AI_MEMORY_SERVER_URL"],
+ true,
+ true,
+ &toggles,
+ ));
+ assert_eq!(
+ argv,
+ [
+ "--network",
+ "--agent-state",
+ "--no-save-config",
+ "--env",
+ "AI_MEMORY_SERVER_URL",
+ "--gpu",
+ "--no-mise",
+ "--",
+ "/bin/ai-memory",
+ "run",
+ "claude",
+ "--jail=gpu,no-mise",
+ ]
+ );
}
}
diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rs
index 9da02bc6..b12a4105 100644
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@ -14,8 +14,11 @@ pub use harness::{
store_override_vars,
};
pub use jail::{
- FORWARDED_ENV_NAMES, JailEnv, JailOs, build_ai_jail_invocation, current_jail_os,
- inside_ai_jail, inside_ai_jail_here, usable_ai_jail, usable_ai_jail_here,
+ FORWARDED_ENV_NAMES, JAIL_TOGGLES, JailChecklistItem, JailEnv, JailHostFacts, JailOs,
+ JailSupport, JailToggle, JailToggleChoice, JailToggleError, JailToggleKind, ai_jail_support,
+ build_ai_jail_invocation, checked_choices, current_jail_os, inside_ai_jail,
+ inside_ai_jail_here, jail_checklist, jail_toggle, parse_jail_toggles, usable_ai_jail,
+ usable_ai_jail_here,
};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
diff --git a/crates/ai-memory-workstream/src/repository.rs b/crates/ai-memory-workstream/src/repository.rs
index 11f18838..69fc2a54 100644
--- a/crates/ai-memory-workstream/src/repository.rs
+++ b/crates/ai-memory-workstream/src/repository.rs
@@ -18,6 +18,13 @@ pub struct RepositoryIdentity {
pub worktree_fingerprint: String,
/// Current non-mutating Git checkpoint.
pub checkpoint: WorkstreamCheckpoint,
+ /// First URL of the `origin` remote, when there is one. The ai-jail
+ /// toggles read it to decide whether `git push` needs SSH.
+ pub origin_url: Option<String>,
+ /// Whether the cwd is a linked worktree (its git dir differs from the
+ /// repository's common dir), whose metadata ai-jail must mount writable
+ /// for the agent to commit.
+ pub linked_worktree: bool,
}
/// Inspect the current checkout without committing, stashing, resetting, or
@@ -53,6 +60,16 @@ pub fn inspect_repository(cwd: &Path) -> Result<RepositoryIdentity> {
repo_fingerprint: sha256(&repo_seed),
worktree_fingerprint: sha256(&worktree_seed),
checkpoint: checkpoint(&canonical),
+ origin_url: remotes
+ .as_deref()
+ .and_then(|remotes| remotes.lines().next())
+ .map(str::trim)
+ .filter(|url| !url.is_empty())
+ .map(str::to_owned),
+ linked_worktree: matches!(
+ (&git_dir, &common_dir),
+ (Some(git_dir), Some(common)) if git_dir != common
+ ),
})
}
@@ -144,6 +161,71 @@ mod tests {
assert_eq!(first.repo_fingerprint, second.repo_fingerprint);
assert_eq!(first.worktree_fingerprint, second.worktree_fingerprint);
assert_eq!(first.repo_fingerprint.len(), 64);
+ assert_eq!(first.origin_url, None);
+ assert!(!first.linked_worktree);
+ }
+
+ fn git_fixture(cwd: &Path, args: &[&str]) {
+ let status = Command::new("git")
+ .arg("-C")
+ .arg(cwd)
+ .args([
+ "-c",
+ "user.name=fixture",
+ "-c",
+ ])
+ .args(args)
+ .status()
+ .unwrap();
+ assert!(status.success(), "git {args:?} failed");
+ }
+
+ /// The ai-jail toggle defaults key off these two facts: an SSH-style
+ /// `origin` pre-checks `ssh`, and only a linked worktree shows `worktree`.
+ #[test]
+ fn reports_origin_url_and_linked_worktree() {
+ let temp = tempfile::tempdir().unwrap();
+ let main = temp.path().join("main");
+ std::fs::create_dir(&main).unwrap();
+ git_fixture(&main, &["init", "-q"]);
+ git_fixture(
+ &main,
+ &["remote", "add", "origin", "[email protected]:example/repo.git"],
+ );
+ git_fixture(
+ &main,
+ &[
+ "commit",
+ "-q",
+ "--allow-empty",
+ "--no-gpg-sign",
+ "-m",
+ "init",
+ ],
+ );
+ let primary = inspect_repository(&main).unwrap();
+ assert_eq!(
+ primary.origin_url.as_deref(),
+ Some("[email protected]:example/repo.git")
+ );
+ assert!(!primary.linked_worktree, "the main checkout is not linked");
+
+ let linked = temp.path().join("linked");
+ git_fixture(
+ &main,
+ &[
+ "worktree",
+ "add",
+ "-q",
+ "-b",
+ "side",
+ linked.to_str().unwrap(),
+ ],
+ );
+ let worktree = inspect_repository(&linked).unwrap();
+ assert!(worktree.linked_worktree);
+ assert_eq!(worktree.origin_url, primary.origin_url);
}
#[test]
diff --git a/docs/cookbook.md b/docs/cookbook.md
index e7105d69..c29f9b3c 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -179,6 +179,31 @@ ai-memory run --yolo claude
`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).
+- **Choosing what the jail gets.** After you accept the offer, a checklist
+ lists what this host can mount, pre-marked so `Enter` does the friendly
+ thing: every credential that exists (`~/.config/gh`, `~/.aws`, `~/.kube`,
+ `~/.config/gcloud`, `~/.docker/config.json`), SSH keys + agent when your
+ `origin` is an SSH remote, and worktree metadata in a linked worktree. The
+ Docker socket (grants host root), GPU, display, Pictures, and Tailscale are
+ listed unchecked. Type row numbers to flip them (`2 4`), or `all` / `none`.
+ A mounted credential is usable by the unsupervised agent, so uncheck what it
+ should not touch.
+- **Skipping the questions.** `ai-memory run --jail claude` re-runs inside
+ ai-jail straight away with those defaults — with or without `--yolo`, and in
+ scripts too; it fails rather than running unjailed if ai-jail is not usable.
+ `--jail=github,ssh,no-mise` enables exactly the listed toggles (`no-X`
+ forces one off), plus `all` / `none`. `--no-jail` never jails and skips the
+ offer (the `--yolo` warning stays). There are no bare `--github`-style
+ flags on purpose: they would collide with the harness's own flags (Claude
+ Code has a `--worktree`). The credential mounts need ai-jail 2.5.0; toggles
+ your installed ai-jail lacks are hidden, and naming one is an error.
+- **A project `.ai-jail` wins.** If the directory you launch from has its own
+ `.ai-jail`, ai-jail loads it as-is: no checklist, and a bare `--jail` adds
+ no toggles; `--jail=…` still applies its list on top. A project file cannot
+ enable credentials (ai-jail treats it as untrusted), so to have them mounted
+ automatically there, enable them in your global `~/.ai-jail` or pass
+ `--jail=github,…`. ai-memory always passes `--no-save-config`, so a jailed
+ run never writes its own flags into your repository's `.ai-jail`.
- **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
diff --git a/docs/design-yolo-safety-ai-jail.md b/docs/design-yolo-safety-ai-jail.md
index a3f0e536..6d052590 100644
--- a/docs/design-yolo-safety-ai-jail.md
+++ b/docs/design-yolo-safety-ai-jail.md
@@ -27,7 +27,8 @@ every tool call with no confirmation. Three gaps:
## Non-goals
- Changing default (non-`--yolo`) behavior. Everything here is gated on
- `--yolo`.
+ `--yolo`, except the explicit `--jail` flag (§5), which a user types to ask
+ for a jailed run.
- 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
@@ -75,7 +76,7 @@ On yes, ai-memory re-execs itself under ai-jail instead of spawning the agent
directly:
```
-ai-jail --network --agent-state <state> \
+ai-jail --network --agent-state --no-save-config \
--env AI_MEMORY_SERVER_URL --env AI_MEMORY_HOOK_URL \
--env ANTHROPIC_API_KEY --env CLAUDE_CODE_OAUTH_TOKEN \
--env CLAUDE_CONFIG_DIR --env … \
@@ -110,6 +111,8 @@ ai-jail --network --agent-state <state> \
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.
+- **`--no-save-config`** so ai-jail never writes these flags into the
+ project `.ai-jail` (§5).
- **`--agent-state`** so the harness's own login/credentials persist across the
private home.
@@ -176,6 +179,163 @@ The `claude_true_yolo` config key only upgrades a launch that is already
`--yolo`/`--true-yolo`; on its own it never turns an ordinary run into a
permission-bypassing one without the warning.
+### 5. Choosing what the jail exposes: `--jail`, `--no-jail`, the checklist
+
+ai-jail keeps credentials and host devices out by default and exposes each
+through a boolean toggle (`--X` / `--no-X`). A jailed agent that cannot reach
+`gh`, the AWS CLI, or an SSH key often cannot finish the task, so the user
+picks what the jail mounts — from the CLI or an interactive checklist — and
+pressing Enter does the friendly thing.
+
+**CLI.** Two wrapper flags on `ai-memory run` (and recognized after native
+arguments too, like `--yolo`; neither ever reaches the harness):
+
+| Form | Meaning |
+|---|---|
+| `--jail` | Re-run inside ai-jail now, without the "Re-run inside it?" question or the checklist, using the smart defaults below. |
+| `--jail=github,aws,no-mise` | Same, enabling exactly the listed toggles; `no-X` forces one off (`--no-X`). Nothing unlisted is enabled. |
+| `--jail=all` / `--jail=none` | Every checklist row this host shows / no toggles at all. Lists are applied left to right, so `all,no-docker` works. |
+| `--no-jail` | Never re-run inside ai-jail; the `--yolo` warning still shows. Conflicts with `--jail`. |
+
+`--jail` needs `=` for its list (`require_equals`), so `ai-memory run --jail
+claude` keeps `claude` as the harness. It works with or without `--yolo` and
+in non-interactive runs too — that is how a script gets a jailed run. When
+ai-jail is not usable on the host (§2) it fails with an error instead of
+silently running unjailed. An explicit `--jail` re-execs *before* the managed
+run is prepared, so no lease is opened and cancelled outside the jail. Inside
+ai-jail (§3) both flags are ignored: no nesting, no error.
+
+There are deliberately **no bare `--github`-style flags** on `ai-memory run`.
+They would collide with harness-native flags of the same name (Claude Code
+has its own `--worktree`), and wrapper flags after the harness name are
+stripped from the native argv — a bare `--worktree` meant for Claude would be
+silently taken away from it. The single namespaced `--jail=` list has no such
+collision.
+
+**Toggles.** The table (`JAIL_TOGGLES` in `ai-memory-workstream/src/jail.rs`):
+
+| Toggle | Kind | Checklist | Smart default (Enter / bare `--jail`) |
+|---|---|---|---|
+| `github` (`~/.config/gh`) | credential | when that directory exists | on when present |
+| `aws` (`~/.aws`) | credential | when present | on when present |
+| `kube` (`~/.kube`) | credential | when present | on when present |
+| `gcloud` (`~/.config/gcloud`) | credential | when present | on when present |
+| `docker-config` (`~/.docker/config.json`) | credential | when present | on when present |
+| `ssh` (`~/.ssh` read-only + `SSH_AUTH_SOCK`) | credential | when `~/.ssh` exists or an agent socket is set | on only when `origin` is SSH-style (`git@host:…`, `ssh://…`) |
+| `worktree` | capability | only in a linked git worktree | on there |
+| `docker` (socket — ⚠ grants host root) | capability | always | off |
+| `gpu`, `display` | capability | Linux only | off |
+| `pictures`, `tailscale` | capability | always | off |
+| `audio`, `x11`, `host-shm`, `terminal-passthrough`, `update-check`, `mise`, `toolchains` | capability | never (`--jail=` only) | not passed |
+
+Why these defaults: every credential is pre-checked when present because a
+user who keeps `gh` or AWS credentials on the machine almost always wants the
+agent able to use them, and a box shown only when the path exists never mounts
+nothing. The credential rows check the exact path ai-jail mounts — `GH_CONFIG_DIR`
+is not consulted, because ai-jail 2.5.0 mounts `~/.config/gh` regardless. SSH
+is shown but left unchecked for an HTTPS remote, since only an SSH `origin`
+makes `git push` need it. `worktree` is pre-checked in a linked worktree,
+where without its metadata mounted writable the agent cannot commit. The host
+capabilities stay off: they widen the sandbox without being needed for the
+usual task.
+
+**Semantics.** Unchecked rows (and toggles a list does not name) emit
+nothing, so ai-jail's own default — off for every checklist toggle — and the
+user's own ai-jail configuration stay in charge; `no-X` is the explicit way to
+force one off. The chosen toggles are emitted as `--X` / `--no-X` after the
+`--network --agent-state --no-save-config --env …` baseline and before the `--` separator.
+
+**A project `.ai-jail` replaces the checklist.** ai-jail reads its project
+config only from the invocation directory, which the re-exec inherits from
+ai-memory. When a regular file `.ai-jail` exists there:
+
+| | no project `.ai-jail` | project `.ai-jail` present |
+|---|---|---|
+| offer accepted (no flag) | checklist, smart defaults | no checklist, no toggles: the file is loaded as-is |
+| bare `--jail` | smart defaults | no toggles: the file is loaded as-is |
+| `--jail=LIST` | exactly the list | the list, on top of the file (CLI flags override config in ai-jail) |
+
+A project file is untrusted — it lives in the repository the agent works on.
+ai-jail lets it disable capabilities but never enable credentials, `docker`,
+`agent_state`, and the like, so ai-memory must not pre-check anything on its
+behalf either, and an untrusted repository must not be able to steer the
+checklist. Only the file's presence is probed (`JailHostFacts::project_config`);
+its contents are never read or parsed. The global `~/.ai-jail` is not
+consulted: ai-jail writes it for its status-bar preferences, so most users have
+one. To get credentials mounted automatically alongside a project `.ai-jail`,
+enable them in the trusted global `~/.ai-jail` or pass `--jail=github,…`,
+because the project file cannot enable them.
+
+**Why every re-exec passes `--no-save-config`.** On every ordinary run (not
+`--dry-run`, not lockdown, saving not disabled) ai-jail merges its CLI flags
+into the project config and writes `.ai-jail` back. Without the flag, the
+first jailed run would persist ai-memory's transient flags (`--network`,
+`--agent-state`, the checked credentials) into the user's repository; every
+later run would then find a project file, skip the checklist, and silently
+lose the credential mounts a project file cannot enable — and ai-jail would
+warn that the project file's `agent_state` is ignored because it weakens the
+baseline sandbox. `--no-save-config` sits in the baseline next to `--network`
+/ `--agent-state`, before the `--`, guarded by the same `--help` detection (both
+2.4.1 and 2.5.0 have it). It is reserved: `--jail=save-config` is refused.
+
+**Checklist.** Without either flag and without a project `.ai-jail`, after the
+user accepts the §2 offer, the rows visible on this host are listed with their
+smart defaults:
+
+```
+Enable in the jail (Enter = as marked; numbers flip, e.g. "2 4"; "all" / "none"):
+ [x] 1) GitHub CLI credentials ~/.config/gh, read-only
+ [x] 2) AWS credentials ~/.aws, read-only
+ [ ] 3) SSH keys + agent ~/.ssh read-only + SSH_AUTH_SOCK; needed for git over SSH
+ [ ] 4) Docker socket ⚠ grants host root
+>
+```
+
+Enter (or EOF) accepts as marked; row numbers (spaces or commas) flip rows and
+redraw the list; `all` / `none` set every row. An unrecognized answer changes
+nothing and re-prompts; the third one aborts the launch rather than guessing
+what to mount. One summary line then names what the jail gets, grouped into
+credentials, capabilities, and forced-off toggles. With no visible row the
+checklist is skipped. The reader takes injected `BufRead`/`Write`, like the §1
+prompt, so its grammar is unit-tested without a TTY.
+
+**Decision table** (`jail_decision` in `run.rs`):
+
+| | already jailed | `--no-jail` | `--jail[=…]` | neither |
+|---|---|---|---|---|
+| `--yolo` warning (interactive only) | no | yes | yes | yes |
+| ai-jail | no (no nesting) | never | re-exec now; error if not usable | offer + checklist when interactive and usable (no checklist with a project `.ai-jail`) |
+
+**Version requirements.** ai-jail rejects an unknown flag, so ai-memory only
+passes flags the *installed* ai-jail supports. It runs `<ai-jail> --help` once
+and treats a toggle as supported only when the exact token `--X` appears
+(tokens split on whitespace and `/`; never a substring match, so `--docker`
+and `--docker-config` stay distinct). Unsupported toggles are hidden from the
+checklist; one named explicitly in `--jail=` is an error naming the release
+that has it. The credential mounts (`github`, `aws`, `kube`, `gcloud`,
+`docker-config`) and `toolchains` need ai-jail **2.5.0**; the rest are in
+2.4.1.
+
+**Never offered.** `--jail=` refuses the security switches and the flags
+ai-memory owns, with "not available through ai-memory; run ai-jail directly":
+`private-home`, `lockdown`, `landlock`, `seccomp`, `rlimits`, `systemd-user`,
+`inherit-env`, `macos-host-ipc`, `browser`, the audit-log flags (each weakens
+or reconfigures the sandbox itself), and `network` / `agent-state` /
+`save-config` (set by ai-memory, §2). Someone who needs one runs ai-jail
+directly.
+
+**Security notes.**
+
+- A credential mounted into an unsupervised (`--yolo`) agent is usable by it:
+ read-only stops it from changing the files, not from using the tokens in
+ them. Pre-checking present credentials trades that exposure for a jailed
+ agent that can do its job; the checklist shows each one, and `--jail=none`
+ or unchecking opts out.
+- `docker` grants effective root on the host; it is never on by default and
+ its note says so.
+- The re-exec still forwards only environment names already set (§2), and
+ the toggle flags carry no values or secrets.
+
## OS support matrix
| Concern | Linux | macOS | Windows |
@@ -197,6 +357,11 @@ permission-bypassing one without the warning.
(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).
+- §5: the toggle table, `--help` support detection (`JailSupport`), host facts
+ (`JailHostFacts`, fed by `inspect_repository`'s `origin_url` /
+ `linked_worktree`), `jail_checklist`, and `parse_jail_toggles` live in
+ `jail.rs`; `run.rs` owns `--jail`/`--no-jail` parsing, the `jail_decision`
+ table, and the checklist reader.
- `ai-memory-workstream/src/harness.rs`: `apply_claude_true_yolo(env, args)`
next to `apply_yolo`.
@@ -223,3 +388,11 @@ permission-bypassing one without the warning.
`--settings` arg for Claude and is a no-op for other harnesses.
- CHANGELOG `### Added` (minor); support-matrix + cookbook updated in the same
change.
+- §5: `jail.rs` unit tests cover list parsing, support detection against
+ 2.4.1/2.5.0 help text, and every smart default with an injected `$HOME`;
+ `run.rs` tests cover the decision table, flag stripping via a real clap
+ parse, and the checklist grammar. `tests/suite/yolo_ai_jail.rs` feeds every
+ toggle the real installed ai-jail advertises through `ai-jail --dry-run`;
+ `tests/suite/jail_toggles_e2e.rs` runs the built binary with fake
+ `ai-jail`/`bwrap`/`claude` and a mock server (including a PTY run of the
+ offer + checklist and of `--yolo --no-jail`).
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 5d63037a..3df5c1d2 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -22,7 +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 usable — installed and with its sandbox backend present (`bwrap` / `sandbox-exec`); otherwise it asks nothing and proceeds (`--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` implies `--yolo` and, for Claude only, additionally forces `bypassPermissions` over any settings `defaultMode` (interchangeable with `--yolo` for other harnesses); `claude_true_yolo` applies the same Claude extra to `--yolo` launches. Claude's own explicit `ask` rules and command-safety checks still prompt in every mode. See [`docs/design-yolo-safety-ai-jail.md`](design-yolo-safety-ai-jail.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 usable — installed and with its sandbox backend present (`bwrap` / `sandbox-exec`); otherwise it asks nothing and proceeds (`--network`, forwarding only already-set credential/config env vars). Accepting the offer shows a checklist of ai-jail toggles pre-marked with smart defaults (credentials present on the host, SSH for an SSH `origin`, worktree metadata in a linked worktree; Docker socket, GPU, display, Pictures, Tailscale unchecked). `--jail` re-runs inside ai-jail without asking (also without `--yolo` and non-interactively; it errors when ai-jail is not usable), `--jail=github,aws,no-mise` enables exactly the listed toggles (`all`/`none` too), and `--no-jail` skips the offer. Only toggles the installed ai-jail supports are offered; the credential mounts (`github`, `aws`, `kube`, `gcloud`, `docker-config`) need ai-jail 2.5.0. A project `.ai-jail` in the launch directory replaces the checklist and the bare-`--jail` defaults (ai-jail loads it as-is; `--jail=…` still overrides), and every re-exec passes `--no-save-config` so ai-jail never writes the run's flags into it. 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` implies `--yolo` and, for Claude only, additionally forces `bypassPermissions` over any settings `defaultMode` (interchangeable with `--yolo` for other harnesses); `claude_true_yolo` applies the same Claude extra to `--yolo` launches. Claude's own explicit `ask` rules and command-safety checks still prompt in every mode. 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). |