Skip to content

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

Rust

Merge pull request #975 from dajiaohuang/post-run-switch

AkitaOnRails45f69a59f504
diff --cc CHANGELOG.md
index fa8f65f8,2e02377b..209c1e66
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -8,266 -8,11 +8,271 @@@ and this project adheres to [Semantic V
## [Unreleased]
### Added
+- Added a NixOS module exposed as `nixosModules.default`, with a dedicated
+ non-login service user, a hardened systemd unit, declarative non-secret
+ settings, agenix/sops/environment-file secret sources, and opt-in web,
+ firewall, and resource settings. Non-loopback binds require exactly one
+ secret source; expensive Darwin and privileged container checks run only in
+ the full CI tier. (#989)
+- Added `ai-memory doctor` reporting for Claude Code's default native
+ `memory/` store for the current repository: location, file count, and whether
+ the nearest marker's `ignore_paths` would exclude a read. Repository-root
+ resolution keeps worktrees and subdirectories on the same report, and the
+ output warns that shell/PowerShell compatibility hooks do not enforce the
+ exclusion. (#1003)
+- Added per-event outcomes to `/hook/batch` acknowledgements and process-lifetime
+ ingest counters for stored events, replays, recovery, ignored endings,
+ collisions and failures. Legacy acknowledgement fields were preserved. (#1015)
+- Added receipt outcomes and delivery counts to the companion relay. Opening a
+ schema 1 queue now upgrades it atomically to schema 2; older relay binaries
+ refuse schema 2, so downgrade requires a pre-upgrade backup with all queue
+ users stopped. Pending order and existing delivery metadata were preserved.
+ Receipts now retain their first known outcome. (#1015)
+- Added `ai-memory list-projects [--workspace] [--json]`: a plain, scriptable
+ listing of every workspace/project pair the server knows about, sorted by
+ workspace then project. Previously the only way to see this from outside
+ an interactive `show` session was to call `GET /api/v1/projects` directly.
+ (#1022)
+- Added scope and policy preflight to `ai-memory hook --check-capture`, including
+ event eligibility, sanitized routing hints and server-remapping information.
+ Partial scope, excluded events, rejected profiles and oversized hints refuse
+ capture. Inspection neither ingests events nor claims handoffs. (#1019)
+- Added the latest scoped consolidation job's state and attempt count to HTTP
+ session summaries and MCP `memory_read_session_observations`. The field is
+ `null` when no job exists; provider errors remain private and existing session
+ ownership filters are preserved. (#1018)
+- Added incremental paging to scoped HTTP `recent` reads with `updated_since`
+ and an opaque, scope-bound cursor. Queries preserve equal-time ordering,
+ exclude expired and superseded pages and recheck authorization on each
+ request. Calls without incremental arguments retain their existing array
+ response. Added a generic MCP/HTTP integration guide. (#1017)
+- Added machine-authenticated `GET /identity`, available with the web UI
+ disabled, and `ai-memory doctor` diagnostics for caller identity, external
+ capture ownership and sessions with multiple capture sources (native events
+ or distinct extensions, including backfill).
+ Mixed-source counts preserve scope, session ownership and time-window filters;
+ older servers leave unsupported fields unknown. (#1016)
+
+### Changed
+- Documented FutureInfra as an endpoint for the existing `openai-compat`
+ provider. (#1026)
+
+### Fixed
+- Fixed completed retries and no-op session endings advancing
+ `last_persisted_ms` without a durable write. Recovery still advances the
+ timestamp when it commits a new page or terminal effect. (#1015)
+- `ai-memory doctor` now warns when the nearest `.ai-memory.toml`'s
+ `[capture]` section is invalid. This fails closed today — every file and
+ shell tool event is reduced to metadata until the marker is fixed, nothing
+ leaks — but nothing surfaced that it had happened, so an operator could
+ believe `ignore_paths` was excluding paths it no longer was. The check is
+ based on the same resolution state the live hook path uses (not just
+ whether the TOML parses), so it also catches a `[capture]` table that
+ parses fine but is still rejected at compile time, e.g. an unsupported glob
+ character in `ignore_paths`. (#1021)
+- Fixed the shell and PowerShell hook scripts mishandling a `$HOME` that ends
+ in a separator: the shell walks missed a marker between the checkout and
+ home, and the PowerShell walks went past home and read a marker above it.
+ Both now match the native `ai-memory hook` walk. (#1023)
+- Fixed `ai-memory run --jail` leaving the `ssh` toggle unchecked when
+ `git push` goes over SSH but `origin`'s fetch URL does not show it: an HTTPS
+ `origin` with an SSH `pushurl` or `pushInsteadOf`, or a `host:path` remote
+ using an `~/.ssh/config` alias. The interactive offer now also uses
+ ai-jail's own dry-run preflight, so a backend that exists but fails ai-jail's
+ trust checks is treated as unavailable instead of producing a broken offer.
+ (#1024)
+
+## [2.5.2] - 2026-10-01
+
+### 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, and anything else is left to
+ the user's own ai-jail config. `--jail=github,aws,no-mise` is exact: it
+ passes every checklist row it does not name as `--no-X`, so a global
+ `~/.ai-jail` cannot add to it (`all` and `none` also work); the checklist
+ likewise passes unchecked rows as `--no-X`. `--jail` 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
+ sending the marker's `[briefing]` keys (`briefing`, `briefing_budget`) on the
+ handoff request, so a repository with `inject_on_session_start = true` got
+ the handoff without its compiled brief on script installs (Docker wrapper,
+ `setup-agent`). Only the native `ai-memory hook` command and the Kiro CLI and
+ Kimi Code scripts sent them; all now match `docs/marker-file.md`. (#998)
+- Fixed a wiki checkpoint leaving `.git/index` behind the commit it made. A
+ path-scoped checkpoint wrote the index file only once every 50 commits, so
+ between writes `HEAD` and the working tree held the new page while the index
+ still named the old blob, and `git status` from outside the server showed
+ every checkpointed page as `MM`; a checkpoint with nothing to commit left a
+ stale index the same way. The history itself was always correct. Not specific
+ to Windows. (#983, #1006)
+- Fixed a wiki checkpoint failing instead of retrying when a full walk listed a
+ file that was gone by the time it was read (libgit2's `Os`-class "failed to
+ read file into stream", e.g. an atomic writer's temp file renamed away
+ mid-walk). It now takes the same bounded racy-read retry as a file changed
+ mid-write; unrelated I/O errors still fail fast. This was also the source of
+ an intermittent `concurrent_commits_queue_instead_of_failing` CI failure.
+
+### Security
+- Fixed GHSA-gf78-hf8g-vffm: `memory_read_page` with `include_related` returning pages from
+ projects the caller cannot read under per-project authorization, and walking
+ through them to reach others: in multi-user mode an authenticated user without
+ a grant saw the paths, titles, kinds, and project names of pages in a
+ `restricted` project up to three hops away (never their bodies). `page_links`
+ and the graph already hid them; the multi-hop related walk now filters every
+ hop the same way. Installs without authorization, and root, are unchanged.
+ (#999)
+- Fixed CLI `ai-memory message send` (`POST /admin/messages/send`) bypassing
+ `message_send` admission: it inserted the message without consulting a
+ configured webhook's reject policy or notifying observers, while the MCP
+ send path enforced both. It now runs admission at the recipient scope before
+ the insert — a rejection returns 403 and stores nothing — and notifies
+ observers only after a successful commit, without waiting on nonblocking
+ ones. (#756)
+
+## [2.5.1] - 2026-10-01
+
+### Fixed
+- Fixed `ai-memory run --yolo`'s ai-jail re-exec aborting when the wrapped
+ command carried a flag that ai-jail also defines: `run claude --yolo --env
+ GH_TOKEN=…` failed with "flag --env after command would be passed to the
+ child". The invocation now separates ai-jail's sandbox flags from the
+ wrapped command with `--`; forwarding such a flag also needs ai-jail 2.4.2 or
+ later, whose guard honors the separator.
+- Fixed the `--yolo` ai-jail offer appearing when accepting it could not
+ work. It is now shown only on Linux/macOS when both ai-jail and its sandbox
+ backend (`bwrap` / `sandbox-exec`) are present — never on Windows, even with a
+ file named `ai-jail` on `PATH` — and otherwise the run proceeds without the
+ question. The re-exec runs the exact binary that was found, so a
+ `~/.local/bin`-only ai-jail no longer fails to exec after the user accepted.
+- Fixed `--true-yolo`. It now implies `--yolo` (the warning, the ai-jail
+ offer, and each harness's dangerous mode), so passing it alone no longer
+ bypassed Claude's permissions with no warning; it is interchangeable with
+ `--yolo` for non-Claude harnesses instead of printing "ignoring it"; and it is
+ recognized after native arguments (`run claude --model opus --true-yolo`)
+ instead of being passed to Claude as an unknown option. The `claude_true_yolo`
+ config key now
+ only upgrades an explicit `--yolo`/`--true-yolo` launch, as documented,
+ rather than applying `bypassPermissions` to every managed Claude run.
+- Fixed relaunching right after an interrupted `ai-memory run` failing with
+ "workstream is already active: owned by … until …" when the previous
+ launcher could not release its lease (killed, terminal closed, or an
+ ai-jail sandbox torn down). An interactive launch now names the holder and
+ waits for that lease to lapse (at most one ~90-second lease; Ctrl-C aborts),
+ then starts by itself. A holder that renews the lease meanwhile is reported
+ as a launcher still running — never displaced — and non-interactive launches
+ keep the short retry window.
+- Fixed `--true-yolo` claiming protections it never provided. It set three
+ `CLAUDE_CODE_DISABLE_*RM*` environment variables that Claude Code does not
+ read, and passed an empty `permissions.ask` array that cannot clear `ask`
+ rules from other settings scopes (Claude Code unions them). Both were
+ removed; true-yolo now forces only `bypassPermissions`, and the docs state
+ that Claude still honors your own `ask` rules and command-safety checks in
+ every mode.
+
+### Security
+- Fixed GHSA-vh98: a capture-exclusion candidate or shell argument spelled
+ with a leading `//` (e.g. `//repo/secret/token.txt`) self-classified as a
+ Windows UNC path regardless of the actual host, so it matched zero POSIX
+ `ignore_paths` patterns (a flavor mismatch) and was captured instead of
+ dropped. Path flavor for an untrusted candidate is now derived from the
+ host (the cwd) rather than the candidate string alone, both in the native
+ hook (`ai-memory-hooks` `capture_policy.rs`) and the generated
+ OpenCode/OMP/Pi/OpenClaw TypeScript integrations
+ (`ai-memory-cli` `render_shared.rs`); a genuine Windows/UNC host's UNC
+ candidates are unaffected.
+## [2.5.0] - 2026-09-30
+
+### Added
+- `ai-memory run --yolo` now warns before disarming an agent's safety prompts
+ and, on Linux/macOS, offers to re-run the session inside
+ [ai-jail](https://github.com/akitaonrails/ai-jail) when it is installed.
+ The warning and offer are TTY-gated (stdin and stderr must both be real
+ terminals) and skipped entirely when already running inside ai-jail
+ (detected via the Linux `ai-sandbox` hostname or the macOS `(jail) ` `PS1`
+ prefix), so hook, CI, detached, and piped runs are unaffected. Accepting
+ the ai-jail offer re-execs the original invocation under `ai-jail
+ --network --agent-state <harness> --env <NAME>...` (only already-set
+ credential/config env vars are forwarded); declining `--yolo` itself
+ aborts before the agent spawns. A new opt-in `--true-yolo` flag /
+ `claude_true_yolo` config key additionally silences Claude Code's
+ residual `--dangerously-skip-permissions` prompts (the `rm` timeout and
+ confirmation, and the PowerShell `rm` deny) and forces
+ `--settings '{"permissions":{"defaultMode":"bypassPermissions","ask":[]}}'`;
+ it is a no-op for every other harness. See
+ `docs/design-yolo-safety-ai-jail.md`. (#994)
+- `ai-memory repair-backfill-timestamps [--project] [--workspace] [--confirm]
+ [--json]` and `POST /admin/repair-session-times` correct
+ `sessions.started_at`/`ended_at` for sessions an older `backfill` imported
+ before it carried the transcript's own event time, which flattened every
+ imported session onto the import day. Only rewrites a row whose
+ `started_at` actually postdates the candidate's own transcript end (a
+ correctly hook-captured session, or a re-run, is a no-op); refuses
+ out-of-scope, unchanged, negative, inverted, or future-dated candidates;
+ never closes a still-open session; and records an `audit_log` row on
+ apply. Dry-run by default. (#921)
+- Native tool output resolution for Antigravity CLI lifecycle hooks
+ (`post-tool-use`). Command stdout (`run_command`), file views (`view_file`),
+ search results (`find_by_name`, `grep_search`, `search_web`), and task
+ management outputs are now read directly from
+ `.system_generated/steps/<stepIdx>/output.txt` and populated into observation
+ excerpts. Code modification capture via `write_to_file` and
+ `replace_file_content` remains preserved from invocation arguments. (#966)
+- The watcher's reconcile pass can now optionally tombstone a wiki page whose
+ file has disappeared from disk, closing part of the gap left by #929 (the
+ watcher only reconciled create/modify events, so a deleted file stayed
+ indexed until `ai-memory delete-page` ran explicitly). Opt-in and default
+ `false` (`[maintenance] reconcile_tombstones_deleted_pages`), so existing
+ installs see no behavior change unless they turn it on. When enabled, a
+ page's file must be observed missing on two consecutive 30s reconcile
+ passes, re-verified against the live filesystem immediately before acting;
+ a circuit breaker refuses to act on a whole scope when more than `max(3,
+ 50%)` of its candidate pages look missing in one pass, or when a
+ non-partial walk finds nothing at all (either shape is far more likely a
+ walk/mount problem than genuine mass deletion); and reserved/indexed-but-
+ unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/` sidecars, and
+ `sessions/*.md` — excluded because a same-workspace `move-session` re-home
+ can leave one with a correct row and no file, a separate pre-existing bug)
+ are never candidates. The action is a soft tombstone (`is_latest = 0` +
+ `superseded_at`, the same shape decay eviction already uses), picked up by
+ the SAME aged-tombstone hard-delete sweep decay eviction uses — it is not
+ exempt from it. What actually protects it: it is never destroyed while its
+ chain has no successor; if the file returns, the new version re-links onto
+ the tombstoned chain instead of starting a fresh, disconnected one, so
+ nothing is left orphaned for that sweep to destroy. It never runs the
+ blocking admission gate (nothing can refuse it), but does fire-and-forget
+ any non-blocking observer/mirror webhook on success. `restore-page` and
+ version history remain intact. See `docs/okf.md` for the full design.
+ (#964)
+- `ai-memory run` now finalizes the session when a harness without a native
+ session-end hook exits (Command Code, Kiro CLI v2 and v3, Antigravity CLI),
+ so the summary, handoff and opt-in SessionEnd consolidation no longer wait
+ for a manual `ai-memory finalize-session`. Only a session the run can tie to
+ itself (named, chosen before the spawn, or linked during the run) is closed,
+ including again after it was resumed; if finalizing fails, the run prints
+ the exact command to run and keeps the harness's exit code. (#941)
+ - After an interactive managed `ai-memory run` session exits successfully, a
+ default-quit prompt can switch to another installed harness or re-run the
+ current one in the same workstream. The prompt is limited to terminal
+ session launches without `--executable`; utility, failed, interrupted, and
+ non-interactive runs keep their existing exit behavior. (#909)
- `[consolidation] input_token_safety_margin` (float, default `0.8`, validated
to `(0.0, 1.0]`) scales the approximate char-count input budget. The
`max_input_tokens` budget uses a flat chars-per-token heuristic that
diff --cc crates/ai-memory-cli/src/commands/run.rs
index 3594e03e,897c2f1d..82155294
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@@ -9,23 -9,20 +9,24 @@@ use std::time::{Duration, SystemTime}
use ai_memory_core::{
AgentKind, FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,
ManagedRunContextResponse, ManagedRunStatus, PrepareManagedRunRequest,
- PrepareManagedRunResponse,
+ PrepareManagedRunResponse, SessionId,
};
use ai_memory_workstream::{
- AmbiguousNativeSession, ExportedTranscript, LaunchMode, LaunchPlan, LaunchRoots,
- ManagedHarness, NativeSessionCandidate, allows_native_session_adoption, apply_yolo,
+ 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, crush_global_config_path,
- discover_native_session, export_transcript, has_native_session_selector, inspect_repository,
- is_interactive_session_invocation, kiro_explicit_session_id, kiro_harness_from_source_cursor,
- kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,
- kiro_v3_resume_uses_default_store, list_native_sessions, native_session_exists,
- native_session_in_checkout, omp_profile_flag, omp_profile_flag_env, store_override_vars,
- wait_for_transcript_flush,
+ discover_native_session, export_transcript, has_native_session_selector, inside_ai_jail_here,
- inspect_repository, 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,
- marked_choices, 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,
++ inspect_repository, is_interactive_session_invocation, 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, marked_choices, 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 clap::ValueEnum as _;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
@@@ -119,6 -109,212 +120,198 @@@ pub(super) async fn run_from_with_wirin
cwd: &Path,
wire_overrides: &super::run_autowire::WireOverrides,
) -> Result<i32> {
+ run_once_with_wiring(config, args, cwd, wire_overrides)
+ .await
+ .map(|outcome| outcome.exit_code)
+ }
+
+ #[derive(Debug)]
+ struct RunOutcome {
+ exit_code: i32,
+ harness: ManagedHarness,
+ interactive_session: bool,
+ mode: LaunchMode,
+ workstream_name: String,
+ }
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ enum AfterRunAction {
+ Switch(RunHarnessChoice),
+ Rerun,
+ Quit,
+ }
+
-const RUN_HARNESS_CHOICES: [RunHarnessChoice; 12] = [
- RunHarnessChoice::Claude,
- RunHarnessChoice::Codex,
- RunHarnessChoice::OpenCode,
- RunHarnessChoice::OpenCode2,
- RunHarnessChoice::Pi,
- RunHarnessChoice::Crush,
- RunHarnessChoice::Omp,
- RunHarnessChoice::Kimi,
- RunHarnessChoice::CommandCode,
- RunHarnessChoice::Kiro,
- RunHarnessChoice::Grok,
- RunHarnessChoice::Antigravity,
-];
-
+ async fn run_with_exit_prompt(config: &Config, args: RunArgs, cwd: &Path) -> Result<i32> {
+ let interactive_terminal =
+ io::stdin().is_terminal() && io::stdout().is_terminal() && io::stderr().is_terminal();
+ let custom_executable = args.executable.is_some();
+ let mut next_args = args;
+ preserve_trailing_run_options(&mut next_args);
+
+ loop {
+ let outcome = run_once_with_wiring(
+ config,
+ next_args.clone(),
+ cwd,
+ &super::run_autowire::WireOverrides::default(),
+ )
+ .await?;
+ if !should_offer_after_run(&outcome, interactive_terminal, custom_executable) {
+ return Ok(outcome.exit_code);
+ }
+
+ let available = available_switch_harnesses(outcome.harness);
+ let action = {
+ let stdin = io::stdin();
+ let stderr = io::stderr();
+ choose_after_run(
+ outcome.harness,
+ &outcome.workstream_name,
+ &available,
+ &mut stdin.lock(),
+ &mut stderr.lock(),
+ )
+ };
+ let action = match action {
+ Ok(action) => action,
+ Err(error) => {
+ eprintln!("ai-memory: could not read the post-run choice ({error}); exiting");
+ return Ok(outcome.exit_code);
+ }
+ };
+ if !apply_after_run_action(&mut next_args, &outcome, action) {
+ return Ok(outcome.exit_code);
+ }
+ }
+ }
+
+ fn should_offer_after_run(
+ outcome: &RunOutcome,
+ interactive_terminal: bool,
+ custom_executable: bool,
+ ) -> bool {
+ outcome.exit_code == 0
+ && outcome.mode == LaunchMode::Session
+ && outcome.interactive_session
+ && interactive_terminal
+ && !custom_executable
+ }
+
+ fn preserve_trailing_run_options(args: &mut RunArgs) {
- args.yolo |= args
- .native_args
- .iter()
- .any(|arg| arg == OsStr::new("--yolo"));
- args.no_autowire |= args
- .native_args
- .iter()
- .any(|arg| arg == OsStr::new("--no-autowire"));
++ args.yolo |= remove_wrapper_yolo(&mut args.native_args);
++ args.true_yolo |= remove_wrapper_true_yolo(&mut args.native_args);
++ args.no_autowire |= remove_wrapper_no_autowire(&mut args.native_args);
++ let trailing_jail = remove_wrapper_jail(&mut args.native_args);
++ if trailing_jail.jail.is_some() {
++ args.jail = trailing_jail.jail;
++ }
++ args.no_jail |= trailing_jail.no_jail;
+ }
+
+ fn available_switch_harnesses(current: ManagedHarness) -> Vec<RunHarnessChoice> {
- RUN_HARNESS_CHOICES
- .into_iter()
++ RunHarnessChoice::value_variants()
++ .iter()
++ .copied()
+ .filter(|choice| {
+ managed_harness(*choice).agent_kind() != current.agent_kind()
+ && harness_available(*choice)
+ })
+ .collect()
+ }
+
+ fn choose_after_run(
+ current: ManagedHarness,
+ workstream_name: &str,
+ available: &[RunHarnessChoice],
+ input: &mut impl io::BufRead,
+ output: &mut impl io::Write,
+ ) -> io::Result<AfterRunAction> {
+ writeln!(
+ output,
+ "ai-memory: {} exited successfully in workstream '{}'.",
+ current.as_str(),
+ workstream_name
+ )?;
+ for (index, choice) in available.iter().enumerate() {
+ writeln!(
+ output,
+ " {}) switch to {}",
+ index + 1,
+ managed_harness(*choice).as_str()
+ )?;
+ }
+ writeln!(output, " r) run {} again", current.as_str())?;
+ writeln!(output, " q) quit (default)")?;
+
+ loop {
+ write!(output, "Select [q]: ")?;
+ output.flush()?;
+ let mut line = String::new();
+ if input.read_line(&mut line)? == 0 {
+ return Ok(AfterRunAction::Quit);
+ }
+ let choice = line.trim();
+ if choice.is_empty() || choice.eq_ignore_ascii_case("q") || choice == "0" {
+ return Ok(AfterRunAction::Quit);
+ }
+ if choice.eq_ignore_ascii_case("r") {
+ return Ok(AfterRunAction::Rerun);
+ }
+ if let Ok(index) = choice.parse::<usize>()
+ && let Some(harness) = index.checked_sub(1).and_then(|i| available.get(i))
+ {
+ return Ok(AfterRunAction::Switch(*harness));
+ }
+ writeln!(output, "Choose a listed number, r, or q.")?;
+ }
+ }
+
+ fn apply_after_run_action(
+ args: &mut RunArgs,
+ outcome: &RunOutcome,
+ action: AfterRunAction,
+ ) -> bool {
+ let choice = match action {
+ AfterRunAction::Quit => return false,
+ AfterRunAction::Switch(choice) => choice,
+ AfterRunAction::Rerun => run_harness_choice(outcome.harness),
+ };
+ args.harness = Some(choice);
+ args.native_args =
+ if action == AfterRunAction::Rerun && outcome.harness == ManagedHarness::KiroV3 {
+ vec![OsString::from("--v3")]
+ } else {
+ Vec::new()
+ };
+ args.workstream = Some(outcome.workstream_name.clone());
+ args.new_workstream = None;
+ args.fresh = false;
+ true
+ }
+
+ const fn run_harness_choice(harness: ManagedHarness) -> RunHarnessChoice {
+ match harness {
+ ManagedHarness::Claude => RunHarnessChoice::Claude,
+ ManagedHarness::Codex => RunHarnessChoice::Codex,
+ ManagedHarness::OpenCode => RunHarnessChoice::OpenCode,
+ ManagedHarness::OpenCode2 => RunHarnessChoice::OpenCode2,
+ ManagedHarness::Pi => RunHarnessChoice::Pi,
+ ManagedHarness::Crush => RunHarnessChoice::Crush,
+ ManagedHarness::Omp => RunHarnessChoice::Omp,
+ ManagedHarness::Kimi => RunHarnessChoice::Kimi,
+ ManagedHarness::CommandCode => RunHarnessChoice::CommandCode,
+ ManagedHarness::Kiro | ManagedHarness::KiroV3 => RunHarnessChoice::Kiro,
+ ManagedHarness::Grok => RunHarnessChoice::Grok,
+ ManagedHarness::Antigravity => RunHarnessChoice::Antigravity,
+ }
+ }
+
+ async fn run_once_with_wiring(
+ config: &Config,
+ args: RunArgs,
+ cwd: &Path,
+ wire_overrides: &super::run_autowire::WireOverrides,
+ ) -> Result<RunOutcome> {
let repository = inspect_repository(cwd)?;
let home = native_home(config).context("locating native harness session storage")?;
let automatic_harness = args.harness.is_none();
@@@ -732,81 -829,15 +926,87 @@@
prepared.workstream_name
);
interrupt_task.abort();
+ if let Some((session, finalized)) = finalize_hookless_session(
+ config,
+ harness,
+ own_session_id.as_deref(),
+ &workspace,
+ &project,
+ )
+ .await
+ {
+ let agent = harness.agent_kind().as_str();
+ match finalized {
+ Ok(ids) if !ids.is_empty() => {
+ eprintln!("ai-memory: finalized the {agent} session {session}");
+ }
+ // No session under that id for this agent and owner in this
+ // scope: its hooks are not installed or never fired, or they
+ // filed it under another workspace/project.
+ Ok(_) => {}
+ Err(error) => eprintln!(
+ "ai-memory: could not finalize the {agent} session {session} ({error:#}); run `ai-memory finalize-session --agent {agent} --reopen --session-id {session} --workspace {} --project {}`",
+ super::render_shared::shell_quote(&workspace),
+ super::render_shared::shell_quote(&project)
+ ),
+ }
+ }
- Ok(exit_code)
+ Ok(RunOutcome {
+ exit_code,
+ harness,
+ interactive_session,
+ mode: plan.mode,
+ workstream_name: prepared.workstream_name,
+ })
}
+/// How long finalizing may hold up the harness's exit code.
+const FINALIZE_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// Finalizes the run's own session when the harness has no native session-end
+/// hook, which would otherwise leave it open until a manual
+/// `ai-memory finalize-session` (#941). The harness has exited, so the session
+/// is over for this run.
+/// Returns the stored session id and the ids finalized, or `None` when there
+/// is nothing to do.
+async fn finalize_hookless_session(
+ config: &Config,
+ harness: ManagedHarness,
+ own_session_id: Option<&str>,
+ workspace: &str,
+ project: &str,
+) -> Option<(SessionId, Result<Vec<String>>)> {
+ let native_session_id = own_session_id?;
+ if !harness.lacks_session_end_hook() {
+ return None;
+ }
+ let session = SessionId::from_native(native_session_id);
+ let args = crate::cli::FinalizeSessionArgs {
+ agent: harness.agent_kind(),
+ workspace: Some(workspace.to_string()),
+ project: Some(project.to_string()),
+ all_owners: false,
+ all: false,
+ session_id: Some(session),
+ // These harnesses keep capturing under the same id when a session is
+ // resumed, so a later run must be able to end it again. A re-end
+ // with nothing new since the last one changes nothing on the server.
+ reopen: true,
+ json: false,
+ };
+ // Tokio keeps SIGINT once it has been captured, so listen afresh: Ctrl-C
+ // skips a slow finalize instead of being dropped.
+ let finalized = tokio::select! {
+ finalized = tokio::time::timeout(
+ FINALIZE_TIMEOUT,
+ super::finalize_session::finalize(config, &args),
+ ) => finalized
+ .unwrap_or_else(|_| Err(anyhow!("timed out after {}s", FINALIZE_TIMEOUT.as_secs()))),
+ Ok(()) = tokio::signal::ctrl_c() => Err(anyhow!("interrupted")),
+ };
+ Some((session, finalized.map(|(_, _, ids)| ids)))
+}
+
async fn capture_interrupts(interrupted: CancellationToken) {
while tokio::signal::ctrl_c().await.is_ok() {
interrupted.cancel();
@@@ -2485,477 -1866,184 +2685,632 @@@ const fn managed_harness(choice: RunHar
}
}
-fn managed_harness_for_args(choice: RunHarnessChoice, native_args: &[OsString]) -> ManagedHarness {
- let harness = managed_harness(choice);
- if harness == ManagedHarness::Kiro && kiro_selects_v3_engine(native_args) {
- ManagedHarness::KiroV3
- } else {
- harness
+fn managed_harness_for_args(choice: RunHarnessChoice, native_args: &[OsString]) -> ManagedHarness {
+ let harness = managed_harness(choice);
+ if harness == ManagedHarness::Kiro && kiro_selects_v3_engine(native_args) {
+ ManagedHarness::KiroV3
+ } else {
+ harness
+ }
+}
+
+const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness> {
+ match agent {
+ AgentKind::ClaudeCode => Some(ManagedHarness::Claude),
+ AgentKind::Codex => Some(ManagedHarness::Codex),
+ AgentKind::OpenCode => Some(ManagedHarness::OpenCode),
+ AgentKind::Pi => Some(ManagedHarness::Pi),
+ AgentKind::Crush => Some(ManagedHarness::Crush),
+ AgentKind::KimiCode => Some(ManagedHarness::Kimi),
+ AgentKind::CommandCode => Some(ManagedHarness::CommandCode),
+ AgentKind::KiroCli => Some(ManagedHarness::Kiro),
+ AgentKind::Grok => Some(ManagedHarness::Grok),
+ AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::ffi::{OsStr, OsString};
+ use std::io::Cursor;
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ use ai_memory_core::{ManagedRunId, WorkstreamId};
+ use axum::Router;
+ use axum::http::StatusCode;
+ use axum::response::IntoResponse as _;
+ use axum::routing::post;
+ use clap::Parser as _;
+
+ use super::*;
+ 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 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!(
+ 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!(
+ 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", "--no-ssh", "--no-docker"],
+ "every row as seen: unchecked rows are forced off"
+ );
+ 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", "--no-ssh", "--no-docker"]
+ );
+ }
+
+ #[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", "--no-aws", "--no-ssh", "--docker"]
+ );
+ assert!(
+ 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(),
+ ["--no-github", "--aws", "--ssh", "--no-docker"]
+ );
+ 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(),
+ ["--no-github", "--no-aws", "--no-ssh", "--no-docker"]
+ );
+ let (none_then_one, _) = run_checklist("none\n3\n");
+ assert_eq!(
+ none_then_one.unwrap(),
+ ["--no-github", "--no-aws", "--ssh", "--no-docker"]
+ );
+ }
+
+ #[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", "--no-aws", "--no-ssh", "--no-docker"],
+ "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", "--no-ssh", "--no-docker"]
+ );
+
+ let (gave_up, _) = run_checklist("x\nx\nx\n\n");
+ assert!(
+ 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,
+ implied: false,
+ };
+ let implied_off = |stem| JailToggleChoice {
+ stem,
+ enable: false,
+ implied: true,
+ };
+ 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)"
+ );
+ // An explicit selection: the user's own `no-X` is named, the rows it
+ // left out are summarized, never claimed as "no extra mounts" only.
+ assert_eq!(
+ jail_summary(
+ &[
+ choice("github", true),
+ choice("mise", false),
+ implied_off("docker"),
+ implied_off("gpu"),
+ ],
+ false
+ ),
+ "ai-memory: re-running inside ai-jail (credentials: GitHub CLI credentials; \
+ forced off: --no-mise; everything else in the checklist off)"
+ );
+ assert_eq!(
+ jail_summary(&[implied_off("docker")], false),
+ "ai-memory: re-running inside ai-jail (everything else in the checklist off)"
+ );
+ }
+
+ #[test]
+ fn yolo_decision_defaults_to_proceed() {
+ assert!(yolo_decision(""), "empty line (bare Enter) proceeds");
+ assert!(yolo_decision("\n"));
+ assert!(yolo_decision("y"));
+ assert!(yolo_decision("Y"));
+ assert!(yolo_decision("yes"));
+ assert!(yolo_decision("YES"));
+ assert!(
+ yolo_decision("whatever"),
+ "an unrecognized line still proceeds (default yes)"
+ );
}
-}
-const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness> {
- match agent {
- AgentKind::ClaudeCode => Some(ManagedHarness::Claude),
- AgentKind::Codex => Some(ManagedHarness::Codex),
- AgentKind::OpenCode => Some(ManagedHarness::OpenCode),
- AgentKind::Pi => Some(ManagedHarness::Pi),
- AgentKind::Crush => Some(ManagedHarness::Crush),
- AgentKind::KimiCode => Some(ManagedHarness::Kimi),
- AgentKind::CommandCode => Some(ManagedHarness::CommandCode),
- AgentKind::KiroCli => Some(ManagedHarness::Kiro),
- AgentKind::Grok => Some(ManagedHarness::Grok),
- AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),
- _ => None,
+ #[test]
+ fn yolo_decision_declines_only_on_explicit_no() {
+ assert!(!yolo_decision("n"));
+ assert!(!yolo_decision("N"));
+ assert!(!yolo_decision("no"));
+ assert!(!yolo_decision("NO\n"));
}
-}
-#[cfg(test)]
-mod tests {
- use std::ffi::{OsStr, OsString};
- use std::io::Cursor;
- use std::sync::Arc;
- use std::sync::atomic::{AtomicUsize, Ordering};
+ #[test]
+ fn read_yolo_confirmation_default_enter_proceeds_without_jail_offer() {
+ let mut input = Cursor::new(b"\n".to_vec());
+ let mut output = Vec::new();
+ let confirmation = read_yolo_confirmation(false, &mut input, &mut output).unwrap();
+ assert_eq!(
+ confirmation,
+ YoloConfirmation {
+ proceed: true,
+ jail: false
+ }
+ );
+ let printed = String::from_utf8(output).unwrap();
+ assert!(printed.contains("Proceed? [Y/n]"));
+ assert!(!printed.contains("ai-jail is installed"));
+ }
- use ai_memory_core::{ManagedRunId, WorkstreamId};
- use axum::Router;
- use axum::http::StatusCode;
- use axum::response::IntoResponse as _;
- use axum::routing::post;
- use clap::Parser as _;
+ #[test]
+ fn read_yolo_confirmation_decline_aborts_before_the_jail_offer() {
+ let mut input = Cursor::new(b"n\n".to_vec());
+ let mut output = Vec::new();
+ let confirmation = read_yolo_confirmation(true, &mut input, &mut output).unwrap();
+ assert_eq!(
+ confirmation,
+ YoloConfirmation {
+ proceed: false,
+ jail: false
+ }
+ );
+ let printed = String::from_utf8(output).unwrap();
+ assert!(
+ !printed.contains("ai-jail is installed"),
+ "declining --yolo must never reach the ai-jail offer"
+ );
+ }
- use super::*;
- use crate::cli::{Cli, Command as CliCommand};
+ #[test]
+ fn read_yolo_confirmation_offers_ai_jail_and_reads_its_answer() {
+ let mut input = Cursor::new(b"\nn\n".to_vec());
+ let mut output = Vec::new();
+ let confirmation = read_yolo_confirmation(true, &mut input, &mut output).unwrap();
+ assert_eq!(
+ confirmation,
+ YoloConfirmation {
+ proceed: true,
+ jail: false
+ }
+ );
+ let printed = String::from_utf8(output).unwrap();
+ assert!(printed.contains("ai-jail is installed. Re-run this session inside it? [Y/n]"));
+ }
+ fn run_args_for_after_run_test() -> RunArgs {
+ RunArgs {
+ workspace: Some("work".into()),
+ project: Some("repo".into()),
+ workstream: None,
+ new_workstream: Some("initial".into()),
+ executable: None,
+ yolo: true,
++ true_yolo: true,
++ jail: None,
++ no_jail: true,
+ fresh: true,
+ no_autowire: true,
+ env: vec![("MODEL_HOME".into(), "custom".into())],
+ env_file: None,
+ harness: Some(RunHarnessChoice::Claude),
+ native_args: vec![OsString::from("--model"), OsString::from("opus")],
+ }
+ }
+
+ #[test]
+ fn post_run_choice_defaults_to_quit_and_lists_same_workstream_actions() {
+ let mut input = Cursor::new(b"\n");
+ let mut output = Vec::new();
+ let action = choose_after_run(
+ ManagedHarness::Claude,
+ "research",
+ &[RunHarnessChoice::Codex],
+ &mut input,
+ &mut output,
+ )
+ .unwrap();
+
+ assert_eq!(action, AfterRunAction::Quit);
+ let output = String::from_utf8(output).unwrap();
+ assert!(output.contains("workstream 'research'"));
+ assert!(output.contains("1) switch to codex"));
+ assert!(output.contains("r) run claude again"));
+ assert!(output.contains("q) quit (default)"));
+ }
+
+ #[test]
+ fn post_run_choice_selects_an_installed_harness_by_number() {
+ let mut input = Cursor::new(b"1\n");
+ let mut output = Vec::new();
+ assert_eq!(
+ choose_after_run(
+ ManagedHarness::Claude,
+ "research",
+ &[RunHarnessChoice::Codex],
+ &mut input,
+ &mut output,
+ )
+ .unwrap(),
+ AfterRunAction::Switch(RunHarnessChoice::Codex)
+ );
+ }
+
+ #[test]
+ fn trailing_wrapper_options_survive_the_post_run_menu() {
+ let mut args = run_args_for_after_run_test();
+ args.yolo = false;
++ args.true_yolo = false;
++ args.jail = None;
++ args.no_jail = false;
+ args.no_autowire = false;
- args.native_args
- .extend([OsString::from("--yolo"), OsString::from("--no-autowire")]);
++ args.native_args.extend([
++ OsString::from("--yolo"),
++ OsString::from("--true-yolo"),
++ OsString::from("--jail=github,no-mise"),
++ OsString::from("--no-autowire"),
++ ]);
+
+ preserve_trailing_run_options(&mut args);
+ assert!(args.yolo);
++ assert!(args.true_yolo);
++ assert_eq!(args.jail.as_deref(), Some("github,no-mise"));
++ assert!(!args.no_jail);
+ assert!(args.no_autowire);
++ assert_eq!(
++ args.native_args,
++ [OsString::from("--model"), OsString::from("opus")]
++ );
+ }
+
+ #[test]
+ fn post_run_actions_reuse_the_workstream_without_replaying_native_args() {
+ let mut args = run_args_for_after_run_test();
+ let outcome = RunOutcome {
+ exit_code: 0,
+ harness: ManagedHarness::Claude,
+ interactive_session: true,
+ mode: LaunchMode::Session,
+ workstream_name: "research".into(),
+ };
+
+ assert!(apply_after_run_action(
+ &mut args,
+ &outcome,
+ AfterRunAction::Switch(RunHarnessChoice::Codex)
+ ));
+ assert_eq!(args.harness, Some(RunHarnessChoice::Codex));
+ assert_eq!(args.workstream.as_deref(), Some("research"));
+ assert_eq!(args.new_workstream, None);
+ assert!(!args.fresh);
+ assert!(args.native_args.is_empty());
+ assert!(args.yolo);
++ assert!(args.true_yolo);
++ assert!(args.no_jail);
+ assert!(args.no_autowire);
+ assert_eq!(args.env, [("MODEL_HOME".into(), "custom".into())]);
+ }
+
+ #[test]
+ fn rerunning_kiro_v3_keeps_its_engine_without_replaying_user_args() {
+ let mut args = run_args_for_after_run_test();
+ let outcome = RunOutcome {
+ exit_code: 0,
+ harness: ManagedHarness::KiroV3,
+ interactive_session: true,
+ mode: LaunchMode::Session,
+ workstream_name: "research".into(),
+ };
+
+ assert!(apply_after_run_action(
+ &mut args,
+ &outcome,
+ AfterRunAction::Rerun
+ ));
+ assert_eq!(args.harness, Some(RunHarnessChoice::Kiro));
+ assert_eq!(args.native_args, [OsString::from("--v3")]);
+ assert_eq!(args.workstream.as_deref(), Some("research"));
+ }
+
+ #[test]
+ fn post_run_prompt_requires_clean_interactive_managed_session_without_custom_binary() {
+ let outcome = RunOutcome {
+ exit_code: 0,
+ harness: ManagedHarness::Claude,
+ interactive_session: true,
+ mode: LaunchMode::Session,
+ workstream_name: "research".into(),
+ };
+ assert!(should_offer_after_run(&outcome, true, false));
+ assert!(!should_offer_after_run(&outcome, false, false));
+ assert!(!should_offer_after_run(&outcome, true, true));
+
+ let mut failed = outcome;
+ failed.exit_code = 1;
+ assert!(!should_offer_after_run(&failed, true, false));
+ failed.exit_code = 0;
+ failed.mode = LaunchMode::Passthrough;
+ assert!(!should_offer_after_run(&failed, true, false));
+ }
+
#[tokio::test(start_paused = true)]
async fn native_session_choice_interrupt_does_not_wait_for_input() {
let interrupted = CancellationToken::new();
diff --cc crates/ai-memory-workstream/src/lib.rs
index ae6a13c1,c3fb13c6..5b8c61d4
--- a/crates/ai-memory-workstream/src/lib.rs
+++ b/crates/ai-memory-workstream/src/lib.rs
@@@ -7,19 -6,12 +7,19 @@@ mod transcript
pub use harness::{
LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,
- apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path, crush_data_dir,
- crush_global_config_path, env_dir_override, has_native_session_selector,
+ apply_claude_true_yolo, apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path,
+ crush_data_dir, crush_global_config_path, env_dir_override, has_native_session_selector,
- kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,
- kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag, omp_profile_flag_env,
- store_override_vars,
+ is_interactive_session_invocation, kiro_explicit_session_id, kiro_selects_non_default_engine,
+ kiro_selects_v2_engine, kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag,
+ omp_profile_flag_env, store_override_vars,
};
+pub use jail::{
+ FORWARDED_ENV_NAMES, 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, marked_choices, parse_jail_toggles,
+ usable_ai_jail, usable_ai_jail_here,
+};
pub use repository::{RepositoryIdentity, inspect_repository};
pub use transcript::{
AmbiguousNativeSession, ExportedTranscript, NativeSessionCandidate, discover_native_session,
diff --cc docs/managed-workstreams.md
index b1115cd0,6f284a83..e4a340b8
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@@ -73,6 -73,18 +73,19 @@@ ai-memory run kiro --v
ai-memory run
```
+ After an interactive managed session exits successfully, `ai-memory run` offers
+ the installed harnesses, a way to run the current harness again, and quit.
+ Choosing another harness keeps the same workstream selected, so its saved
+ context remains available to the next run. The prompt defaults to quit. It
+ appears only when stdin, stdout, and stderr are terminals, the managed launch
+ was a session, and `--executable` was not used; utility commands, failed or
+ interrupted exits, and non-interactive launches do not prompt. A switch or
+ re-run does not replay the previous harness's native arguments, which may be
+ specific to that CLI; wrapper settings such as `--workspace`, `--project`,
-`--yolo`, `--no-autowire`, `--env`, and `--env-file` remain in effect. The
-initial `--fresh` choice applies only to the first launch.
++`--yolo` / `--true-yolo`, ai-jail controls, `--no-autowire`, `--env`, and
++`--env-file` remain in effect. The initial `--fresh` choice applies only to the
++first launch.
+
Everything after the harness name is native argv except the wrapper-owned exact
flags `--yolo` and `--fresh`. No `--` separator is needed, and ai-memory does
not maintain a second copy of each harness's option schema. Other wrapper