Skip to main content

aither_sandbox/
terminal.rs

1//! Terminal command tool implementation with heel sandboxing.
2//!
3//! Provides the main `terminal` tool that LLMs use to execute terminal work.
4//! Despite the historical tool name, execution does not have to go through a
5//! literal `terminal` process: simple commands may be executed directly, while shell
6//! syntax falls back to a real shell when needed.
7//! Commands run in a sandbox with configurable permission modes.
8//!
9//! Each `Shell` works in one shared working directory. All terminal
10//! executions share this directory, but each execution gets a fresh sandbox
11//! (new TTY/process). The ids the model addresses — task ids, stored output
12//! names, subagent spaces — are leased from the terminal's
13//! [`AnyIdAllocator`](aither_core::AnyIdAllocator).
14
15use crate::foreground_wait::ForegroundWait;
16use crate::memory::{
17    AnyContainerMemory, AnyFootprintReader, AnyFootprintRegistry, FootprintReader,
18    FootprintRegistry, JobMemory, ProbedContainerMemory, ResponseWindow, SystemFootprints,
19};
20use crate::outage::Outages;
21use crate::spawn::Backend;
22#[cfg(test)]
23use crate::{AnyShellWording, OutputPolicy};
24use crate::{CallRefusal, RunFailure, ShellWording};
25use std::{
26    borrow::Cow,
27    io::Read,
28    path::{Path, PathBuf},
29    sync::{
30        Arc, Mutex,
31        atomic::{AtomicBool, AtomicUsize, Ordering},
32    },
33    time::Duration,
34};
35
36use crate::spawn::container_ipc::ExecSetup;
37use aither_core::llm::tool::{
38    AnyApprover, Approval, ApprovalError, ApprovalKind, ApprovalRequest, Approver,
39};
40use aither_core::llm::{AgentPath, CallIdentity, ToolContext};
41use aither_core::llm::{
42    CommandOutcome, CommandResult, CommandStream, Interruption, IntoToolResult, StoredFile, Tool,
43    ToolResult,
44};
45use aither_core::{AnyIdAllocator, IdLease, IdsExhausted, WeakIdLease};
46use askama::Template;
47use async_channel::{Receiver, Sender};
48use executor_core::{Executor, Task};
49#[cfg(target_os = "linux")]
50use heel::supervisor::{TreeControl, TreeReport};
51use heel::{CpuPriority, IoPriority, NetworkAuditLog, ProcessPriority};
52/// On platforms without `heel supervise` a wait produces no report.
53#[cfg(not(target_os = "linux"))]
54pub struct TreeReport;
55use schemars::JsonSchema;
56use serde::{Deserialize, Serialize};
57use shell_words::split as split_shell_words;
58use tracing::{debug, info, warn};
59
60use crate::builtin::ShellToolSettings;
61use crate::events::{
62    DescendantsKilled, EventSender, JobEnded, JobStarted, LongRunning, ShellEvent, ShellEvents,
63    StdinBlocked, StdinWatchFailed,
64};
65use crate::jobs::Jobs;
66#[cfg(all(unix, feature = "jobserver"))]
67use crate::jobserver::{JobBroker, JobPool, job_broker_channel};
68use crate::{
69    Carry, ContainerPath, MountRoot, OutputTreatment, RemoteLaunch, SandboxMode, ScriptDecision,
70    ScriptDir, ScriptOrigin, ScriptOutcome, ScriptPolicies, ScriptRefusal,
71    interpreter::Interpreter,
72    job_registry::{JobRegistry, JobStatus, TerminalStream, job_registry_channel},
73    limits::{LiveDuration, ShellLimits},
74    output::{MediaResolution, OutputFormat, OutputStore, stored_path},
75    process_tree::{JobProcess, JobTree},
76    shell_session::{ContainerShellRuntime, ShellSessionRegistry},
77    spawn::stdio::{read_chunks, write_chunks},
78    spawn::{
79        Descendants, EnvSource, GrantSnapshot, Grants, LocalSpawn, Pipe, Sandbox, SpawnSpec,
80        Stdio as SpawnStdio, TreeLifetime,
81    },
82    ssh::{SshClient, SshEnvironment, SshServer},
83    stdin_watch::{
84        EpisodeDetector, FeedCounter, LocalStdinProbe, STDIN_WATCH_INTERVAL, StdinWatchSignal,
85    },
86    subagent::{
87        AnySubagentSpaces, CommitLedger, CommittingWorktree, ImportBudget, ImportLimits,
88        LaunchHistory, Launcher, PreparedSpace, ResolvedGrant, RunSpace, Spelling, SubagentGit,
89        SubagentGrant, SubagentGrantError, SubagentSpaces, canonical as canonical_path,
90    },
91};
92
93mod builder;
94mod subagent_git;
95
96pub use builder::{Given, Missing, ShellBuilder};
97
98/// Opens a daily-rotated network audit log under `dir`, creating the directory if needed.
99///
100/// Keeps at most `max_files` rotated files. Attach the log with
101/// [`Sandbox::with_audit_log`] to record every sandboxed
102/// network policy decision.
103///
104/// # Errors
105/// Returns an error when the directory cannot be created or the log cannot
106/// be opened.
107pub async fn open_network_audit_log(
108    dir: impl AsRef<Path>,
109    max_files: usize,
110) -> Result<NetworkAuditLog, TerminalError> {
111    let dir = dir.as_ref();
112    async_fs::create_dir_all(dir).await?;
113    NetworkAuditLog::rolling_daily(dir, max_files).map_err(|error| {
114        TerminalError::SandboxSetup(format!("failed to open network audit log: {error}"))
115    })
116}
117
118fn parse_direct_command(script: &str) -> Result<(String, Vec<String>), TerminalError> {
119    let parts = split_shell_words(script)
120        .map_err(|error| TerminalError::Execution(format!("failed to parse command: {error}")))?;
121    let Some((program, args)) = parts.split_first() else {
122        return Err(TerminalError::Execution(
123            "command must not be empty".to_string(),
124        ));
125    };
126    Ok((program.clone(), args.to_vec()))
127}
128
129enum TerminalLaunch {
130    Direct { program: String, args: Vec<String> },
131    Shell { program: String, args: Vec<String> },
132}
133
134fn script_requires_shell(script: &str) -> bool {
135    let mut in_single = false;
136    let mut in_double = false;
137    let mut escaped = false;
138
139    for ch in script.chars() {
140        if escaped {
141            escaped = false;
142            continue;
143        }
144
145        match ch {
146            '\\' if !in_single => escaped = true,
147            '\'' if !in_double => in_single = !in_single,
148            '"' if !in_single => in_double = !in_double,
149            // Double quotes keep parameter, command and arithmetic expansion.
150            '$' | '`' if !in_single => return true,
151            '\n' | '\r' | '|' | '&' | ';' | '<' | '>' | '(' | ')' | '*' | '?' | '[' | ']' | '{'
152            | '}' | '!' | '~'
153                if !in_single && !in_double =>
154            {
155                return true;
156            }
157            _ => {}
158        }
159    }
160
161    false
162}
163
164fn looks_like_env_assignment(token: &str) -> bool {
165    let Some((name, _value)) = token.split_once('=') else {
166        return false;
167    };
168    !name.is_empty() && name.chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
169}
170
171fn is_shell_builtin(program: &str) -> bool {
172    matches!(
173        program,
174        "alias"
175            | "bg"
176            | "break"
177            | "cd"
178            | "command"
179            | "continue"
180            | "eval"
181            | "exec"
182            | "exit"
183            | "export"
184            | "fg"
185            | "jobs"
186            | "read"
187            | "readonly"
188            | "return"
189            | "set"
190            | "shift"
191            | "source"
192            | "times"
193            | "trap"
194            | "type"
195            | "ulimit"
196            | "umask"
197            | "unalias"
198            | "unset"
199    )
200}
201
202/// The program and arguments that run `script` in a shell. Windows runs
203/// `cmd.exe`; every other platform runs `managed_shell`, the managed bash.
204pub fn shell_launch(managed_shell: &str, script: &str) -> (String, Vec<String>) {
205    #[cfg(windows)]
206    {
207        let _ = managed_shell;
208        let shell = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string());
209        return (shell, vec!["/C".to_string(), script.to_string()]);
210    }
211
212    #[cfg(not(windows))]
213    {
214        (
215            managed_shell.to_string(),
216            crate::spawn::shell_arguments(script),
217        )
218    }
219}
220
221/// The shell script that runs `script`, written in `language`, for the job
222/// `task_id`.
223fn launch_script<'a>(
224    interpreter: Interpreter,
225    script: &'a str,
226    task_id: &str,
227) -> Result<Cow<'a, str>, TerminalError> {
228    interpreter.launch_script(script, task_id).map_err(|error| {
229        TerminalError::Execution(format!("failed to render the launch script: {error}"))
230    })
231}
232
233/// Turns `script` into the process to launch. A shell launch with a `report`
234/// file records the shell's final directory there when it exits; a direct
235/// command cannot change directory, so it reports nothing.
236fn build_terminal_launch(
237    managed_shell: &str,
238    script: &str,
239    report: Option<&Path>,
240) -> Result<TerminalLaunch, TerminalError> {
241    let script = script.trim();
242    if script.is_empty() {
243        return Err(TerminalError::Execution(
244            "command must not be empty".to_string(),
245        ));
246    }
247
248    match direct_command(script)? {
249        Some((program, args)) => Ok(TerminalLaunch::Direct { program, args }),
250        None => shell_launch_reporting(managed_shell, script, report),
251    }
252}
253
254/// The program and arguments of a script that runs without a shell, or
255/// `None` when it needs one.
256fn direct_command(script: &str) -> Result<Option<(String, Vec<String>)>, TerminalError> {
257    if script_requires_shell(script) {
258        return Ok(None);
259    }
260    let (program, args) = parse_direct_command(script)?;
261    if looks_like_env_assignment(&program) || is_shell_builtin(&program) {
262        return Ok(None);
263    }
264    Ok(Some((program, args)))
265}
266
267/// Whether a local launch of `script` runs in a shell, the only way a
268/// command can change directory.
269fn runs_in_shell(script: &str) -> bool {
270    matches!(direct_command(script.trim()), Ok(None))
271}
272
273/// A command killed because its `timeout` bound passed, with the UTC times it
274/// started and was killed at.
275///
276/// [`ShellWording::command_killed`](crate::ShellWording::command_killed)
277/// renders the sentence the model reads.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub struct TimeoutKill {
280    /// The `timeout` the command was bounded by.
281    pub timeout: Duration,
282    /// When the command started.
283    pub started: jiff::Timestamp,
284    /// When the kill was issued.
285    pub killed: jiff::Timestamp,
286}
287
288#[derive(Template)]
289#[template(path = "carry_cwd.sh", escape = "none")]
290struct CarryCwdTemplate<'a> {
291    escaped_report: &'a str,
292    escaped_script: &'a str,
293}
294
295fn shell_launch_reporting(
296    managed_shell: &str,
297    script: &str,
298    report: Option<&Path>,
299) -> Result<TerminalLaunch, TerminalError> {
300    let Some(report) = report else {
301        let (program, args) = shell_launch(managed_shell, script);
302        return Ok(TerminalLaunch::Shell { program, args });
303    };
304    let script = carry_cwd_script(script, &report.to_string_lossy())?;
305    let (program, args) = shell_launch(managed_shell, &script);
306    Ok(TerminalLaunch::Shell { program, args })
307}
308
309/// `script`, run through `eval`, followed by a trailer that writes the
310/// shell's final directory to `report`, a path as the shell sees it, and
311/// exits with the script's status.
312///
313/// The report is not written from an `EXIT` trap: setting one makes a
314/// non-interactive bash catch SIGTERM, and a child it has just forked still
315/// carries that handler until it resets its signals, so a `kill` sent in that
316/// window is swallowed and the process it names runs on. `eval` keeps the
317/// trailer out of reach of the script's own syntax, such as an unterminated
318/// here-document. A script that ends through `exit` writes no report.
319fn carry_cwd_script(script: &str, report: &str) -> Result<String, TerminalError> {
320    let escaped_report = shell_escape(report);
321    let escaped_script = shell_escape(script);
322    CarryCwdTemplate {
323        escaped_report: &escaped_report,
324        escaped_script: &escaped_script,
325    }
326    .render()
327    .map_err(|error| {
328        TerminalError::Execution(format!("failed to render directory report: {error}"))
329    })
330}
331
332// The arguments of the shell tool. They carry no rustdoc: the schema's
333// descriptions are the embedder's, supplied by the tool's `ToolIdentity`.
334#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
335#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
336pub struct ShellArgs {
337    // A short explanation of what the command does, shown instead of its source.
338    pub description: String,
339
340    // The source to run.
341    pub script: String,
342
343    // The interpreter of `script`.
344    #[serde(default)]
345    pub interpreter: Interpreter,
346
347    // Whether the command runs inside the sandbox.
348    #[serde(default)]
349    pub sandbox: SandboxMode,
350
351    // Where the command runs: the home environment, or a named SSH server.
352    #[serde(default)]
353    pub location: Option<String>,
354
355    // The resolution media in the output is delivered at.
356    #[serde(default)]
357    pub resolution: MediaResolution,
358
359    // The most output lines returned inline.
360    #[serde(default)]
361    pub max_lines: Option<u32>,
362
363    // Whether the output is returned verbatim, without compression.
364    #[serde(default)]
365    pub raw: bool,
366
367    // The command's maximum runtime in seconds.
368    pub timeout: u64,
369
370    // Whether the command is detached at once instead of waited for.
371    #[serde(default)]
372    pub background: bool,
373}
374
375/// Time bounds applied to every execution this terminal spawns.
376#[derive(Debug, Clone)]
377struct TerminalLimits {
378    /// Foreground wait before a `terminal` call promotes to a background
379    /// task.
380    foreground_wait: ForegroundWait,
381    /// Maximum accepted `timeout` for a command.
382    timeout_cap: LiveDuration,
383    /// Runtime after which a background job produces a long-running alert.
384    long_job_alert: LiveDuration,
385    /// Most bytes a subagent's sandbox may send while its commits are
386    /// imported; shared with every terminal derived from this one, and
387    /// adjustable at runtime.
388    subagent_import: ImportBudget,
389    /// How long the agent has to act on a final memory warning; adjustable
390    /// at runtime and shared with every terminal derived from this one.
391    response_window: ResponseWindow,
392    /// Reads what the terminal's jobs hold of the machine's memory.
393    footprints: AnyFootprintReader,
394    /// Shares the total the agent's jobs hold with the machine's other
395    /// agents; `None` when the embedder configured no registry.
396    footprint_registry: Option<AnyFootprintRegistry>,
397}
398
399impl TerminalLimits {
400    fn new(limits: ShellLimits) -> Self {
401        Self {
402            response_window: limits.response_window,
403            footprints: AnyFootprintReader::new(SystemFootprints),
404            footprint_registry: None,
405            foreground_wait: limits.foreground_wait,
406            timeout_cap: limits.timeout_cap,
407            long_job_alert: limits.long_job_alert,
408            subagent_import: limits.subagent_import,
409        }
410    }
411}
412
413/// Why the next foreground command does not start where the last one left
414/// the shell.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum DirectoryResetReason {
417    /// The command failed, so the directory it ended in is not carried.
418    Failed,
419    /// The command ended through `exit` or a signal and reported no
420    /// directory.
421    Unreported,
422    /// The directory it ended in lies outside the paths the terminal may
423    /// read.
424    OutsideReadable,
425    /// The directory it ended in lies outside the container's workspace
426    /// mount.
427    OutsideWorkspace,
428    /// The directory no longer exists.
429    Removed,
430}
431
432/// A command that ran to completion.
433#[derive(Debug, Clone)]
434pub struct CompletedCommand {
435    /// stdout output.
436    pub stdout: CommandStream,
437
438    /// stderr output (if non-empty).
439    pub stderr: Option<CommandStream>,
440
441    /// Exit code of the script.
442    pub exit_code: i32,
443
444    /// Sleep and offline intervals the command ran through.
445    pub interruptions: Vec<Interruption>,
446}
447
448impl CompletedCommand {
449    /// The command as a result: it exited with its code, or was killed for
450    /// `killed`.
451    fn into_script_result(self, killed: Option<crate::KillCause>) -> crate::ScriptResult {
452        crate::ScriptResult {
453            stdout: self.stdout,
454            stderr: self.stderr,
455            outcome: killed.map_or(
456                crate::RunOutcome::Exited {
457                    code: self.exit_code,
458                },
459                crate::RunOutcome::Killed,
460            ),
461            interruptions: self.interruptions,
462        }
463    }
464}
465
466#[derive(Clone)]
467struct BackgroundStartup {
468    tx: async_channel::Sender<Result<(), String>>,
469    reported: Arc<AtomicBool>,
470    /// Closed once the startup was reported or every clone is gone: nothing
471    /// is sent on it.
472    settled: async_channel::Sender<()>,
473    settled_rx: Receiver<()>,
474}
475
476impl BackgroundStartup {
477    fn new(tx: async_channel::Sender<Result<(), String>>) -> Self {
478        let (settled, settled_rx) = async_channel::bounded(1);
479        Self {
480            tx,
481            reported: Arc::new(AtomicBool::new(false)),
482            settled,
483            settled_rx,
484        }
485    }
486
487    /// Resolves once the job registered, or failed to start.
488    fn settled(&self) -> Receiver<()> {
489        self.settled_rx.clone()
490    }
491
492    async fn report_ready(&self) {
493        if self
494            .reported
495            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
496            .is_ok()
497        {
498            let _ = self.tx.send(Ok(())).await;
499            self.settled.close();
500        }
501    }
502
503    async fn report_failure(&self, error: &TerminalError) {
504        if self
505            .reported
506            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
507            .is_ok()
508        {
509            let _ = self.tx.send(Err(error.detail().into_owned())).await;
510            self.settled.close();
511        }
512    }
513}
514
515/// A script [`Shell::run`] runs to its end.
516#[derive(Debug, Clone)]
517pub struct Script {
518    /// The script's source, in the shell's own interpreter.
519    pub source: String,
520    /// Where it starts: a host path, which for a container shell lies in its
521    /// workspace mount.
522    pub dir: PathBuf,
523    /// The bound after which the script and its process tree are killed.
524    pub timeout: Duration,
525    /// Whether it runs inside the sandbox; an unsandboxed script is put to
526    /// the shell's policies like any other.
527    pub sandbox: SandboxMode,
528}
529
530impl Script {
531    /// `source`, started in `dir` and killed with its process tree once
532    /// `timeout` passes, in [`SandboxMode::Sandboxed`].
533    #[must_use]
534    pub fn new(source: impl Into<String>, dir: impl Into<PathBuf>, timeout: Duration) -> Self {
535        Self {
536            source: source.into(),
537            dir: dir.into(),
538            timeout,
539            sandbox: SandboxMode::Sandboxed,
540        }
541    }
542
543    /// The same script run in `sandbox`.
544    #[must_use]
545    pub const fn with_sandbox(mut self, sandbox: SandboxMode) -> Self {
546        self.sandbox = sandbox;
547        self
548    }
549}
550
551/// Why a [`Shell::run`] did not run to an end.
552///
553/// The variants carry the facts; the `Display` texts are for logs and
554/// diagnostics, and the model never reads them: the tool boundary words a
555/// failure through [`ShellWording::run_failure`] and
556/// [`ShellWording::call_refused`].
557#[derive(Debug, thiserror::Error)]
558#[non_exhaustive]
559pub enum ShellRunError {
560    /// The timeout is zero or above the terminal's cap.
561    #[error("timeout must be between 1 and {} seconds", .cap.as_secs())]
562    Timeout {
563        /// The longest timeout the terminal accepts.
564        cap: Duration,
565    },
566    /// A command policy refused the script.
567    #[error(transparent)]
568    Refused(ScriptRefusal),
569    /// The terminal runs in a container that declares no workspace mount,
570    /// so no host directory maps into it.
571    #[error("the container declares no workspace mount, so a run cannot start in a host directory")]
572    NoWorkspaceMount,
573    /// The working directory lies outside the container's workspace mount.
574    #[error(transparent)]
575    OutsideWorkspace(#[from] crate::MountRootError),
576    /// The terminal could not run the script: no backend for its mode, a
577    /// refused permission or a failed execution.
578    #[error(transparent)]
579    Terminal(#[from] TerminalError),
580    /// Every model-facing id is leased, so the command has no task id.
581    #[error(transparent)]
582    Ids(#[from] IdsExhausted),
583}
584
585impl ShellRunError {
586    /// The error a tool call answers with: a refusal stays typed so the agent
587    /// loop recognises it, every other failure is worded by `wording`.
588    pub(crate) fn into_tool_error(self, wording: &dyn ShellWording) -> anyhow::Error {
589        let failure = match self {
590            Self::Refused(refusal) => return anyhow::Error::from(refusal),
591            Self::Timeout { cap } => {
592                return crate::Refused::call(wording, CallRefusal::TimeoutOutOfRange { cap });
593            }
594            Self::NoWorkspaceMount => RunFailure::NoWorkspaceMount,
595            Self::OutsideWorkspace(ref error) => RunFailure::OutsideWorkspace(error),
596            Self::Terminal(ref error) => RunFailure::Terminal(error),
597            Self::Ids(_) => RunFailure::IdsExhausted,
598        };
599        anyhow::Error::msg(wording.run_failure(&failure))
600    }
601}
602
603/// Kills the running jobs of a registry when dropped.
604///
605/// `Drop` cannot await, so the kill runs as a task the terminal's executor
606/// spawns.
607struct KillJobsOnDrop {
608    registry: JobRegistry,
609    /// Spawns the kill of the registry's jobs on the terminal's executor.
610    spawn_kill: Box<dyn Fn(JobRegistry) + Send + Sync>,
611}
612
613impl KillJobsOnDrop {
614    fn new<E>(registry: JobRegistry, executor: E) -> Self
615    where
616        E: Executor + 'static,
617    {
618        Self {
619            registry,
620            spawn_kill: Box::new(move |registry| {
621                executor
622                    .spawn(async move {
623                        registry.kill_running().await;
624                    })
625                    .detach();
626            }),
627        }
628    }
629}
630
631impl Drop for KillJobsOnDrop {
632    fn drop(&mut self) {
633        (self.spawn_kill)(self.registry.clone());
634    }
635}
636
637impl std::fmt::Debug for KillJobsOnDrop {
638    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
639        f.debug_struct("KillJobsOnDrop").finish_non_exhaustive()
640    }
641}
642
643/// What a subagent's terminal holds that the main agent's does not.
644#[derive(Clone, Debug)]
645struct SubagentAuthority {
646    /// Kills the subagent's running jobs when the last handle of its terminal
647    /// goes. Only a subagent's terminal holds one: the main agent's jobs
648    /// outlive its terminal, so an embedder can rebuild it with its
649    /// background commands still running.
650    _jobs: Arc<KillJobsOnDrop>,
651    /// Keeps the word naming its space leased while the terminal lives.
652    _space_name: IdLease,
653    /// The worktrees it may commit in, with their git data; it hands on no
654    /// other commit grant.
655    committing: Vec<CommittingWorktree>,
656    /// Runs git in its sandbox, as it, for the host's view of its commits.
657    git: SubagentGit,
658    /// What the launcher's [`SubagentSpaces`] made in its space; `None` when
659    /// the launcher has none.
660    prepared: Option<PreparedSpace>,
661}
662
663/// A subagent launch whose grant is resolved: everything the launch still
664/// needs from what the launching terminal handed out.
665struct ResolvedLaunch {
666    /// The launching terminal's working directory and grants, canonical.
667    authority: Vec<PathBuf>,
668    /// Where the subagent's space goes.
669    spaces_root: PathBuf,
670    /// The container workspace mount, for a container terminal.
671    mount: Option<MountRoot>,
672    granted: ResolvedGrant,
673}
674
675/// The main agent's working directory, carried from one foreground command
676/// to the next. `None` inside means the terminal's own working directory.
677#[derive(Clone, Default)]
678struct CarriedDir(Arc<Mutex<Option<PathBuf>>>);
679
680impl CarriedDir {
681    fn get(&self) -> Option<PathBuf> {
682        self.0.lock().expect("carried directory lock").clone()
683    }
684
685    fn set(&self, dir: Option<PathBuf>) {
686        *self.0.lock().expect("carried directory lock") = dir;
687    }
688
689    /// Records `moved_to` when there is one and returns the directory carried
690    /// afterwards, under one lock: the directory the next foreground script
691    /// starts in is the one returned here, whatever scripts settle beside
692    /// this one.
693    fn settle(&self, moved_to: Option<PathBuf>) -> Option<PathBuf> {
694        let mut carried = self.0.lock().expect("carried directory lock");
695        if moved_to.is_some() {
696            *carried = moved_to;
697        }
698        carried.clone()
699    }
700}
701
702/// Where a command starts, and for a foreground command of the main agent,
703/// the report of the directory it ended in.
704#[derive(Clone)]
705struct CwdCarry {
706    /// Where the command starts.
707    start: Option<PathBuf>,
708    /// The file the command's shell writes its final directory to when it
709    /// exits; `None` for a command that carries no directory, such as a
710    /// script [`Shell::run`] runs.
711    report: Option<PathBuf>,
712    /// Set for a container command: the workspace mount that maps the host
713    /// paths above into the container and back.
714    container: Option<ContainerCarry>,
715    /// Whether the command runs in a shell and so writes the report; a
716    /// direct command cannot change directory and writes none.
717    shell: bool,
718    /// Whether the directory carried to this command no longer existed, so
719    /// the command starts in the terminal's own directory instead.
720    removed: bool,
721}
722
723/// How a container command spells its start and directory report.
724#[derive(Clone)]
725struct ContainerCarry {
726    mount: MountRoot,
727    /// Where the container sees the report file, when there is one.
728    report: Option<ContainerPath>,
729    /// Where the command starts inside the container.
730    start: ContainerPath,
731}
732
733/// The terminal tool for executing scripts in a sandbox.
734///
735/// Creates a shared working directory that persists across all executions,
736/// named by heel with four random words; that name is not one of the leased
737/// model-facing ids. Each execution creates a fresh sandbox but shares the
738/// working directory.
739pub struct Shell<E> {
740    /// Shared working directory, named by heel with four random words (e.g.,
741    /// `amber-forest-thunder-pearl/`) rather than a leased id.
742    working_dir: PathBuf,
743    /// The SSH servers scripts may name as their `location`.
744    sessions: ShellSessionRegistry,
745    /// Approves what no call's context can: a script run with no tool call
746    /// to ask through. Shared with the subagents' terminals.
747    approver: Option<AnyApprover>,
748    executor: E,
749    /// Leases the words naming what the model addresses: task ids, stored
750    /// outputs and subagent spaces. Shared with the output store and every
751    /// subagent terminal launched from this one.
752    ids: AnyIdAllocator,
753    output_store: OutputStore,
754    job_registry: JobRegistry,
755    /// Where the facts about this shell's jobs are raised (cloned for each
756    /// task that reports one).
757    events_tx: EventSender,
758    /// Where they are read.
759    events_rx: ShellEvents,
760    /// What the shell tool and the job control tools are named and
761    /// described as.
762    job_tools: ShellToolSettings,
763    /// The interpreters a script may run under.
764    interpreters: Arc<[Interpreter]>,
765    /// Time bounds applied to spawned executions.
766    limits: TerminalLimits,
767    /// Number of still-running spawned executions associated with this tool.
768    running_tasks: Arc<AtomicUsize>,
769    /// The sandbox this shell's scripts run in: its grants, which every clone
770    /// shares and commands snapshot at launch, environment source, network
771    /// policy, priority, backend and `heel`. Each job runs in a copy of it
772    /// with what the job adds.
773    sandbox: Sandbox,
774    /// Set on a subagent's terminal, never on the main agent's.
775    subagent: Option<SubagentAuthority>,
776    /// The working directory the next foreground command starts in; held on
777    /// the main agent's terminal only, a subagent's commands always start in
778    /// its own space.
779    carried_dir: Option<CarriedDir>,
780    /// Shared jobserver token broker, when configured.
781    #[cfg(all(unix, feature = "jobserver"))]
782    jobserver: Option<JobBroker>,
783    /// Records the outages commands run through.
784    outages: Outages,
785    /// Prepares the space of every subagent launched from this terminal and,
786    /// at any depth, from theirs.
787    subagent_spaces: Option<AnySubagentSpaces>,
788    /// The script policies every script of this shell is put to, bound to
789    /// the state of the agent the shell serves.
790    policies: ScriptPolicies,
791    /// Chooses each script's output treatment, shared with every subagent
792    /// shell derived from this one; without it every output is command
793    /// output.
794    treat_output: Option<crate::output_treatment::AnyTreatOutput>,
795    /// The commands the embedder serves to this shell's scripts, shared with
796    /// every subagent shell derived from this one.
797    ipc: Option<crate::AnyIpcProvider>,
798    /// The worktrees this shell's subagents were granted commit in so far,
799    /// in grant order: the map the host's `git` shim reads. Shared with
800    /// every subagent shell derived from this one.
801    committed: Arc<Mutex<Vec<CommittingWorktree>>>,
802    /// What this shell handed its subagents, so no grant exceeds an earlier
803    /// one's claim; launches resolve one at a time.
804    launches: Arc<async_lock::Mutex<LaunchHistory>>,
805    /// The shell scripts run under when the sandbox runs on the host; `None`
806    /// on a container, whose launch names it.
807    host_launch: Option<crate::HostLaunch>,
808}
809
810impl<E: Clone> Clone for Shell<E> {
811    fn clone(&self) -> Self {
812        Self {
813            working_dir: self.working_dir.clone(),
814            sessions: self.sessions.clone(),
815            approver: self.approver.clone(),
816            executor: self.executor.clone(),
817            ids: self.ids.clone(),
818            output_store: self.output_store.clone(),
819            job_registry: self.job_registry.clone(),
820            events_tx: self.events_tx.clone(),
821            events_rx: self.events_rx.clone(),
822            job_tools: self.job_tools.clone(),
823            interpreters: self.interpreters.clone(),
824            limits: self.limits.clone(),
825            running_tasks: self.running_tasks.clone(),
826            sandbox: self.sandbox.clone(),
827            subagent: self.subagent.clone(),
828            carried_dir: self.carried_dir.clone(),
829            #[cfg(all(unix, feature = "jobserver"))]
830            jobserver: self.jobserver.clone(),
831            outages: self.outages.clone(),
832            subagent_spaces: self.subagent_spaces.clone(),
833            policies: self.policies.clone(),
834            treat_output: self.treat_output.clone(),
835            ipc: self.ipc.clone(),
836            committed: self.committed.clone(),
837            launches: self.launches.clone(),
838            host_launch: self.host_launch.clone(),
839        }
840    }
841}
842
843impl<E: Executor + Clone + 'static> Shell<E> {
844    /// Sets the approver that answers the approvals of scripts no tool call
845    /// carries ([`Shell::run`] and [`Self::run_background`]), and
846    /// of calls whose dispatcher attached none. Without one, such a script
847    /// that needs approval does not run.
848    #[must_use]
849    pub fn with_approver(mut self, approver: impl Approver) -> Self {
850        self.approver = Some(AnyApprover::new(approver));
851        self
852    }
853
854    /// Serves the SSH servers of `sessions` as the locations scripts may
855    /// name. Registries share their server set, so terminals given clones of
856    /// one see the same servers.
857    #[must_use]
858    pub fn with_shell_sessions(mut self, sessions: ShellSessionRegistry) -> Self {
859        self.sessions = sessions;
860        self
861    }
862
863    /// Has `spaces` prepare the space of every subagent launched from this
864    /// terminal and, at any depth, from theirs, before the subagent's
865    /// terminal exists. A launch whose space cannot be prepared fails with
866    /// the error `spaces` gives.
867    #[must_use]
868    pub fn with_subagent_spaces(mut self, spaces: impl SubagentSpaces) -> Self {
869        self.subagent_spaces = Some(AnySubagentSpaces::new(spaces));
870        self
871    }
872
873    /// Leases every word this terminal names something with for the model —
874    /// a command's task id, a stored output's file name, a subagent's space —
875    /// from `ids`, as do the subagent terminals launched from it and the
876    /// `subagent` command bound to it. A terminal given none leases from its
877    /// own [`AnyIdAllocator::default`].
878    #[must_use]
879    pub fn with_id_allocator(mut self, ids: AnyIdAllocator) -> Self {
880        self.output_store = OutputStore::at(
881            self.output_store.dir().to_path_buf(),
882            ids.clone(),
883            self.output_store.policy().clone(),
884            self.output_store.wording().clone(),
885        );
886        self.ids = ids;
887        self
888    }
889
890    /// Creates a shell whose scripts run in `sandbox`, working in its
891    /// working directory itself.
892    ///
893    /// # Errors
894    /// Returns an error when the working directory or output store cannot be
895    /// created, or when the sandbox runs its processes on an SSH server: a
896    /// server is a location a script names, not a shell's home.
897    pub(crate) async fn from_parts(
898        sandbox: Sandbox,
899        executor: E,
900        parts: builder::ShellParts,
901    ) -> Result<Self, TerminalError> {
902        match (sandbox.backend(), &parts.host_shell) {
903            (Backend::Ssh { server, .. }, _) => {
904                return Err(TerminalError::SandboxSetup(format!(
905                    "the sandbox runs on the SSH server {}: a server is a location, not a shell's home",
906                    server.name
907                )));
908            }
909            (Backend::Host { .. }, None) => {
910                return Err(TerminalError::SandboxSetup(
911                    "a shell on the host needs its host shell: build it with `Shell::builder_on_host`"
912                        .into(),
913                ));
914            }
915            (Backend::Container { .. }, Some(_)) => {
916                return Err(TerminalError::SandboxSetup(
917                    "a host shell was given to a shell on a container, which runs the shell its launch names"
918                        .into(),
919                ));
920            }
921            (Backend::Host { .. }, Some(_)) | (Backend::Container { .. }, None) => {}
922        }
923        // Ensure working directory exists, then resolve it once: heel and the
924        // directory report both use this spelling, and a symlink in the given
925        // one is not necessarily granted inside the sandbox.
926        async_fs::create_dir_all(sandbox.working_dir()).await?;
927        let working_dir_path =
928            dunce::simplified(&async_fs::canonicalize(sandbox.working_dir()).await?).to_path_buf();
929
930        // Create outputs directory inside working dir
931        let ids = AnyIdAllocator::default();
932        let output_store = OutputStore::new(
933            working_dir_path.join("outputs"),
934            ids.clone(),
935            parts.output,
936            parts.wording,
937        )
938        .await?;
939
940        // Start job registry service
941        let (job_registry, job_registry_service) =
942            job_registry_channel(output_store.policy().clone());
943        executor
944            .spawn(async move { job_registry_service.serve().await })
945            .detach();
946
947        let events_rx = parts.events.unwrap_or_default();
948        let events_tx = events_rx.sender(AgentPath::main());
949        let running_tasks = Arc::new(AtomicUsize::new(0));
950        let sandbox = sandbox
951            .with_working_dir(working_dir_path.clone())
952            .with_scanner(job_registry.scanner());
953
954        Ok(Self {
955            working_dir: working_dir_path,
956            sessions: ShellSessionRegistry::default(),
957            approver: None,
958            executor,
959            ids,
960            output_store,
961            job_registry,
962            events_tx,
963            events_rx,
964            job_tools: parts.tools,
965            interpreters: parts.interpreters.into(),
966            limits: TerminalLimits::new(parts.limits),
967            running_tasks,
968            sandbox,
969            subagent: None,
970            carried_dir: Some(CarriedDir::default()),
971            #[cfg(all(unix, feature = "jobserver"))]
972            jobserver: None,
973            outages: Outages::none(),
974            subagent_spaces: None,
975            policies: ScriptPolicies::new(parts.policies),
976            treat_output: parts.treat_output,
977            ipc: parts.ipc,
978            committed: Arc::new(Mutex::new(Vec::new())),
979            launches: Arc::default(),
980            host_launch: parts.host_shell,
981        })
982    }
983
984    /// A shell on the host in `working_dir` under the test `heel`, with
985    /// shell and Python configured and nothing granted.
986    #[cfg(test)]
987    pub(crate) async fn new_exact(
988        working_dir: impl AsRef<std::path::Path>,
989        executor: E,
990        limits: ShellLimits,
991        output: OutputPolicy,
992        wording: AnyShellWording,
993        tools: ShellToolSettings,
994    ) -> Result<Self, TerminalError> {
995        let heel = crate::test_heel::binary().await.expect("a test heel");
996        let sandbox = Sandbox::new(
997            Backend::Host { heel },
998            executor.clone(),
999            working_dir.as_ref(),
1000        );
1001        Self::new_exact_on(sandbox, executor, limits, output, wording, tools).await
1002    }
1003
1004    /// A shell running in `sandbox`, with shell and Python configured.
1005    #[cfg(test)]
1006    pub(crate) async fn new_exact_on(
1007        sandbox: Sandbox,
1008        executor: E,
1009        limits: ShellLimits,
1010        output: OutputPolicy,
1011        wording: AnyShellWording,
1012        tools: ShellToolSettings,
1013    ) -> Result<Self, TerminalError> {
1014        let host_shell = matches!(sandbox.backend(), Backend::Host { .. })
1015            .then(|| crate::HostLaunch::new(TEST_HOST_SHELL));
1016        Self::from_parts(
1017            sandbox,
1018            executor,
1019            builder::ShellParts {
1020                interpreters: vec![Interpreter::Shell, Interpreter::Python],
1021                limits,
1022                output,
1023                wording,
1024                tools,
1025                events: None,
1026                policies: Vec::new(),
1027                ipc: None,
1028                treat_output: None,
1029                host_shell,
1030            },
1031        )
1032        .await
1033    }
1034
1035    /// The sandbox this shell's scripts run in, so an embedder that built the
1036    /// shell spawns its own processes in the same sandbox: the same live
1037    /// grants, environment source, network policy and backend.
1038    #[must_use]
1039    pub const fn sandbox(&self) -> &Sandbox {
1040        &self.sandbox
1041    }
1042}
1043
1044/// The shell program the tests' host shells run scripts under.
1045#[cfg(test)]
1046const TEST_HOST_SHELL: &str = "/bin/bash";
1047
1048#[cfg(test)]
1049impl<E> Shell<E>
1050where
1051    E: Executor + Clone + 'static,
1052{
1053    /// This shell with `policies` as its script policies, in place of the
1054    /// ones it was built with.
1055    fn with_test_policies(mut self, policies: Vec<crate::AnyScriptPolicy>) -> Self {
1056        self.policies = ScriptPolicies::new(policies);
1057        self
1058    }
1059
1060    /// A subagent terminal with an empty grant.
1061    async fn subagent_without_grant(&self) -> Result<Self, SubagentGrantError> {
1062        self.subagent(SubagentGrant::new(), None, "worker").await
1063    }
1064}
1065
1066impl<E> Shell<E>
1067where
1068    E: Executor + Clone + 'static,
1069{
1070    /// Shares a jobserver token pool across every command this tool runs.
1071    ///
1072    /// `pool` is the host-provided shared pool (a `fifo:` jobserver). Each
1073    /// command — foreground or background — gets its own fifo beneath
1074    /// `fifo_dir` (created if missing, broker-owned, kept out of command
1075    /// working directories), exported through
1076    /// `MAKEFLAGS=--jobserver-auth=fifo:PATH`. The broker moves tokens
1077    /// between the pool and each fifo on demand and returns every token
1078    /// once the command's whole process tree is gone: the fifo's read end
1079    /// reports EOF only when its last writer — including surviving
1080    /// grandchildren — has exited. Commands never see the shared pool
1081    /// directly, so killed commands cannot leak tokens.
1082    ///
1083    /// A container command's fifo is made inside the container, where its
1084    /// `MAKEFLAGS` names it, and brokered against the same pool by a relay
1085    /// run with the image's managed `python3`, with the same accounting. An
1086    /// SSH command runs on another machine, outside the pool: it takes no
1087    /// token and gets no fifo.
1088    ///
1089    /// # Errors
1090    /// Returns an error when the fifo directory cannot be created or the
1091    /// broker's readiness poller cannot be set up.
1092    #[cfg(all(unix, feature = "jobserver"))]
1093    pub fn with_jobserver_pool(
1094        mut self,
1095        pool: JobPool,
1096        fifo_dir: impl AsRef<Path>,
1097    ) -> Result<Self, TerminalError> {
1098        let (broker, service) = job_broker_channel(pool, fifo_dir)?;
1099        self.executor
1100            .spawn(async move { service.serve().await })
1101            .detach();
1102        self.jobserver = Some(broker);
1103        Ok(self)
1104    }
1105
1106    /// A handle on the foreground window, shared with every terminal derived
1107    /// from this one: a longer window put in force through it applies to the
1108    /// next foreground wait of each of them.
1109    #[must_use]
1110    pub fn foreground_wait(&self) -> ForegroundWait {
1111        self.limits.foreground_wait.clone()
1112    }
1113
1114    /// A handle on the response window, shared with every terminal derived
1115    /// from this one: a window set through it applies to the next final
1116    /// warning of each of them.
1117    #[must_use]
1118    pub fn response_window(&self) -> ResponseWindow {
1119        self.limits.response_window.clone()
1120    }
1121
1122    /// Reads job footprints and the machine's physical memory through
1123    /// `reader` instead of the platform's own.
1124    #[must_use]
1125    pub fn with_footprint_reader(mut self, reader: impl FootprintReader) -> Self {
1126        self.limits.footprints = AnyFootprintReader::new(reader);
1127        self
1128    }
1129
1130    /// Shares the memory this terminal's jobs hold with the machine's other
1131    /// agents through `registry`, so a final warning can name the agent that
1132    /// contributes the most when all agents together exceed physical memory.
1133    #[must_use]
1134    pub fn with_footprint_registry(mut self, registry: impl FootprintRegistry) -> Self {
1135        self.limits.footprint_registry = Some(AnyFootprintRegistry::new(registry));
1136        self
1137    }
1138
1139    /// The memory the terminal's jobs hold, for a guard that warns about and
1140    /// kills a runaway job.
1141    #[must_use]
1142    ///
1143    /// The machine the embedder runs on is always judged. When the terminal
1144    /// runs in a container, the container's own memory limit is judged too,
1145    /// read inside the container. Jobs of a remote execution environment are
1146    /// never judged.
1147    pub fn job_memory(&self) -> JobMemory {
1148        let memory = JobMemory::new(
1149            self.job_registry(),
1150            self.limits.footprints.clone(),
1151            self.limits.footprint_registry.clone(),
1152            self.limits.response_window.clone(),
1153        );
1154        match self.container_probe() {
1155            Some(probe) => {
1156                memory.with_container(AnyContainerMemory::new(ProbedContainerMemory::new(probe)))
1157            }
1158            None => memory,
1159        }
1160    }
1161
1162    /// A reader of the container the agent works in, when the terminal's
1163    /// home environment is a container; `None` when it is the local
1164    /// machine. A remote execution environment is never a home environment.
1165    #[must_use]
1166    pub fn container_probe(&self) -> Option<crate::ContainerProbe> {
1167        match self.sandbox.backend() {
1168            Backend::Container { runtime, .. } => Some(runtime.probe()),
1169            Backend::Host { .. } | Backend::Ssh { .. } => None,
1170        }
1171    }
1172
1173    /// A handle on the most bytes a subagent's sandbox may send the host
1174    /// while its commits are imported, shared with every subagent this
1175    /// terminal launches: a change through it applies to the next import of
1176    /// each of them.
1177    #[must_use]
1178    pub fn subagent_import_budget(&self) -> ImportBudget {
1179        self.limits.subagent_import.clone()
1180    }
1181
1182    /// Records the sleep and offline intervals `connectivity` reports during
1183    /// each command, and states them in the command's result and, for a
1184    /// background job, its completion alert.
1185    ///
1186    /// Terminals launched for subagents share the record. Only commands that
1187    /// start after this call are recorded.
1188    #[cfg(feature = "connectivity")]
1189    #[must_use]
1190    pub fn with_connectivity(mut self, connectivity: &aither_connectivity::Connectivity) -> Self {
1191        self.outages = Outages::watching(connectivity, &self.executor);
1192        self
1193    }
1194
1195    /// The SSH servers scripts may name as their `location`, shared with
1196    /// child terminals.
1197    #[must_use]
1198    pub const fn shell_sessions(&self) -> &ShellSessionRegistry {
1199        &self.sessions
1200    }
1201
1202    /// Returns the working directory path.
1203    pub const fn working_dir(&self) -> &PathBuf {
1204        &self.working_dir
1205    }
1206
1207    /// Returns the outputs directory path.
1208    pub fn outputs_dir(&self) -> PathBuf {
1209        self.working_dir.join("outputs")
1210    }
1211
1212    /// Returns the output store.
1213    pub const fn output_store(&self) -> &OutputStore {
1214        &self.output_store
1215    }
1216
1217    /// The allocator this terminal leases its model-facing ids from.
1218    pub const fn id_allocator(&self) -> &AnyIdAllocator {
1219        &self.ids
1220    }
1221
1222    /// The job registry handle.
1223    pub(crate) fn job_registry(&self) -> JobRegistry {
1224        self.job_registry.clone()
1225    }
1226
1227    /// The largest `timeout` a script of this shell accepts now.
1228    pub(crate) fn timeout_cap(&self) -> Duration {
1229        self.limits.timeout_cap.get()
1230    }
1231
1232    /// This terminal's jobs.
1233    #[must_use]
1234    pub fn jobs(&self) -> Jobs {
1235        Jobs::new(
1236            self.job_registry(),
1237            self.events(),
1238            self.output_store.clone(),
1239        )
1240    }
1241
1242    /// What a watch task reports through; `monitor` clones it for every pump
1243    /// it spawns.
1244    pub(crate) fn event_sender(&self) -> EventSender {
1245        self.events_tx.clone()
1246    }
1247
1248    /// The executor backing this terminal, for spawning watch tasks.
1249    pub const fn executor(&self) -> &E {
1250        &self.executor
1251    }
1252
1253    /// Paths mounted readable for commands, besides the working directory.
1254    /// The shared runtime grant handle: adding a grant through it affects
1255    /// every command launched afterwards, on this terminal and its clones.
1256    pub fn grants(&self) -> Grants {
1257        self.sandbox.grants().clone()
1258    }
1259
1260    ///
1261    /// The facts about this terminal's jobs. Every handle shares the queues,
1262    /// so an event reaches one reader.
1263    pub fn events(&self) -> ShellEvents {
1264        self.events_rx.clone()
1265    }
1266
1267    /// The events as tests read them.
1268    #[cfg(test)]
1269    pub(crate) fn background_receiver(&self) -> ShellEvents {
1270        self.events()
1271    }
1272}
1273
1274/// The directory, inside a launching terminal's working directory, that holds
1275/// the spaces of the subagents it launches.
1276const SUBAGENT_SPACES_DIR: &str = "subagent-spaces";
1277
1278impl<E> Shell<E>
1279where
1280    E: Executor + Clone + 'static,
1281{
1282    /// Launches the shell of a subagent: it runs in a space of its own
1283    /// inside this shell's working directory and never exceeds this shell's
1284    /// authority.
1285    ///
1286    /// `grant` is everything the subagent may write beyond its space, and
1287    /// must lie inside what this shell can write. When this shell has
1288    /// [`SubagentSpaces`], they prepare the space first and are told
1289    /// `caller`, the directory the launch is asked for from (this shell's
1290    /// working directory when `None`). Grants are resolved one at a time, so
1291    /// what this shell handed out is recorded in one place. The subagent's
1292    /// shell shares this shell's approver, output store, events and
1293    /// policies' definitions, with state of its own, and its own jobs.
1294    ///
1295    /// `name` is the subagent's name beneath this shell's agent: every event
1296    /// its shell raises carries that [`AgentPath`], where the main shell's
1297    /// carry [`AgentPath::main`]. The subagent's running jobs are killed when
1298    /// the last handle of its shell is dropped, which a main shell never
1299    /// does.
1300    ///
1301    /// # Errors
1302    /// Returns an error when `grant` names a path this shell cannot write or
1303    /// a commit it cannot grant, when a container shell has no workspace
1304    /// mount, or when the subagent's space cannot be created or prepared.
1305    pub async fn subagent(
1306        &self,
1307        grant: SubagentGrant,
1308        caller: Option<&Path>,
1309        name: impl Into<String>,
1310    ) -> Result<Self, SubagentGrantError> {
1311        let resolved = {
1312            let mut history = self.launches.lock().await;
1313            self.resolve_launch(&mut history, grant).await?
1314        };
1315        self.launch_resolved(resolved, caller, name.into()).await
1316    }
1317
1318    /// Resolves the grant of a subagent this terminal launches: it never
1319    /// exceeds what this terminal can write or commit. `history` records what
1320    /// the main agent's terminal handed out.
1321    ///
1322    /// # Errors
1323    /// Returns an error when `grant` names a path this terminal cannot write
1324    /// or a commit it cannot grant, when the grant cannot be resolved, or when
1325    /// a container session has no workspace mount.
1326    async fn resolve_launch(
1327        &self,
1328        history: &mut LaunchHistory,
1329        grant: SubagentGrant,
1330    ) -> Result<ResolvedLaunch, SubagentGrantError> {
1331        // Grants are compared by real path, so every path of the subagent's
1332        // view is canonical.
1333        let working_dir = canonical_path(&self.working_dir).await?;
1334        let mut authority = vec![working_dir.clone()];
1335        for path in &self.sandbox.grants().snapshot().writable {
1336            authority.push(canonical_path(path).await?);
1337        }
1338        let spaces_root = working_dir.join(SUBAGENT_SPACES_DIR);
1339        let mount = self.container_mount().await?;
1340        let granted = grant
1341            .resolve(
1342                Launcher {
1343                    writable: &authority,
1344                    committing: self
1345                        .subagent
1346                        .as_ref()
1347                        .map(|subagent| subagent.committing.as_slice()),
1348                    spaces_root: &spaces_root,
1349                    spelling: mount
1350                        .as_ref()
1351                        .map_or_else(Spelling::host, Spelling::through),
1352                },
1353                history,
1354            )
1355            .await?;
1356        {
1357            let mut committed = self.committed.lock().expect("committed worktrees");
1358            for worktree in &granted.committing {
1359                if !committed.contains(worktree) {
1360                    committed.push(worktree.clone());
1361                }
1362            }
1363        }
1364        Ok(ResolvedLaunch {
1365            authority,
1366            spaces_root,
1367            mount,
1368            granted,
1369        })
1370    }
1371
1372    /// Creates the terminal tool of a subagent this terminal launches with
1373    /// the grant `resolved` holds.
1374    ///
1375    /// The subagent shares the approver, output store and SSH servers, binds
1376    /// the script policies to state of its own and has its own launch
1377    /// history and background task tracking. It works in a space of its own
1378    /// inside this terminal's working directory, which this terminal's
1379    /// [`SubagentSpaces`] fill first; everything this terminal can write is
1380    /// read-only to it, apart from what the grant hands over.
1381    ///
1382    /// # Errors
1383    /// Returns an error when a container session cannot express the
1384    /// subagent's paths, or when the subagent's space cannot be created or
1385    /// prepared.
1386    #[allow(clippy::too_many_lines)]
1387    async fn launch_resolved(
1388        &self,
1389        ResolvedLaunch {
1390            authority,
1391            spaces_root,
1392            mount,
1393            granted,
1394        }: ResolvedLaunch,
1395        caller: Option<&Path>,
1396        name: String,
1397    ) -> Result<Self, SubagentGrantError> {
1398        async_fs::create_dir_all(&spaces_root)
1399            .await
1400            .map_err(|source| SubagentGrantError::Space {
1401                path: spaces_root.clone(),
1402                source,
1403            })?;
1404        // The space is named by a leased word the subagent's terminal holds
1405        // for as long as it lives. A word a space of an earlier terminal
1406        // already has stays leased until a free one is found, so the
1407        // allocator hands out another.
1408        let mut taken = Vec::new();
1409        let (space_name, space, container) = loop {
1410            let name = self.ids.lease()?;
1411            let space = spaces_root.join(name.as_str());
1412            let container = mount
1413                .as_ref()
1414                .map(|mount| container_confinement_for(mount, &space, &granted.writable))
1415                .transpose()?;
1416            match async_fs::create_dir(&space).await {
1417                Ok(()) => break (name, space, container),
1418                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
1419                    taken.push(name);
1420                }
1421                Err(source) => {
1422                    return Err(SubagentGrantError::Space {
1423                        path: space,
1424                        source,
1425                    });
1426                }
1427            }
1428        };
1429        drop(taken);
1430        let prepared = match &self.subagent_spaces {
1431            Some(spaces) => {
1432                let launcher = &authority[0];
1433                let run = RunSpace {
1434                    space: &space,
1435                    launcher,
1436                    caller: caller.unwrap_or(launcher),
1437                };
1438                match prepare_space(spaces, run).await {
1439                    Ok(prepared) => Some(prepared),
1440                    Err(error) => {
1441                        // No run ever worked in the space, so it is no one's
1442                        // to keep.
1443                        if let Err(removal) = async_fs::remove_dir_all(&space).await {
1444                            warn!(
1445                                space = %space.display(),
1446                                %removal,
1447                                "cannot remove a subagent space whose preparation failed"
1448                            );
1449                        }
1450                        return Err(error);
1451                    }
1452                }
1453            }
1454            None => None,
1455        };
1456
1457        // The subagent's jobs raise their facts on the parent's handle, as
1458        // the agent named beneath this shell's.
1459        let agent = self.events_tx.agent().child(name);
1460        let events_rx = self.events_rx.clone();
1461        let events_tx = events_rx.sender(agent);
1462        let running_tasks = Arc::new(AtomicUsize::new(0));
1463        let (job_registry, job_registry_service) =
1464            job_registry_channel(self.output_store.policy().clone());
1465        self.executor
1466            .spawn(async move { job_registry_service.serve().await })
1467            .detach();
1468        // The derived sandbox carries none of the launcher's space variables;
1469        // the run's are those its own space was prepared with.
1470        let space_environment = prepared
1471            .as_ref()
1472            .map(|prepared| prepared.env_dirs().to_vec())
1473            .unwrap_or_default();
1474        let sandbox = self
1475            .sandbox
1476            .derived(GrantSnapshot {
1477                readable: authority,
1478                writable: granted.writable.clone(),
1479                ..GrantSnapshot::default()
1480            })
1481            .with_working_dir(space.clone())
1482            .with_space_environment(space_environment)
1483            .with_scanner(job_registry.scanner());
1484        let jobs = Arc::new(KillJobsOnDrop::new(
1485            job_registry.clone(),
1486            self.executor.clone(),
1487        ));
1488        let readable_paths = sandbox.grants().snapshot().readable.clone();
1489        let git = match (&container, mount, self.sandbox.backend()) {
1490            (Some(confinement), Some(mount), Backend::Container { runtime, launch }) => {
1491                SubagentGit::new(Arc::new(subagent_git::ContainerGit {
1492                    executor: self.executor.clone(),
1493                    launch: launch.clone(),
1494                    runtime: runtime.clone(),
1495                    confinement: confinement.clone(),
1496                    mount,
1497                    priority: self.sandbox.priority(),
1498                }))
1499            }
1500            _ => SubagentGit::new(Arc::new(subagent_git::LocalGit {
1501                executor: self.executor.clone(),
1502                working_dir: space.clone(),
1503                writable: granted.writable,
1504                readable: readable_paths,
1505                committing: granted.committing.clone(),
1506                priority: self.sandbox.priority(),
1507                heel: self
1508                    .sandbox
1509                    .host_heel()
1510                    .expect("a subagent outside a container runs on the host")
1511                    .clone(),
1512            })),
1513        };
1514        Ok(Self {
1515            working_dir: space,
1516            sessions: self.sessions.clone(),
1517            approver: self.approver.clone(),
1518            executor: self.executor.clone(),
1519            ids: self.ids.clone(),
1520            output_store: self.output_store.clone(),
1521            job_registry,
1522            events_tx,
1523            events_rx,
1524            job_tools: self.job_tools.clone(),
1525            interpreters: self.interpreters.clone(),
1526            limits: self.limits.clone(),
1527            running_tasks,
1528            sandbox,
1529            subagent: Some(SubagentAuthority {
1530                _jobs: jobs,
1531                _space_name: space_name,
1532                committing: granted.committing,
1533                git,
1534                prepared,
1535            }),
1536            carried_dir: None,
1537            #[cfg(all(unix, feature = "jobserver"))]
1538            jobserver: self.jobserver.clone(),
1539            outages: self.outages.clone(),
1540            subagent_spaces: self.subagent_spaces.clone(),
1541            policies: self.policies.for_agent(),
1542            treat_output: self.treat_output.clone(),
1543            ipc: self.ipc.clone(),
1544            committed: self.committed.clone(),
1545            launches: Arc::default(),
1546            host_launch: self.host_launch.clone(),
1547        })
1548    }
1549
1550    /// What this terminal's launcher prepared in its space; `None` for the
1551    /// main agent's terminal and when the launcher has no
1552    /// [`SubagentSpaces`].
1553    #[must_use]
1554    pub fn prepared_space(&self) -> Option<PreparedSpace> {
1555        self.subagent
1556            .as_ref()
1557            .and_then(|subagent| subagent.prepared.clone())
1558    }
1559
1560    /// The workspace mount of this terminal's home container, with its host
1561    /// side canonical, spelling every path of a subagent's view inside the
1562    /// container. `None` outside a container.
1563    async fn container_mount(&self) -> Result<Option<MountRoot>, SubagentGrantError> {
1564        let Backend::Container { runtime, .. } = self.sandbox.backend() else {
1565            return Ok(None);
1566        };
1567        let mount = runtime
1568            .workspace_mount()
1569            .ok_or(SubagentGrantError::NoContainerMount)?;
1570        // The mount is compared by real path, like everything it maps.
1571        Ok(Some(MountRoot::new(
1572            canonical_path(&mount.host_root).await?,
1573            mount.container_root.clone(),
1574        )))
1575    }
1576}
1577
1578/// Has `spaces` prepare `run`'s space and confines what they name to it.
1579async fn prepare_space(
1580    spaces: &AnySubagentSpaces,
1581    run: RunSpace<'_>,
1582) -> Result<PreparedSpace, SubagentGrantError> {
1583    spaces
1584        .prepare(run)
1585        .await
1586        .map_err(|source| SubagentGrantError::Preparation {
1587            space: run.space.to_path_buf(),
1588            source,
1589        })?
1590        .confine(run.space)
1591        .await
1592}
1593
1594/// The sandbox a subagent's commands run in inside a container: its space and
1595/// granted paths, spelled through the container's workspace mount.
1596fn container_confinement_for(
1597    mount: &MountRoot,
1598    space: &Path,
1599    writable: &[PathBuf],
1600) -> Result<ContainerConfinement, SubagentGrantError> {
1601    let map = |path: &Path| {
1602        mount
1603            .container_path(path)
1604            .map_err(|source| SubagentGrantError::OutsideContainerMount {
1605                path: path.to_path_buf(),
1606                source,
1607            })
1608    };
1609    Ok(ContainerConfinement {
1610        working_dir: map(space)?,
1611        grants: writable
1612            .iter()
1613            .map(|path| Ok((map(path)?, heel::Access::WRITE)))
1614            .collect::<Result<_, SubagentGrantError>>()?,
1615    })
1616}
1617
1618impl<E> Shell<E>
1619where
1620    E: Executor + Clone + 'static,
1621{
1622    /// Lists the commits of the subagent this terminal serves, when it holds a
1623    /// commit grant.
1624    #[must_use]
1625    pub fn commit_ledger(&self) -> Option<CommitLedger> {
1626        self.subagent.as_ref().and_then(|subagent| {
1627            CommitLedger::new(
1628                &subagent.committing,
1629                subagent.git.clone(),
1630                ImportLimits {
1631                    bytes: self.limits.subagent_import.clone(),
1632                    time: self.limits.foreground_wait.get(),
1633                },
1634            )
1635        })
1636    }
1637}
1638
1639/// The execution path a `terminal` call and a [`Shell::run`] share.
1640impl<E> Shell<E>
1641where
1642    E: Executor + Clone + 'static,
1643{
1644    /// The server `location` names, or `None` for the home environment.
1645    fn resolve_location(
1646        &self,
1647        location: Option<&str>,
1648    ) -> Result<Option<Arc<SshEnvironment>>, TerminalError> {
1649        let Some(name) = location.map(str::trim).filter(|name| !name.is_empty()) else {
1650            return Ok(None);
1651        };
1652        self.sessions
1653            .ssh_environments()
1654            .get(name)
1655            .map(Some)
1656            .ok_or_else(|| TerminalError::UnknownLocation(name.to_string()))
1657    }
1658
1659    fn resolve_home_target(&self, mode: SandboxMode) -> Result<ExecutionTarget, TerminalError> {
1660        let backend = match self.sandbox.backend() {
1661            Backend::Host { .. } => ExecutionBackend::Local {
1662                shell: self
1663                    .host_launch
1664                    .as_ref()
1665                    .expect("a shell on the host is built with its host shell")
1666                    .shell()
1667                    .clone(),
1668            },
1669            Backend::Container {
1670                runtime,
1671                #[cfg(all(unix, feature = "jobserver"))]
1672                launch,
1673                ..
1674            } => {
1675                if mode == SandboxMode::Unsandboxed {
1676                    return Err(TerminalError::InvalidTarget(
1677                        "unsafe mode is only available in heel local runtime".into(),
1678                    ));
1679                }
1680                ExecutionBackend::Container {
1681                    runtime: runtime.clone(),
1682                    #[cfg(all(unix, feature = "jobserver"))]
1683                    launch: launch.clone(),
1684                }
1685            }
1686            Backend::Ssh { .. } => unreachable!("a shell is never built on an SSH server"),
1687        };
1688        Ok(ExecutionTarget { mode, backend })
1689    }
1690
1691    /// A command on `environment` in `mode`. Default mode needs the server's
1692    /// `heel`.
1693    ///
1694    /// # Errors
1695    /// Fails when the server's first preparation fails; the next command
1696    /// prepares again.
1697    async fn resolve_ssh_target(
1698        &self,
1699        environment: &SshEnvironment,
1700        mode: SandboxMode,
1701    ) -> Result<ExecutionTarget, TerminalError> {
1702        let prepared = environment.prepared().await?;
1703        let server = environment.server();
1704        let heel = match (mode, &prepared.heel) {
1705            (SandboxMode::Sandboxed, Some(heel)) => Some(heel.clone()),
1706            (SandboxMode::Sandboxed, None) => {
1707                return Err(TerminalError::NoRemoteSandbox(server.name.clone()));
1708            }
1709            (SandboxMode::Unsandboxed, _) => None,
1710        };
1711        Ok(ExecutionTarget {
1712            mode,
1713            backend: ExecutionBackend::Ssh {
1714                client: self.sessions.ssh_environments().client().clone(),
1715                server: server.clone(),
1716                heel,
1717                launch: prepared.launch.clone(),
1718            },
1719        })
1720    }
1721
1722    /// The worktrees the main agent's scripts may reach through the host's
1723    /// `git` shim, in grant order; a subagent's shell reaches none.
1724    fn committed_worktrees(&self) -> Vec<CommittingWorktree> {
1725        if self.subagent.is_some() {
1726            return Vec::new();
1727        }
1728        self.committed.lock().expect("committed worktrees").clone()
1729    }
1730
1731    fn spawn_terminal_execution(&self, request: TerminalSpawnRequest) -> SpawnedTerminal {
1732        let TerminalSpawnRequest {
1733            target,
1734            task_id,
1735            execution_id,
1736            script,
1737            interpreter,
1738            expect,
1739            resolution,
1740            max_lines,
1741            stdout,
1742            background,
1743            timeout,
1744            carry,
1745            call,
1746        } = request;
1747        let ExecutionTarget { mode, backend } = target;
1748        let (result_tx, result_rx) = async_channel::bounded(1);
1749        let (taken_tx, taken_rx) = async_channel::bounded(1);
1750        let (startup_tx, startup_rx) = async_channel::bounded(1);
1751        let background_startup = BackgroundStartup::new(startup_tx);
1752        self.spawn_kill_watchdog(&task_id, timeout, background_startup.settled());
1753        self.spawn_long_job_alert(&task_id);
1754
1755        let info = crate::LaunchInfo::new(task_id.to_string(), call.clone(), mode);
1756        let lifetime = if background {
1757            JobLifetime::Background {
1758                stdin: StdinAlerts {
1759                    tx: self.events_tx.clone(),
1760                    task_id: task_id.to_string(),
1761                    script: script.clone(),
1762                },
1763            }
1764        } else {
1765            JobLifetime::Foreground {
1766                alerts: self.events_tx.clone(),
1767                task_id: task_id.to_string(),
1768                call,
1769            }
1770        };
1771        let running_tasks = self.running_tasks.clone();
1772        let completed_tx = self.events_tx.clone();
1773        let outages = self.outages.clone();
1774        outages.begin(&task_id);
1775
1776        running_tasks.fetch_add(1, Ordering::AcqRel);
1777        self.executor
1778            .spawn(execute_terminal_task(SpawnedTerminalTask {
1779                sandbox: self.sandbox.clone(),
1780                executor: self.executor.clone(),
1781                policies: self.policies.clone(),
1782                ipc: self.ipc.clone(),
1783                committed: self.committed_worktrees(),
1784                job_registry: self.job_registry.clone(),
1785                task_id,
1786                info,
1787                execution_id,
1788                background,
1789                timeout,
1790                carry,
1791                carried_dir: self.carried_dir.clone(),
1792                script,
1793                interpreter,
1794                mode,
1795                backend,
1796                lifetime,
1797                background_startup,
1798                expect,
1799                resolution,
1800                outputs: self.output_store.clone(),
1801                max_lines,
1802                stdout,
1803                result_tx,
1804                taken: taken_rx,
1805                completed_tx,
1806                running_tasks,
1807                #[cfg(all(unix, feature = "jobserver"))]
1808                jobserver: self.jobserver.clone(),
1809                outages,
1810            }))
1811            .detach();
1812
1813        SpawnedTerminal {
1814            result: result_rx,
1815            startup: startup_rx,
1816            taken: taken_tx,
1817        }
1818    }
1819}
1820
1821/// The model-facing tool of a [`Shell`]: the embedder's name and description
1822/// over the shell's execution, with an argument schema that lists exactly the
1823/// interpreters the shell was configured with.
1824#[derive(Debug, Clone)]
1825pub struct ShellTool<E> {
1826    shell: Shell<E>,
1827    identity: crate::builtin::ToolIdentity,
1828}
1829
1830impl<E: Executor + Clone + 'static> Tool for ShellTool<E> {
1831    fn name(&self) -> Cow<'static, str> {
1832        self.identity.name.clone()
1833    }
1834
1835    fn description(&self) -> Cow<'static, str> {
1836        self.identity.description.clone()
1837    }
1838
1839    fn arguments_schema(&self) -> schemars::Schema {
1840        let mut schema = schemars::schema_for!(ShellArgs);
1841        let interpreters = self
1842            .shell
1843            .interpreters
1844            .iter()
1845            .map(|interpreter| {
1846                serde_json::to_value(interpreter).expect("an interpreter serializes as a name")
1847            })
1848            .collect::<Vec<_>>();
1849        let definition = schema
1850            .get_mut("$defs")
1851            .and_then(serde_json::Value::as_object_mut)
1852            .and_then(|definitions| definitions.get_mut("Interpreter"))
1853            .expect("the schema of ShellArgs defines its interpreter");
1854        *definition = serde_json::json!({
1855            "type": "string",
1856            "enum": interpreters,
1857        });
1858        self.identity.describe(schema)
1859    }
1860
1861    type Arguments = ShellArgs;
1862    type Res = ToolResult;
1863
1864    async fn call(
1865        &self,
1866        arguments: Self::Arguments,
1867        cx: ToolContext,
1868    ) -> aither_core::Result<Self::Res> {
1869        self.shell.call(arguments, cx).await
1870    }
1871}
1872
1873impl<E: Executor + Clone + 'static> Shell<E> {
1874    /// Runs `script` to its end, through the foreground window and past it,
1875    /// and returns its output and how it ended; a script its timeout killed
1876    /// ends [`CommandOutcome::Killed`].
1877    ///
1878    /// The run is under the shell's whole policy: its grants, network
1879    /// policy, backend, policies, priority, environment and jobserver. It
1880    /// starts where `script` says and leaves the directory the shell carries
1881    /// between calls alone. It is a job of the shell, listed and killable
1882    /// like any other, but never announced as one: its end is told to the
1883    /// caller alone.
1884    ///
1885    /// # Errors
1886    /// Returns an error when the timeout is out of range, a policy refuses
1887    /// the script, the directory does not map into the shell's container, or
1888    /// the execution fails.
1889    pub async fn run(&self, script: Script) -> Result<crate::ScriptResult, ShellRunError> {
1890        let mut shell = self.clone();
1891        shell.carried_dir = None;
1892        shell.run_to_end(script).await
1893    }
1894
1895    /// The model-facing tool of this shell, named and described as the
1896    /// embedder's [`ShellToolSettings`] say.
1897    #[must_use]
1898    pub fn tool(&self) -> ShellTool<E> {
1899        ShellTool {
1900            shell: self.clone(),
1901            identity: self.job_tools.shell.clone(),
1902        }
1903    }
1904
1905    /// Runs one `terminal` call: the script of `arguments` in its
1906    /// interpreter, in the foreground window or detached.
1907    ///
1908    /// # Errors
1909    /// Returns an error when the arguments are out of range, the interpreter
1910    /// is not one the shell is configured with, a policy refuses the script
1911    /// or the execution fails.
1912    pub async fn call(
1913        &self,
1914        arguments: ShellArgs,
1915        cx: ToolContext,
1916    ) -> aither_core::Result<ToolResult> {
1917        match self.execute(arguments, cx).await? {
1918            Execution::Finished(result) => result.into_tool_result(),
1919            Execution::Detached(detached) => detached.into_command_result().into_tool_result(),
1920        }
1921    }
1922
1923    /// Runs one call to the point it answers: its result, or the job it
1924    /// detached.
1925    async fn execute(
1926        &self,
1927        arguments: ShellArgs,
1928        mut cx: ToolContext,
1929    ) -> aither_core::Result<Execution> {
1930        if !self.interpreters.contains(&arguments.interpreter) {
1931            return Err(crate::Refused::call(
1932                &**self.wording(),
1933                CallRefusal::InterpreterNotConfigured {
1934                    interpreter: arguments.interpreter,
1935                },
1936            ));
1937        }
1938        let cap = self.limits.timeout_cap.get();
1939        let timeout = Duration::from_secs(arguments.timeout);
1940        if arguments.timeout == 0 || timeout > cap {
1941            return Err(crate::Refused::call(
1942                &**self.wording(),
1943                CallRefusal::TimeoutOutOfRange { cap },
1944            ));
1945        }
1946        let prepared = self.prepare_execution(&arguments, &mut cx).await?;
1947        // A detached job cannot report a directory carry: its final
1948        // directory is unknowable when the call returns.
1949        let carry = if arguments.background {
1950            None
1951        } else {
1952            self.cwd_carry(&prepared, &arguments.script, arguments.interpreter)
1953        };
1954        let spawned = self.spawn_terminal_execution(TerminalSpawnRequest {
1955            target: prepared.target,
1956            task_id: prepared.task_id.clone(),
1957            execution_id: prepared.execution_id,
1958            script: arguments.script,
1959            interpreter: arguments.interpreter,
1960            expect: OutputFormat::Auto,
1961            resolution: arguments.resolution,
1962            max_lines: prepared.max_lines,
1963            stdout: StdoutTreatment::of_call(arguments.raw, prepared.treatment),
1964            background: arguments.background,
1965            timeout,
1966            carry: carry.clone(),
1967            call: cx.identity().cloned(),
1968        });
1969        // Registration, and a background job's stdin pipe, precede
1970        // `report_ready` on every backend, so once startup returns the job
1971        // is killable through the registry, takes input when it has a pipe,
1972        // and the foreground clock only measures the command's own runtime.
1973        wait_for_background_startup(&spawned.startup, &**self.wording()).await?;
1974        if arguments.background {
1975            return detach_job(
1976                &self.job_registry,
1977                &prepared.outputs,
1978                &prepared.task_id,
1979                prepared.max_lines,
1980                &self.events_tx,
1981            )
1982            .await
1983            .map(Execution::Detached);
1984        }
1985        let outcome =
1986            wait_for_foreground_result(&spawned.result, self.limits.foreground_wait.get()).await;
1987        // A result that raced in at the window's edge counts as a
1988        // foreground finish.
1989        let outcome = outcome.or_else(|| spawned.result.try_recv().ok());
1990        match outcome {
1991            Some(Ok(result)) => {
1992                let killed = self
1993                    .job_registry
1994                    .get_by_task_id_settled(&prepared.task_id)
1995                    .await
1996                    .and_then(|job| job.status.kill_cause());
1997                let command = result
1998                    .into_script_result(killed)
1999                    .into_command_result(&prepared.task_id, &self.output_store);
2000                spawned.took_result().await;
2001                Ok(Execution::Finished(command))
2002            }
2003            Some(Err(detail)) => {
2004                spawned.took_result().await;
2005                Err(failed_run(&**self.wording(), &detail))
2006            }
2007            // The command outlived its foreground window: promote it to a
2008            // background task.
2009            None => detach_job(
2010                &self.job_registry,
2011                &prepared.outputs,
2012                &prepared.task_id,
2013                prepared.max_lines,
2014                &self.events_tx,
2015            )
2016            .await
2017            .map(Execution::Detached),
2018        }
2019    }
2020}
2021
2022/// What a call answered.
2023enum Execution {
2024    /// The script ended inside the foreground window.
2025    Finished(CommandResult),
2026    /// The script became a job.
2027    Detached(Detached),
2028}
2029
2030/// A job a call detached, with the output file it was redirected to.
2031struct Detached {
2032    task_id: String,
2033    redirect: BackgroundRedirect,
2034    /// Holds the job until the caller took it over.
2035    watch: crate::job_registry::JobWatch,
2036}
2037
2038impl Detached {
2039    /// The result the model reads for the job's start.
2040    fn into_command_result(self) -> CommandResult {
2041        let Self {
2042            task_id, redirect, ..
2043        } = self;
2044        let stdout = if redirect.truncated {
2045            CommandStream::Stored {
2046                file: redirect.file.clone(),
2047                preview: redirect.preview,
2048                truncated: true,
2049            }
2050        } else {
2051            CommandStream::Inline {
2052                text: redirect.preview,
2053            }
2054        };
2055        CommandResult {
2056            stdout,
2057            stderr: None,
2058            interruptions: Vec::new(),
2059            outcome: CommandOutcome::Running {
2060                task_id,
2061                output: redirect.file,
2062            },
2063        }
2064    }
2065}
2066
2067impl<E: Executor + Clone + 'static> Shell<E> {
2068    /// The directory report of a foreground command on the main agent's
2069    /// terminal; `None` for a subagent, for an ssh command and for a container
2070    /// whose workspace mount is not declared.
2071    fn cwd_carry(
2072        &self,
2073        prepared: &ExecutionPreparation,
2074        script: &str,
2075        interpreter: Interpreter,
2076    ) -> Option<CwdCarry> {
2077        let carried = self.carried_dir.as_ref()?;
2078        let mount = match &prepared.target.backend {
2079            ExecutionBackend::Local { .. } if !cfg!(windows) => None,
2080            ExecutionBackend::Container { runtime, .. } => Some(runtime.workspace_mount()?.clone()),
2081            _ => return None,
2082        };
2083        // Where admission found the script starts, as the policies saw it;
2084        // a directory removed since it was recorded no longer carries.
2085        let (start, removed) = match (&prepared.carried_start, carried.get()) {
2086            (Some(dir), _) => (Some(dir.clone()), false),
2087            (None, Some(_)) => {
2088                carried.set(None);
2089                (None, true)
2090            }
2091            (None, None) => (None, false),
2092        };
2093        let report = self.working_dir.join(format!(".cwd-{}", prepared.task_id));
2094        let container = match mount {
2095            None => None,
2096            Some(mount) => {
2097                // The report must lie in the mounted workspace for the host
2098                // to read it back.
2099                let container_report = mount.container_path(&report).ok()?;
2100                let container_start = start
2101                    .as_ref()
2102                    .and_then(|start| mount.container_path(start).ok())
2103                    .unwrap_or_else(|| {
2104                        ContainerPath::new(CONTAINER_EXEC_WORKING_DIR)
2105                            .expect("the exec directory is absolute")
2106                    });
2107                Some(ContainerCarry {
2108                    mount,
2109                    report: Some(container_report),
2110                    start: container_start,
2111                })
2112            }
2113        };
2114        // A Python script runs from a shell wrapper, so its report is written
2115        // like a shell script's.
2116        let shell =
2117            container.is_some() || interpreter == Interpreter::Python || runs_in_shell(script);
2118        Some(CwdCarry {
2119            start,
2120            report: Some(report),
2121            container,
2122            shell,
2123            removed,
2124        })
2125    }
2126
2127    /// Makes the directory a finished foreground command ended in the start
2128    /// of the next one, and says what became of the carried directory. In
2129    /// production the task consumes the report (see
2130    /// [`execute_script_standalone`]); tests drive the same logic here.
2131    #[cfg(test)]
2132    async fn record_carried_dir(&self, carry: &CwdCarry, succeeded: bool) -> Settled {
2133        let ctx = CarryContext {
2134            carried_dir: self.carried_dir.as_ref(),
2135            working_dir: &self.working_dir,
2136            grants: self.sandbox.grants().snapshot(),
2137        };
2138        settle_cwd(carry, take_cwd_report(carry).await, succeeded, &ctx).await
2139    }
2140}
2141
2142/// A host directory of a container script as the container names it: through
2143/// the workspace mount when `host` lies in it, otherwise the directory the
2144/// container starts in.
2145fn container_script_dir(mount: Option<&MountRoot>, host: Option<PathBuf>, own: &Path) -> ScriptDir {
2146    let inside = host
2147        .as_ref()
2148        .zip(mount)
2149        .and_then(|(host, mount)| mount.container_path(host).ok())
2150        .unwrap_or_else(|| {
2151            ContainerPath::new(CONTAINER_EXEC_WORKING_DIR).expect("the exec directory is absolute")
2152        });
2153    ScriptDir::Container {
2154        inside,
2155        host: host.unwrap_or_else(|| own.to_path_buf()),
2156    }
2157}
2158
2159/// How the backend of a script names the directory the next foreground
2160/// script starts in.
2161#[derive(Clone)]
2162enum DirSpelling {
2163    Host,
2164    Container(Option<MountRoot>),
2165    Remote(String),
2166}
2167
2168impl DirSpelling {
2169    fn of(backend: &ExecutionBackend) -> Self {
2170        match backend {
2171            ExecutionBackend::Local { .. } => Self::Host,
2172            ExecutionBackend::Container { runtime, .. } => {
2173                Self::Container(runtime.workspace_mount().cloned())
2174            }
2175            ExecutionBackend::Ssh { server, .. } => Self::Remote(server.name.clone()),
2176        }
2177    }
2178
2179    /// `host`, the directory carried as settled under the lock of the
2180    /// carried directory, or the terminal's own directory `own` when none is.
2181    fn dir(&self, host: Option<PathBuf>, own: &Path) -> ScriptDir {
2182        match self {
2183            Self::Host => ScriptDir::Host(host.unwrap_or_else(|| own.to_path_buf())),
2184            Self::Container(mount) => container_script_dir(mount.as_ref(), host, own),
2185            Self::Remote(server) => ScriptDir::Remote {
2186                server: server.clone(),
2187            },
2188        }
2189    }
2190}
2191
2192/// The directory `carried` holds, while it still exists: where the next
2193/// foreground script starts.
2194async fn carried_start(carried: Option<&CarriedDir>) -> Option<PathBuf> {
2195    let dir = carried?.get()?;
2196    async_fs::metadata(&dir)
2197        .await
2198        .is_ok_and(|meta| meta.is_dir())
2199        .then_some(dir)
2200}
2201
2202/// Shared state needed to settle a finished command's directory report,
2203/// whether the command finished inside its foreground call or promoted
2204/// and ended as a background task.
2205struct CarryContext<'a> {
2206    carried_dir: Option<&'a CarriedDir>,
2207    working_dir: &'a Path,
2208    grants: std::sync::Arc<GrantSnapshot>,
2209}
2210
2211/// What a finished command did to the carried directory: the fact for the
2212/// policies, and the directory now carried, read in the same critical
2213/// section that recorded it.
2214struct Settled {
2215    carry: Carry,
2216    carried: Option<PathBuf>,
2217}
2218
2219/// Settles a finished command's directory report.
2220///
2221/// `report` is what [`take_cwd_report`] read: `None` when the shell wrote
2222/// none.
2223async fn settle_cwd(
2224    carry: &CwdCarry,
2225    report: Option<String>,
2226    succeeded: bool,
2227    ctx: &CarryContext<'_>,
2228) -> Settled {
2229    // A subagent's terminal carries nothing, and a run reports no directory.
2230    let Some(carried) = ctx.carried_dir.filter(|_| carry.report.is_some()) else {
2231        return Settled {
2232            carry: Carry::NotCarried,
2233            carried: ctx.carried_dir.and_then(CarriedDir::get),
2234        };
2235    };
2236    let (moved_to, outcome) = match report {
2237        Some(reported) => apply_cwd_report(carry, &reported, succeeded, ctx).await,
2238        // A direct command cannot change directory and writes no report.
2239        None if carry.shell => (None, Carry::Reset(DirectoryResetReason::Unreported)),
2240        None => (None, Carry::Unchanged),
2241    };
2242    let outcome = match outcome {
2243        Carry::Unchanged if carry.removed => Carry::Reset(DirectoryResetReason::Removed),
2244        other => other,
2245    };
2246    Settled {
2247        carry: outcome,
2248        carried: carried.settle(moved_to),
2249    }
2250}
2251
2252/// Reads and removes a command's directory report, returning the directory
2253/// the shell ended in when it reported one. The file is consumed either
2254/// way so a promoted command never leaves it behind.
2255async fn take_cwd_report(carry: &CwdCarry) -> Option<String> {
2256    let report = carry.report.as_ref()?;
2257    let reported = async_fs::read_to_string(report).await;
2258    let _ = async_fs::remove_file(report).await;
2259    // A direct command writes no report; a shell that ended through
2260    // `exit` or a signal writes none either.
2261    reported
2262        .ok()
2263        .map(|reported| reported.trim_end_matches('\n').to_owned())
2264        .filter(|reported| !reported.is_empty())
2265}
2266
2267/// The directory a finished command ended in as the directory the next one
2268/// starts in, when the command succeeded and the directory lies inside the
2269/// paths this terminal may read, and what became of the carried directory.
2270/// When the next command does not start where the shell ended, the answer
2271/// says why.
2272async fn apply_cwd_report(
2273    carry: &CwdCarry,
2274    reported: &str,
2275    succeeded: bool,
2276    ctx: &CarryContext<'_>,
2277) -> (Option<PathBuf>, Carry) {
2278    if !succeeded {
2279        let carry = if left_in_start(carry, reported, ctx.working_dir).await {
2280            Carry::Unchanged
2281        } else {
2282            Carry::Reset(DirectoryResetReason::Failed)
2283        };
2284        return (None, carry);
2285    }
2286    if let Some(container) = &carry.container {
2287        // A container is an unconfined main agent: what bounds its
2288        // directory is the workspace mount.
2289        return match ContainerPath::new(reported)
2290            .map_err(drop)
2291            .and_then(|dir| container.mount.host_path(&dir).map_err(drop))
2292        {
2293            Ok(dir) => {
2294                let moved = reported != container.start.as_str();
2295                (
2296                    Some(dir),
2297                    if moved {
2298                        Carry::Moved
2299                    } else {
2300                        Carry::Unchanged
2301                    },
2302                )
2303            }
2304            Err(()) => (None, Carry::Reset(DirectoryResetReason::OutsideWorkspace)),
2305        };
2306    }
2307    let Ok(dir) = canonical_path(Path::new(reported)).await else {
2308        return (None, Carry::Reset(DirectoryResetReason::Removed));
2309    };
2310    for grant in std::iter::once(ctx.working_dir)
2311        .chain(ctx.grants.writable.iter().map(PathBuf::as_path))
2312        .chain(ctx.grants.readable.iter().map(PathBuf::as_path))
2313    {
2314        if canonical_path(grant)
2315            .await
2316            .is_ok_and(|grant| dir.starts_with(grant))
2317        {
2318            let start = match &carry.start {
2319                Some(start) => Some(start.clone()),
2320                None => canonical_path(ctx.working_dir).await.ok(),
2321            };
2322            let moved = start.as_ref() != Some(&dir);
2323            return (
2324                Some(dir),
2325                if moved {
2326                    Carry::Moved
2327                } else {
2328                    Carry::Unchanged
2329                },
2330            );
2331        }
2332    }
2333    (None, Carry::Reset(DirectoryResetReason::OutsideReadable))
2334}
2335
2336/// Whether the shell ended in the directory the command started in.
2337async fn left_in_start(carry: &CwdCarry, reported: &str, working_dir: &Path) -> bool {
2338    if let Some(container) = &carry.container {
2339        return reported == container.start.as_str();
2340    }
2341    let start = carry.start.as_deref().unwrap_or(working_dir);
2342    match (
2343        canonical_path(Path::new(reported)).await,
2344        canonical_path(start).await,
2345    ) {
2346        (Ok(reported), Ok(start)) => reported == start,
2347        _ => false,
2348    }
2349}
2350
2351impl<E: Executor + Clone + 'static> Shell<E> {
2352    /// Runs `script` as a detached background job bounded by `timeout`, for
2353    /// embedders that drive the terminal directly rather than through the
2354    /// `terminal` tool schema, and returns the job. Shares [`Self::call`]'s
2355    /// `background: true` path, so the job is announced as one.
2356    ///
2357    /// # Errors
2358    ///
2359    /// Fails the way a `terminal` call does: an invalid `timeout`, a
2360    /// refused permission, a blocked command or a spawn failure.
2361    pub async fn run_background(&self, arguments: ShellArgs) -> aither_core::Result<crate::Job> {
2362        let execution = self
2363            .execute(
2364                ShellArgs {
2365                    background: true,
2366                    ..arguments
2367                },
2368                ToolContext::new(),
2369            )
2370            .await?;
2371        match execution {
2372            Execution::Detached(detached) => Ok(crate::Job::new(
2373                self.jobs(),
2374                detached.task_id,
2375                detached.watch,
2376            )),
2377            Execution::Finished(_) => unreachable!("a background call detaches its job"),
2378        }
2379    }
2380}
2381
2382impl<E> Shell<E>
2383where
2384    E: Executor + Clone + 'static,
2385{
2386    /// The terminal's own directory as a command sees it.
2387    async fn own_dir(&self) -> PathBuf {
2388        canonical_path(&self.working_dir)
2389            .await
2390            .unwrap_or_else(|_| self.working_dir.clone())
2391    }
2392
2393    /// `host`, or the terminal's own directory `own` when the script starts
2394    /// in neither a carried nor a named one, as the home backend names it.
2395    fn home_script_dir(&self, host: Option<PathBuf>, own: &Path) -> ScriptDir {
2396        match self.sandbox.backend() {
2397            Backend::Container { runtime, .. } => {
2398                container_script_dir(runtime.workspace_mount(), host, own)
2399            }
2400            Backend::Host { .. } | Backend::Ssh { .. } => {
2401                ScriptDir::Host(host.unwrap_or_else(|| own.to_path_buf()))
2402            }
2403        }
2404    }
2405
2406    /// What renders this terminal's refusals and notices: its output store's.
2407    pub(crate) fn wording(&self) -> &crate::AnyShellWording {
2408        self.output_store.wording()
2409    }
2410
2411    /// Shared front half of every `terminal` call: argument validation, then
2412    /// [`Self::admit_command`].
2413    async fn prepare_execution(
2414        &self,
2415        arguments: &ShellArgs,
2416        cx: &mut ToolContext,
2417    ) -> anyhow::Result<ExecutionPreparation> {
2418        if arguments.description.trim().is_empty() {
2419            return Err(crate::Refused::call(
2420                &**self.wording(),
2421                CallRefusal::EmptyDescription,
2422            ));
2423        }
2424        let origin = if arguments.background {
2425            ScriptOrigin::Background
2426        } else {
2427            ScriptOrigin::Foreground
2428        };
2429        let call = cx.identity().cloned();
2430        self.admit_command(
2431            Admission {
2432                script: &arguments.script,
2433                interpreter: arguments.interpreter,
2434                mode: arguments.sandbox,
2435                location: arguments.location.as_deref(),
2436                max_lines: arguments.max_lines,
2437                origin,
2438                call,
2439                run_dir: None,
2440            },
2441            Some(cx),
2442        )
2443        .await
2444        .map_err(|error| error.into_tool_error(&**self.wording()))
2445    }
2446
2447    /// The terminal's policy for a command, whoever runs it — the one entry
2448    /// every foreground, background, subagent and run command on every
2449    /// backend passes through: the script policies, target resolution and
2450    /// permission; then the spawned job's ids.
2451    ///
2452    /// Every script the policies were asked about is reported to them once
2453    /// it ends; one admission fails is reported here, unrun.
2454    async fn admit_command(
2455        &self,
2456        admission: Admission<'_>,
2457        cx: Option<&mut ToolContext>,
2458    ) -> Result<ExecutionPreparation, ShellRunError> {
2459        // Leased for as long as the command can be addressed: the registry
2460        // keeps a clone once the job is registered.
2461        let task_id = self.ids.lease()?;
2462        let environment = self.resolve_location(admission.location)?;
2463        // Decided once, here: the policies see the directory the command
2464        // then starts in, and so does its launch.
2465        let carried_start = if admission.origin == ScriptOrigin::Foreground {
2466            carried_start(self.carried_dir.as_ref()).await
2467        } else {
2468            None
2469        };
2470        let own = self.own_dir().await;
2471        let start = match &environment {
2472            Some(environment) => ScriptDir::Remote {
2473                server: environment.server().name.clone(),
2474            },
2475            None => self.home_script_dir(
2476                admission
2477                    .run_dir
2478                    .map(Path::to_path_buf)
2479                    .or_else(|| carried_start.clone()),
2480                &own,
2481            ),
2482        };
2483        let checked = self
2484            .check_script(&task_id, &admission, &start)
2485            .await
2486            .map_err(ShellRunError::Refused);
2487        let (clearance, treatment) = match checked {
2488            Ok(checked) => checked,
2489            Err(refusal) => {
2490                self.end_unrun(&task_id).await;
2491                return Err(refusal);
2492            }
2493        };
2494        let admitted = self
2495            .admit_checked(&admission, environment.as_deref(), clearance, cx)
2496            .await;
2497        if admitted.is_err() {
2498            self.end_unrun(&task_id).await;
2499        }
2500        let (target, max_lines) = admitted?;
2501        Ok(ExecutionPreparation {
2502            target,
2503            execution_id: format!("exec-{task_id}"),
2504            task_id,
2505            outputs: self.output_store.clone(),
2506            max_lines,
2507            treatment,
2508            carried_start,
2509        })
2510    }
2511
2512    /// Tells the policies a script they were asked about never started, and
2513    /// where the next foreground script starts.
2514    async fn end_unrun(&self, task_id: &str) {
2515        let policies = &self.policies;
2516        if policies.is_empty() {
2517            return;
2518        }
2519        let own = self.own_dir().await;
2520        let end = self.home_script_dir(carried_start(self.carried_dir.as_ref()).await, &own);
2521        policies
2522            .ended(task_id, ScriptOutcome::NotRun, &end, Carry::NotCarried)
2523            .await;
2524    }
2525
2526    /// Puts the script to the shell's script policies and its output
2527    /// treatment, the shell parsed once for all of them, and folds the
2528    /// policies' decisions into what admission does next.
2529    async fn check_script(
2530        &self,
2531        task_id: &str,
2532        admission: &Admission<'_>,
2533        start: &ScriptDir,
2534    ) -> Result<(Clearance, OutputTreatment), ScriptRefusal> {
2535        let policies = &self.policies;
2536        if policies.is_empty() && self.treat_output.is_none() {
2537            return Ok((Clearance::Pass, OutputTreatment::default()));
2538        }
2539        let shell = (admission.interpreter == Interpreter::Shell)
2540            .then(|| crate::ShellScript::parse(admission.script));
2541        let check = crate::ScriptCheck {
2542            task_id,
2543            script: admission.script,
2544            interpreter: admission.interpreter,
2545            shell: shell.as_ref().map(Result::as_ref),
2546            origin: admission.origin,
2547            sandbox: admission.mode,
2548            location: admission.location(),
2549            start,
2550            call: admission.call(),
2551        };
2552        let treatment = self
2553            .treat_output
2554            .as_ref()
2555            .map_or_else(OutputTreatment::default, |treat| treat.treatment(&check));
2556        let clearance = match policies.check(&check).await {
2557            ScriptDecision::Pass => Clearance::Pass,
2558            ScriptDecision::Allow => Clearance::Allow,
2559            ScriptDecision::Ask(request) => Clearance::Ask(request),
2560            ScriptDecision::Refuse(refusal) => return Err(refusal),
2561        };
2562        Ok((clearance, treatment))
2563    }
2564
2565    /// The rest of admission once the policies did not refuse the script.
2566    async fn admit_checked(
2567        &self,
2568        admission: &Admission<'_>,
2569        environment: Option<&SshEnvironment>,
2570        clearance: Clearance,
2571        cx: Option<&mut ToolContext>,
2572    ) -> Result<(ExecutionTarget, usize), ShellRunError> {
2573        let mode = admission.mode;
2574        let target = match environment {
2575            None => {
2576                let target = self.resolve_home_target(mode)?;
2577                self.clear(admission, clearance, cx).await?;
2578                target
2579            }
2580            Some(environment) => {
2581                self.clear(admission, clearance, cx).await?;
2582                self.resolve_ssh_target(environment, mode).await?
2583            }
2584        };
2585        Ok((
2586            target,
2587            self.output_store.policy().lines(admission.max_lines),
2588        ))
2589    }
2590
2591    /// Settles whether the script may run, once the policies did not refuse
2592    /// it: a script that crosses the sandbox boundary, unsandboxed or on a
2593    /// server, runs only after an [`Allow`](ScriptDecision::Allow) or an
2594    /// approved [`Ask`](ScriptDecision::Ask); one the policies only passed
2595    /// is asked about.
2596    async fn clear(
2597        &self,
2598        admission: &Admission<'_>,
2599        clearance: Clearance,
2600        cx: Option<&mut ToolContext>,
2601    ) -> Result<(), TerminalError> {
2602        let request = match clearance {
2603            Clearance::Ask(request) => request,
2604            Clearance::Pass if admission.crosses_boundary() => admission.boundary_request(),
2605            Clearance::Allow | Clearance::Pass => return Ok(()),
2606        };
2607        self.approve(request, admission.call(), cx).await
2608    }
2609
2610    /// Puts `request` to the approver of the call that carries the script, or
2611    /// to the terminal's own when the script has no call to ask through:
2612    /// a run, a background script started directly, or a call whose
2613    /// dispatcher attached none.
2614    async fn approve(
2615        &self,
2616        request: ApprovalRequest,
2617        call: Option<&CallIdentity>,
2618        cx: Option<&mut ToolContext>,
2619    ) -> Result<(), TerminalError> {
2620        let kind = request.kind().clone();
2621        let answer = match cx {
2622            Some(cx) => match cx.approve(request.clone()).await {
2623                Err(ApprovalError::NoApprover { .. }) => None,
2624                answer => Some(answer),
2625            },
2626            None => None,
2627        };
2628        let answer = if let Some(answer) = answer {
2629            answer
2630        } else {
2631            let Some(approver) = &self.approver else {
2632                return Err(TerminalError::NoApprover(kind));
2633            };
2634            let request = match call {
2635                Some(call) => request.with_call(call.clone()),
2636                None => request,
2637            };
2638            approver
2639                .approve(request)
2640                .await
2641                .map_err(|failure| ApprovalError::Failed { kind, failure })
2642        };
2643        match answer? {
2644            Approval::Approved => Ok(()),
2645            Approval::Denied { reason } => Err(TerminalError::Denied(reason)),
2646        }
2647    }
2648
2649    /// Runs `run` to its end on this terminal; see [`Shell::run`].
2650    async fn run_to_end(&self, run: Script) -> Result<crate::ScriptResult, ShellRunError> {
2651        let cap = self.limits.timeout_cap.get();
2652        if run.timeout.is_zero() || run.timeout > cap {
2653            return Err(ShellRunError::Timeout { cap });
2654        }
2655        // A run starts in a host directory, so it resolves the terminal's
2656        // home backend, never an SSH server.
2657        let prepared = self
2658            .admit_command(
2659                Admission {
2660                    script: &run.source,
2661                    interpreter: Interpreter::Shell,
2662                    mode: run.sandbox,
2663                    location: None,
2664                    max_lines: None,
2665                    origin: ScriptOrigin::Run,
2666                    call: None,
2667                    run_dir: Some(&run.dir),
2668                },
2669                None,
2670            )
2671            .await?;
2672        let start = match run_start(&prepared.target, run.dir) {
2673            Ok(start) => start,
2674            Err(error) => {
2675                self.end_unrun(&prepared.task_id).await;
2676                return Err(error);
2677            }
2678        };
2679        let spawned = self.spawn_terminal_execution(TerminalSpawnRequest {
2680            target: prepared.target,
2681            task_id: prepared.task_id.clone(),
2682            execution_id: prepared.execution_id,
2683            script: run.source,
2684            interpreter: Interpreter::Shell,
2685            expect: OutputFormat::Text,
2686            resolution: MediaResolution::Auto,
2687            max_lines: prepared.max_lines,
2688            stdout: StdoutTreatment::Cleaned(prepared.treatment),
2689            background: false,
2690            timeout: run.timeout,
2691            carry: Some(start),
2692            call: None,
2693        });
2694        match spawned.startup.recv().await {
2695            Ok(Ok(())) => {}
2696            Ok(Err(error)) => return Err(TerminalError::Execution(error).into()),
2697            Err(_) => return Err(TerminalError::TaskLost.into()),
2698        }
2699        // The run is never announced as a background task, so its end is
2700        // told to the caller alone, however long it takes.
2701        let result = spawned
2702            .result
2703            .recv()
2704            .await
2705            .map_err(|_| TerminalError::TaskLost);
2706        let killed = self
2707            .job_registry
2708            .get_by_task_id_settled(&prepared.task_id)
2709            .await
2710            .and_then(|job| job.status.kill_cause());
2711        spawned.took_result().await;
2712        let result = result?.map_err(TerminalError::Execution)?;
2713        Ok(result.into_script_result(killed))
2714    }
2715
2716    /// Kills the job through the registry once its timeout passes, the job
2717    /// then reading [`KillCause::Timeout`](crate::KillCause::Timeout).
2718    ///
2719    /// A bound that passes before the job registered is enforced the moment
2720    /// `registered` closes, which is when the job's startup was reported.
2721    fn spawn_kill_watchdog(&self, task_id: &IdLease, timeout: Duration, registered: Receiver<()>) {
2722        let job_registry = self.job_registry.clone();
2723        let started = jiff::Timestamp::now();
2724        // Weak, so a job that ended gives its word back before the timer
2725        // fires; a word that went back may name another job by then.
2726        let task_id = task_id.downgrade();
2727        self.executor
2728            .spawn(async move {
2729                async_io::Timer::after(timeout).await;
2730                // Nothing is ever sent: the channel closes once the startup
2731                // was reported or its flow is gone.
2732                let _ = registered.recv().await;
2733                let Some(task_id) = task_id.upgrade() else {
2734                    return;
2735                };
2736                if let Some(job) = job_registry.get_by_task_id(&task_id).await
2737                    && matches!(job.status, JobStatus::Running)
2738                {
2739                    job_registry
2740                        .kill_timed_out(
2741                            &job.task_id,
2742                            TimeoutKill {
2743                                timeout,
2744                                started,
2745                                killed: jiff::Timestamp::now(),
2746                            },
2747                        )
2748                        .await;
2749                }
2750            })
2751            .detach();
2752    }
2753
2754    /// Raises one [`LongRunning`] when the job crosses the configured
2755    /// long-running threshold.
2756    fn spawn_long_job_alert(&self, task_id: &IdLease) {
2757        let job_registry = self.job_registry.clone();
2758        let alert_tx = self.events_tx.clone();
2759        // Weak for the same reason as the watchdog's.
2760        let task_id = task_id.downgrade();
2761        let alert_after = self.limits.long_job_alert.get();
2762        self.executor
2763            .spawn(async move {
2764                async_io::Timer::after(alert_after).await;
2765                let Some(task_id) = task_id.upgrade() else {
2766                    return;
2767                };
2768                if let Some(job) = job_registry.get_by_task_id(&task_id).await
2769                    && matches!(job.status, JobStatus::Running)
2770                {
2771                    let _ = alert_tx
2772                        .send(ShellEvent::LongRunning(LongRunning {
2773                            agent: alert_tx.agent().clone(),
2774                            task_id: task_id.to_string(),
2775                            script: job.script,
2776                            after: job.started_at.elapsed(),
2777                        }))
2778                        .await;
2779                }
2780            })
2781            .detach();
2782    }
2783}
2784
2785/// What [`Shell::admit_command`] admits: a script and how it came.
2786struct Admission<'a> {
2787    script: &'a str,
2788    interpreter: Interpreter,
2789    mode: SandboxMode,
2790    /// The SSH server the command names; `None` or empty for home.
2791    location: Option<&'a str>,
2792    max_lines: Option<u32>,
2793    origin: ScriptOrigin,
2794    /// The tool call that carries the script and the agent that made it;
2795    /// `None` for a script no call carries.
2796    call: Option<CallIdentity>,
2797    /// The directory a run names; `None` for a `terminal` call.
2798    run_dir: Option<&'a Path>,
2799}
2800
2801impl<'a> Admission<'a> {
2802    /// The tool call that carries the script and the agent that made it.
2803    const fn call(&self) -> Option<&CallIdentity> {
2804        self.call.as_ref()
2805    }
2806
2807    /// The SSH server the command names, when it names one.
2808    fn location(&self) -> Option<&'a str> {
2809        self.location.map(str::trim).filter(|name| !name.is_empty())
2810    }
2811
2812    /// Whether the script runs outside the sandbox, unsandboxed or on a
2813    /// server.
2814    fn crosses_boundary(&self) -> bool {
2815        self.mode == SandboxMode::Unsandboxed || self.location().is_some()
2816    }
2817
2818    /// What the approver is asked about a script the policies only passed.
2819    fn boundary_request(&self) -> ApprovalRequest {
2820        let (kind, reason) = if self.mode == SandboxMode::Unsandboxed {
2821            ("unsandboxed", "the script runs outside the sandbox")
2822        } else {
2823            ("remote", "the script runs on a remote server")
2824        };
2825        ApprovalRequest::new(ApprovalKind::new(kind), self.script).with_reason(reason)
2826    }
2827}
2828
2829/// What the policies' decisions leave admission to do, with a refusal
2830/// already answered.
2831enum Clearance {
2832    /// No policy decided: a script inside the sandbox runs, one that crosses
2833    /// its boundary is asked about.
2834    Pass,
2835    /// A policy approved the script.
2836    Allow,
2837    /// A policy asks the approver first.
2838    Ask(ApprovalRequest),
2839}
2840
2841struct ExecutionPreparation {
2842    target: ExecutionTarget,
2843    task_id: IdLease,
2844    execution_id: String,
2845    outputs: OutputStore,
2846    max_lines: usize,
2847    /// How the script's output is cleaned, as the shell's
2848    /// [`TreatOutput`](crate::TreatOutput) chose.
2849    treatment: OutputTreatment,
2850    /// The carried directory a foreground command starts in, when the
2851    /// terminal carries one and it still exists.
2852    carried_start: Option<PathBuf>,
2853}
2854
2855/// What the output pipeline does to a foreground script's stdout.
2856#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2857enum StdoutTreatment {
2858    /// The call asked for the bytes as written (`raw`): no stage applies,
2859    /// not even rendering.
2860    Raw,
2861    /// The pipeline runs under the script's output treatment.
2862    Cleaned(OutputTreatment),
2863}
2864
2865impl StdoutTreatment {
2866    /// The treatment of a `terminal` call's stdout: `raw` wins over the
2867    /// shell's choice.
2868    const fn of_call(raw: bool, treatment: OutputTreatment) -> Self {
2869        if raw {
2870            Self::Raw
2871        } else {
2872            Self::Cleaned(treatment)
2873        }
2874    }
2875}
2876
2877/// Where a run starts: `dir` on the host, mapped through the workspace
2878/// mount for a container command. A run carries no directory, so it writes
2879/// no report.
2880fn run_start(target: &ExecutionTarget, dir: PathBuf) -> Result<CwdCarry, ShellRunError> {
2881    let container = match &target.backend {
2882        ExecutionBackend::Local { .. } => None,
2883        ExecutionBackend::Container { runtime, .. } => {
2884            let mount = runtime
2885                .workspace_mount()
2886                .cloned()
2887                .ok_or(ShellRunError::NoWorkspaceMount)?;
2888            let start = mount.container_path(&dir)?;
2889            Some(ContainerCarry {
2890                mount,
2891                report: None,
2892                start,
2893            })
2894        }
2895        ExecutionBackend::Ssh { .. } => unreachable!("a run resolves the home backend"),
2896    };
2897    Ok(CwdCarry {
2898        start: Some(dir),
2899        report: None,
2900        container,
2901        shell: false,
2902        removed: false,
2903    })
2904}
2905
2906async fn wait_for_background_startup(
2907    startup_rx: &Receiver<Result<(), String>>,
2908    wording: &dyn ShellWording,
2909) -> anyhow::Result<()> {
2910    match startup_rx.recv().await {
2911        Ok(Ok(())) => Ok(()),
2912        Ok(Err(detail)) => Err(failed_run(wording, &detail)),
2913        Err(_) => Err(anyhow::Error::msg(
2914            wording.run_failure(&RunFailure::Terminal(&TerminalError::TaskLost)),
2915        )),
2916    }
2917}
2918
2919/// The error of a run whose execution failed with `detail`, worded.
2920fn failed_run(wording: &dyn ShellWording, detail: &str) -> anyhow::Error {
2921    anyhow::Error::msg(wording.run_failure(&RunFailure::Failed { detail }))
2922}
2923
2924/// Races the result channel against the foreground limit.
2925///
2926/// Returns `None` when the limit expired (or the channel was dropped, which
2927/// the caller treats the same way — the job is finished or killed).
2928async fn wait_for_foreground_result(
2929    result_rx: &Receiver<Result<CompletedCommand, String>>,
2930    limit: Duration,
2931) -> Option<Result<CompletedCommand, String>> {
2932    futures_lite::future::or(async { result_rx.recv().await.ok() }, async {
2933        async_io::Timer::after(limit).await;
2934        result_rx.try_recv().ok()
2935    })
2936    .await
2937}
2938
2939/// Detaches the running task `task_id` as a job: its output goes to a file
2940/// and the shell raises [`ShellEvent::JobStarted`].
2941async fn detach_job(
2942    job_registry: &JobRegistry,
2943    outputs: &OutputStore,
2944    task_id: &str,
2945    max_lines: usize,
2946    started_tx: &EventSender,
2947) -> aither_core::Result<Detached> {
2948    // The call still owns the job's completion, so the job is registered; the
2949    // hold keeps it past a consumer that takes the completion at once.
2950    let watch = job_registry
2951        .watch(task_id)
2952        .await
2953        .expect("a job whose call has not returned is registered");
2954    let redirect =
2955        start_background_output_redirect(job_registry, outputs, task_id, max_lines).await?;
2956    let _ = started_tx
2957        .send(ShellEvent::JobStarted(JobStarted {
2958            agent: started_tx.agent().clone(),
2959            task_id: task_id.to_string(),
2960            output_preview: redirect.preview.clone(),
2961            output_file: redirect.file.clone(),
2962        }))
2963        .await;
2964    Ok(Detached {
2965        task_id: task_id.to_string(),
2966        redirect,
2967        watch,
2968    })
2969}
2970
2971/// Output file a background job was redirected to, with what it holds so far.
2972struct BackgroundRedirect {
2973    file: StoredFile,
2974    /// First lines already written; empty when nothing was.
2975    preview: String,
2976    truncated: bool,
2977}
2978
2979async fn start_background_output_redirect(
2980    job_registry: &JobRegistry,
2981    outputs: &OutputStore,
2982    task_id: &str,
2983    max_lines: usize,
2984) -> Result<BackgroundRedirect, anyhow::Error> {
2985    let (url, output_path) = outputs.save_raw(&[]).await?;
2986    let file = StoredFile {
2987        url,
2988        path: output_path.display().to_string(),
2989    };
2990    let snapshot = job_registry
2991        .start_output_redirect(task_id, output_path)
2992        .await
2993        .map_err(anyhow::Error::msg)?;
2994    let (preview, truncated) = preview_first_lines(&snapshot, max_lines);
2995    Ok(BackgroundRedirect {
2996        file,
2997        preview: background_preview(&preview),
2998        truncated,
2999    })
3000}
3001
3002/// The preview of what a background job has written so far: empty when it
3003/// wrote only whitespace, otherwise the text with its trailing whitespace cut
3004/// and the first line's indentation kept.
3005fn background_preview(preview: &str) -> String {
3006    if preview.trim().is_empty() {
3007        String::new()
3008    } else {
3009        preview.trim_end().to_string()
3010    }
3011}
3012
3013struct StandaloneExecution<E> {
3014    /// The shell's sandbox: its directory, live grants, environment source,
3015    /// network policy, priority and home backend.
3016    sandbox: Sandbox,
3017    executor: E,
3018    /// The commands the job's processes may call back into the host with.
3019    ipc: Option<crate::AnyIpcProvider>,
3020    /// The worktrees the host's `git` shim maps for the command.
3021    committed: Vec<CommittingWorktree>,
3022    job_registry: JobRegistry,
3023    task_id: IdLease,
3024    /// What the job's processes are launched as.
3025    info: crate::LaunchInfo,
3026    execution_id: String,
3027    background: bool,
3028    carry: Option<CwdCarry>,
3029    carried_dir: Option<CarriedDir>,
3030    script: String,
3031    interpreter: Interpreter,
3032    mode: SandboxMode,
3033    backend: ExecutionBackend,
3034    lifetime: JobLifetime,
3035    background_startup: BackgroundStartup,
3036    #[cfg(all(unix, feature = "jobserver"))]
3037    jobserver: Option<JobBroker>,
3038    expect: OutputFormat,
3039    resolution: MediaResolution,
3040    outputs: OutputStore,
3041    max_lines: usize,
3042    stdout: StdoutTreatment,
3043}
3044
3045struct StandaloneStart<'a, E> {
3046    sandbox: &'a Sandbox,
3047    executor: E,
3048    ipc: Option<&'a crate::AnyIpcProvider>,
3049    committed: &'a [CommittingWorktree],
3050    job_registry: &'a JobRegistry,
3051    task_id: &'a IdLease,
3052    info: crate::LaunchInfo,
3053    execution_id: &'a str,
3054    carry: Option<&'a CwdCarry>,
3055    script: &'a str,
3056    interpreter: Interpreter,
3057    mode: SandboxMode,
3058    backend: &'a ExecutionBackend,
3059    lifetime: JobLifetime,
3060    background_startup: &'a BackgroundStartup,
3061    #[cfg(all(unix, feature = "jobserver"))]
3062    jobserver: &'a Option<JobBroker>,
3063}
3064
3065struct LocalBackgroundExecution<'a, E> {
3066    /// The shell program scripts run under.
3067    shell: &'a str,
3068    sandbox: &'a Sandbox,
3069    executor: E,
3070    ipc: Option<&'a crate::AnyIpcProvider>,
3071    committed: &'a [CommittingWorktree],
3072    task_id: &'a IdLease,
3073    info: crate::LaunchInfo,
3074    execution_id: &'a str,
3075    carry: Option<&'a CwdCarry>,
3076    script: &'a str,
3077    interpreter: Interpreter,
3078    mode: SandboxMode,
3079    job_registry: &'a JobRegistry,
3080    lifetime: JobLifetime,
3081    background_startup: &'a BackgroundStartup,
3082    #[cfg(all(unix, feature = "jobserver"))]
3083    job_fifo: Option<crate::jobserver::CommandFifo>,
3084}
3085
3086struct ContainerJobExecution<'a, E> {
3087    executor: E,
3088    sandbox: &'a Sandbox,
3089    ipc: Option<&'a crate::AnyIpcProvider>,
3090    committed: &'a [CommittingWorktree],
3091    task_id: &'a IdLease,
3092    info: crate::LaunchInfo,
3093    execution_id: &'a str,
3094    script: &'a str,
3095    interpreter: Interpreter,
3096    mode: SandboxMode,
3097    container_runtime: &'a ContainerShellRuntime,
3098    carry: Option<&'a CwdCarry>,
3099    job_registry: &'a JobRegistry,
3100    lifetime: JobLifetime,
3101    background_startup: &'a BackgroundStartup,
3102    /// The command's jobserver fifo inside the container, held until its
3103    /// exec has ended.
3104    #[cfg(all(unix, feature = "jobserver"))]
3105    job_fifo: Option<crate::container_jobserver::ContainerJobFifo>,
3106}
3107
3108struct SshBackgroundExecution<'a, E> {
3109    executor: E,
3110    sandbox: &'a Sandbox,
3111    launch: &'a RemoteLaunch,
3112    task_id: &'a IdLease,
3113    info: crate::LaunchInfo,
3114    execution_id: &'a str,
3115    script: &'a str,
3116    interpreter: Interpreter,
3117    mode: SandboxMode,
3118    client: &'a SshClient,
3119    server: &'a SshServer,
3120    heel: Option<&'a str>,
3121    job_registry: &'a JobRegistry,
3122    lifetime: JobLifetime,
3123    background_startup: &'a BackgroundStartup,
3124}
3125
3126struct CompletedProcessOutput<'a> {
3127    job_registry: &'a JobRegistry,
3128    task_id: &'a IdLease,
3129    output: std::process::Output,
3130    background_output: bool,
3131    outputs: &'a OutputStore,
3132    expect: OutputFormat,
3133    resolution: MediaResolution,
3134    max_lines: usize,
3135    stdout: StdoutTreatment,
3136}
3137
3138/// Where a command runs, with the programs the embedder prepared for exactly
3139/// that environment.
3140enum ExecutionBackend {
3141    /// The local sandbox.
3142    Local {
3143        /// The shell program scripts run under.
3144        shell: Arc<str>,
3145    },
3146    /// A container, whose programs its backend's launch names.
3147    Container {
3148        runtime: ContainerShellRuntime,
3149        /// Read only to open a command's jobserver fifo in the container.
3150        #[cfg(all(unix, feature = "jobserver"))]
3151        launch: crate::ContainerLaunch,
3152    },
3153    /// A remote host over SSH.
3154    Ssh {
3155        client: SshClient,
3156        server: SshServer,
3157        /// The server's `heel`, which a default-mode command runs under; an
3158        /// `unsafe` command has none.
3159        heel: Option<String>,
3160        launch: RemoteLaunch,
3161    },
3162}
3163
3164struct ExecutionTarget {
3165    mode: SandboxMode,
3166    backend: ExecutionBackend,
3167}
3168
3169struct TerminalSpawnRequest {
3170    target: ExecutionTarget,
3171    task_id: IdLease,
3172    execution_id: String,
3173    script: String,
3174    interpreter: Interpreter,
3175    expect: OutputFormat,
3176    resolution: MediaResolution,
3177    max_lines: usize,
3178    stdout: StdoutTreatment,
3179    background: bool,
3180    timeout: Duration,
3181    carry: Option<CwdCarry>,
3182    /// The `terminal` call this execution belongs to.
3183    call: Option<CallIdentity>,
3184}
3185
3186struct SpawnedTerminal {
3187    result: Receiver<Result<CompletedCommand, String>>,
3188    startup: Receiver<Result<(), String>>,
3189    /// Tells the job's flow the call returned its result itself; dropped
3190    /// unsent, the job is a background task whose completion the agent takes.
3191    taken: Sender<Sender<()>>,
3192}
3193
3194impl SpawnedTerminal {
3195    /// The call returns the job's result itself: nothing addresses the job
3196    /// once it does, so its flow takes the completion on the agent's behalf.
3197    /// Returns once the flow ended and the registry forgot the job, so the
3198    /// task id is back with the allocator when the call returns.
3199    async fn took_result(self) {
3200        let (done_tx, done_rx) = async_channel::bounded(1);
3201        // A flow that ended without a result no longer listens.
3202        if self.taken.send(done_tx).await.is_ok() {
3203            let _ = done_rx.recv().await;
3204        }
3205    }
3206}
3207
3208struct SpawnedTerminalTask<E> {
3209    sandbox: Sandbox,
3210    executor: E,
3211    policies: ScriptPolicies,
3212    ipc: Option<crate::AnyIpcProvider>,
3213    committed: Vec<CommittingWorktree>,
3214    job_registry: JobRegistry,
3215    task_id: IdLease,
3216    /// What the job's processes are launched as.
3217    info: crate::LaunchInfo,
3218    execution_id: String,
3219    background: bool,
3220    /// The bound the job runs under.
3221    timeout: Duration,
3222    carry: Option<CwdCarry>,
3223    carried_dir: Option<CarriedDir>,
3224    script: String,
3225    interpreter: Interpreter,
3226    mode: SandboxMode,
3227    backend: ExecutionBackend,
3228    lifetime: JobLifetime,
3229    background_startup: BackgroundStartup,
3230    expect: OutputFormat,
3231    resolution: MediaResolution,
3232    outputs: OutputStore,
3233    max_lines: usize,
3234    stdout: StdoutTreatment,
3235    result_tx: Sender<Result<CompletedCommand, String>>,
3236    /// Whether the call took the result: see [`SpawnedTerminal::took_result`].
3237    taken: Receiver<Sender<()>>,
3238    completed_tx: EventSender,
3239    running_tasks: Arc<AtomicUsize>,
3240    #[cfg(all(unix, feature = "jobserver"))]
3241    jobserver: Option<JobBroker>,
3242    outages: Outages,
3243}
3244
3245#[allow(clippy::too_many_lines)]
3246async fn execute_terminal_task<E>(task: SpawnedTerminalTask<E>)
3247where
3248    E: Executor + Clone + 'static,
3249{
3250    let SpawnedTerminalTask {
3251        sandbox,
3252        executor,
3253        policies,
3254        ipc,
3255        committed,
3256        job_registry,
3257        task_id,
3258        info,
3259        execution_id,
3260        background,
3261        timeout,
3262        carry,
3263        carried_dir,
3264        script,
3265        interpreter,
3266        mode,
3267        backend,
3268        lifetime,
3269        background_startup,
3270        expect,
3271        resolution,
3272        outputs,
3273        max_lines,
3274        stdout,
3275        result_tx,
3276        taken,
3277        completed_tx,
3278        running_tasks,
3279        #[cfg(all(unix, feature = "jobserver"))]
3280        jobserver,
3281        outages,
3282    } = task;
3283    // Before the job registers, so the registry reports the bound it runs under.
3284    job_registry.bound_by_timeout(&task_id, timeout).await;
3285    // Before the process starts, so a command it calls over IPC can already
3286    // append to this job's output.
3287    job_registry.launching(&task_id).await;
3288    let status_registry = job_registry.clone();
3289    // What the policies are told the next script starts in, spelled as this
3290    // script's backend names a directory.
3291    let end_view = (!policies.is_empty()).then(|| {
3292        (
3293            DirSpelling::of(&backend),
3294            carried_dir.clone(),
3295            sandbox.working_dir().to_path_buf(),
3296        )
3297    });
3298    let result = execute_script_standalone(StandaloneExecution {
3299        sandbox,
3300        executor,
3301        ipc,
3302        committed,
3303        job_registry,
3304        task_id: task_id.clone(),
3305        info,
3306        execution_id,
3307        background,
3308        carry,
3309        carried_dir,
3310        script: script.clone(),
3311        interpreter,
3312        mode,
3313        backend,
3314        lifetime,
3315        background_startup,
3316        #[cfg(all(unix, feature = "jobserver"))]
3317        jobserver,
3318        expect,
3319        resolution,
3320        outputs,
3321        max_lines,
3322        stdout,
3323    })
3324    .await;
3325    // A process that never started leaves no job to register.
3326    status_registry.abandon_launch(&task_id).await;
3327    let interruptions = outages.end(&task_id).await;
3328    let (result, settled) = match result {
3329        Ok((command, settled)) => (Ok(command), Some(settled)),
3330        Err(error) => (Err(error), None),
3331    };
3332    let result = result.map(|command| CompletedCommand {
3333        interruptions,
3334        ..command
3335    });
3336    // Ahead of the result, so what a policy records of this end holds for
3337    // the agent's next call.
3338    let outcome = result
3339        .as_ref()
3340        .map_or(ScriptOutcome::Failed, |command| ScriptOutcome::Exited {
3341            code: command.exit_code,
3342        });
3343    if let Some((spelling, carried, working_dir)) = &end_view {
3344        // A settled script already read the carried directory under the
3345        // lock that recorded it; one that settled nothing reads it now.
3346        let (carry, host) = match settled {
3347            Some(Settled { carry, carried }) => (carry, carried),
3348            None => (
3349                Carry::NotCarried,
3350                carried.as_ref().and_then(CarriedDir::get),
3351            ),
3352        };
3353        let own = canonical_path(working_dir)
3354            .await
3355            .unwrap_or_else(|_| working_dir.clone());
3356        let end = spelling.dir(host, &own);
3357        policies.ended(&task_id, outcome, &end, carry).await;
3358    }
3359
3360    let quick_result = match &result {
3361        Ok(ok) => Ok(ok.clone()),
3362        Err(err) => Err(err.detail().into_owned()),
3363    };
3364    let _ = result_tx.send(quick_result).await;
3365    // The call answers at once, taking the result or leaving it to a
3366    // background task.
3367    let foreground = taken.recv().await.ok();
3368    // A kill's signal can end the process before the kill records its
3369    // outcome, so the registry settles the ending once no kill is in flight.
3370    let ending = match &result {
3371        Ok(command) => Ok(command.exit_code),
3372        Err(error) => Err(error.detail().into_owned()),
3373    };
3374    // The job as it ended, settled before a foreground result takes it.
3375    let (info, pending) = match status_registry.owe_completion(&task_id, ending).await {
3376        Some(owed) => (Some(owed.info), owed.pending),
3377        None => (None, None),
3378    };
3379    let kill = info.as_ref().and_then(|info| info.status.kill_cause());
3380    // A result the call returned leaves nothing for the agent to take: the
3381    // completion is taken here, so the registry forgets the job, and the end
3382    // is no fact to raise: the call already told it.
3383    let pending = match foreground {
3384        Some(_) => {
3385            if let Some(pending) = pending {
3386                pending.take().await;
3387            }
3388            None
3389        }
3390        None => pending,
3391    };
3392    // Only a job, one promoted past the foreground window or started in the
3393    // background, reports its end. A command the shell never registered, one
3394    // that failed to start, has no job to report.
3395    if foreground.is_none()
3396        && let Some(info) = info
3397    {
3398        let timeout_kill = match kill {
3399            Some(crate::KillCause::Timeout(kill)) => Some(kill),
3400            _ => None,
3401        };
3402        let _ = completed_tx
3403            .send(ShellEvent::JobEnded(Box::new(JobEnded {
3404                agent: completed_tx.agent().clone(),
3405                info,
3406                result,
3407                timeout_kill,
3408                pending,
3409            })))
3410            .await;
3411    }
3412    running_tasks.fetch_sub(1, Ordering::AcqRel);
3413    // The flow's own hold on the word ends before the call returns.
3414    drop(task_id);
3415    if let Some(done) = foreground {
3416        let _ = done.send(()).await;
3417    }
3418}
3419
3420/// Standalone script execution that can be spawned in a background task.
3421#[allow(clippy::too_many_lines)]
3422async fn execute_script_standalone<E>(
3423    request: StandaloneExecution<E>,
3424) -> Result<(CompletedCommand, Settled), TerminalError>
3425where
3426    E: Executor + Clone + 'static,
3427{
3428    let StandaloneExecution {
3429        sandbox,
3430        executor,
3431        ipc,
3432        committed,
3433        job_registry,
3434        task_id,
3435        info,
3436        execution_id,
3437        background,
3438        carry,
3439        carried_dir,
3440        script,
3441        interpreter,
3442        mode,
3443        backend,
3444        lifetime,
3445        background_startup,
3446        #[cfg(all(unix, feature = "jobserver"))]
3447        jobserver,
3448        expect,
3449        resolution,
3450        outputs,
3451        max_lines,
3452        stdout,
3453    } = request;
3454
3455    info!(
3456        script_len = script.len(),
3457        ?mode,
3458        "executing background terminal command"
3459    );
3460    debug!(script = %script, "script content");
3461    let start_result = start_standalone_execution(StandaloneStart {
3462        sandbox: &sandbox,
3463        executor,
3464        ipc: ipc.as_ref(),
3465        committed: &committed,
3466        job_registry: &job_registry,
3467        task_id: &task_id,
3468        info,
3469        execution_id: &execution_id,
3470        carry: carry.as_ref(),
3471        script: &script,
3472        interpreter,
3473        mode,
3474        backend: &backend,
3475        lifetime,
3476        background_startup: &background_startup,
3477        #[cfg(all(unix, feature = "jobserver"))]
3478        jobserver: &jobserver,
3479    })
3480    .await;
3481    let output = match start_result {
3482        Ok(started) => started,
3483        Err(error) => {
3484            background_startup.report_failure(&error).await;
3485            return Err(error);
3486        }
3487    };
3488
3489    let result = save_completed_process_output(CompletedProcessOutput {
3490        job_registry: &job_registry,
3491        task_id: &task_id,
3492        output,
3493        background_output: background,
3494        outputs: &outputs,
3495        expect,
3496        resolution,
3497        max_lines,
3498        stdout,
3499    })
3500    .await?;
3501    let exit_code = result.exit_code;
3502
3503    debug!(exit_code, "background script completed");
3504
3505    let output_path = stored_path(&result.stdout);
3506    job_registry
3507        .complete(&task_id, exit_code, output_path)
3508        .await;
3509
3510    // The command's directory report arrives with its end, whether the call
3511    // answered in the foreground window or the command promoted: the task
3512    // is its sole consumer, so the next command starts where the shell
3513    // ended and the report file never lingers.
3514    let settled = match &carry {
3515        Some(carry) => {
3516            let ctx = CarryContext {
3517                carried_dir: carried_dir.as_ref(),
3518                working_dir: sandbox.working_dir(),
3519                grants: sandbox.grants().snapshot(),
3520            };
3521            settle_cwd(carry, take_cwd_report(carry).await, exit_code == 0, &ctx).await
3522        }
3523        // Nothing carries: a background or subagent script, a run, or a
3524        // script on a server. The next script starts where it would have.
3525        None => Settled {
3526            carry: Carry::NotCarried,
3527            carried: carried_dir.as_ref().and_then(CarriedDir::get),
3528        },
3529    };
3530
3531    Ok((result, settled))
3532}
3533
3534#[allow(clippy::too_many_lines)]
3535async fn start_standalone_execution<E>(
3536    request: StandaloneStart<'_, E>,
3537) -> Result<std::process::Output, TerminalError>
3538where
3539    E: Executor + Clone + 'static,
3540{
3541    let shell = match request.backend {
3542        ExecutionBackend::Local { shell } => shell.as_ref(),
3543        ExecutionBackend::Container {
3544            runtime,
3545            #[cfg(all(unix, feature = "jobserver"))]
3546            launch,
3547            ..
3548        } => {
3549            // The command's fifo lives in the container's kernel, brokered
3550            // by a relay run with the `python3` the launch's programs hold.
3551            #[cfg(all(unix, feature = "jobserver"))]
3552            let job_fifo = match request.jobserver {
3553                Some(broker) => Some(
3554                    crate::container_jobserver::open_container_job_fifo(
3555                        broker,
3556                        runtime,
3557                        &launch.bin_dir().join("python3"),
3558                        request.executor.clone(),
3559                    )
3560                    .await?,
3561                ),
3562                None => None,
3563            };
3564            return execute_container_job(ContainerJobExecution {
3565                executor: request.executor,
3566                sandbox: request.sandbox,
3567                ipc: request.ipc,
3568                committed: request.committed,
3569                task_id: request.task_id,
3570                info: request.info,
3571                execution_id: request.execution_id,
3572                script: request.script,
3573                interpreter: request.interpreter,
3574                mode: request.mode,
3575                container_runtime: runtime,
3576                carry: request.carry,
3577                job_registry: request.job_registry,
3578                lifetime: request.lifetime,
3579                background_startup: request.background_startup,
3580                #[cfg(all(unix, feature = "jobserver"))]
3581                job_fifo,
3582            })
3583            .await;
3584        }
3585        ExecutionBackend::Ssh {
3586            client,
3587            server,
3588            heel,
3589            launch,
3590        } => {
3591            // The pool bounds the jobs of this machine; the server is another
3592            // machine, so its commands take no token and get no fifo.
3593            return execute_ssh_background(SshBackgroundExecution {
3594                executor: request.executor,
3595                sandbox: request.sandbox,
3596                launch,
3597                task_id: request.task_id,
3598                info: request.info,
3599                execution_id: request.execution_id,
3600                script: request.script,
3601                interpreter: request.interpreter,
3602                mode: request.mode,
3603                client,
3604                server,
3605                heel: heel.as_deref(),
3606                job_registry: request.job_registry,
3607                lifetime: request.lifetime,
3608                background_startup: request.background_startup,
3609            })
3610            .await;
3611        }
3612    };
3613    #[cfg(all(unix, feature = "jobserver"))]
3614    let job_fifo = match request.jobserver {
3615        Some(broker) => Some(broker.open_fifo().await?),
3616        None => None,
3617    };
3618    let local = LocalBackgroundExecution {
3619        shell,
3620        sandbox: request.sandbox,
3621        executor: request.executor,
3622        ipc: request.ipc,
3623        committed: request.committed,
3624        task_id: request.task_id,
3625        info: request.info,
3626        execution_id: request.execution_id,
3627        carry: request.carry,
3628        script: request.script,
3629        interpreter: request.interpreter,
3630        mode: request.mode,
3631        job_registry: request.job_registry,
3632        lifetime: request.lifetime,
3633        background_startup: request.background_startup,
3634        #[cfg(all(unix, feature = "jobserver"))]
3635        job_fifo,
3636    };
3637    // Unsafe mode bypasses the proxy entirely, so its connections are not
3638    // audited at this layer.
3639    execute_local_background(local).await
3640}
3641
3642async fn save_completed_process_output(
3643    request: CompletedProcessOutput<'_>,
3644) -> Result<CompletedCommand, TerminalError> {
3645    let CompletedProcessOutput {
3646        job_registry,
3647        task_id,
3648        output,
3649        background_output,
3650        outputs,
3651        expect,
3652        resolution,
3653        max_lines,
3654        stdout,
3655    } = request;
3656    let stdout = save_completed_stdout(
3657        job_registry,
3658        task_id,
3659        &output.stdout,
3660        CompletedStdoutFormat {
3661            background_output,
3662            outputs,
3663            expect,
3664            resolution,
3665            max_lines,
3666            stdout,
3667        },
3668    )
3669    .await?;
3670    let stderr = save_completed_stderr(job_registry, task_id, outputs, &output.stderr).await?;
3671    let exit_code = output.status.code().unwrap_or(-1);
3672
3673    Ok(CompletedCommand {
3674        stdout,
3675        stderr,
3676        exit_code,
3677        interruptions: Vec::new(),
3678    })
3679}
3680
3681struct CompletedStdoutFormat<'a> {
3682    background_output: bool,
3683    outputs: &'a OutputStore,
3684    expect: OutputFormat,
3685    resolution: MediaResolution,
3686    max_lines: usize,
3687    stdout: StdoutTreatment,
3688}
3689
3690async fn save_completed_stdout(
3691    job_registry: &JobRegistry,
3692    task_id: &IdLease,
3693    stdout: &[u8],
3694    format: CompletedStdoutFormat<'_>,
3695) -> Result<CommandStream, TerminalError> {
3696    let byte_limit = Some(format.outputs.policy().get().inline_bytes);
3697    let data_to_save = if format.background_output {
3698        Cow::Borrowed(stdout)
3699    } else {
3700        compressed_stdout_data(format.outputs, stdout, format.expect, format.stdout).await?
3701    };
3702
3703    match format
3704        .outputs
3705        .save_text_with_line_limit(
3706            data_to_save.as_ref(),
3707            format.expect,
3708            format.resolution,
3709            format.max_lines,
3710            byte_limit,
3711        )
3712        .await
3713    {
3714        Ok(entry) => Ok(entry),
3715        Err(err) => {
3716            job_registry.fail(task_id, &err.to_string(), None).await;
3717            Err(TerminalError::Io(err))
3718        }
3719    }
3720}
3721
3722/// Runs the output cleaning pipeline over a completed command's stdout,
3723/// under the script's output treatment.
3724///
3725/// [`StdoutTreatment::Raw`] bypasses it entirely, as do non-text formats and
3726/// output that is not valid UTF-8, so the model sees exactly the bytes the
3727/// command wrote.
3728async fn compressed_stdout_data<'a>(
3729    outputs: &OutputStore,
3730    stdout: &'a [u8],
3731    expect: OutputFormat,
3732    treatment: StdoutTreatment,
3733) -> Result<Cow<'a, [u8]>, TerminalError> {
3734    let is_text = matches!(expect, OutputFormat::Text | OutputFormat::Auto);
3735    let StdoutTreatment::Cleaned(treatment) = treatment else {
3736        return Ok(Cow::Borrowed(stdout));
3737    };
3738    if !is_text || stdout.is_empty() {
3739        return Ok(Cow::Borrowed(stdout));
3740    }
3741    let Ok(text) = std::str::from_utf8(stdout) else {
3742        return Ok(Cow::Borrowed(stdout));
3743    };
3744
3745    let cleaned = crate::output_compress::compress_text(outputs, text, treatment)
3746        .await
3747        .map_err(TerminalError::Io)?;
3748    Ok(cleaned.map_or(Cow::Borrowed(stdout), |cleaned| {
3749        Cow::Owned(cleaned.into_bytes())
3750    }))
3751}
3752
3753async fn save_completed_stderr(
3754    job_registry: &JobRegistry,
3755    task_id: &IdLease,
3756    outputs: &OutputStore,
3757    stderr: &[u8],
3758) -> Result<Option<CommandStream>, TerminalError> {
3759    if stderr.is_empty() {
3760        return Ok(None);
3761    }
3762    match outputs
3763        .save_with_limit(
3764            stderr,
3765            OutputFormat::Text,
3766            MediaResolution::Auto,
3767            Some(outputs.policy().get().inline_bytes),
3768        )
3769        .await
3770    {
3771        Ok(entry) => Ok(Some(entry)),
3772        Err(err) => {
3773            job_registry.fail(task_id, &err.to_string(), None).await;
3774            Err(TerminalError::Io(err))
3775        }
3776    }
3777}
3778
3779/// The script a container's command runs ahead of its own: the worktree map
3780/// as exports. Empty without a map — subagent containers never see it.
3781#[cfg(unix)]
3782fn container_git_preamble(
3783    committed: &[CommittingWorktree],
3784    mount: Option<&MountRoot>,
3785) -> Result<String, TerminalError> {
3786    use std::fmt::Write as _;
3787    let mut environment = Vec::new();
3788    // A program inside the container compares its working directory against
3789    // the map: every path it holds must be spelled the way the container's
3790    // workspace mount resolves it.
3791    let spell = |path: &Path| -> Result<String, TerminalError> {
3792        let mount = mount.ok_or_else(|| {
3793            TerminalError::SandboxSetup(format!(
3794                "a committing worktree {} has no workspace mount to map through",
3795                path.display()
3796            ))
3797        })?;
3798        let host_root =
3799            std::fs::canonicalize(&mount.host_root).unwrap_or_else(|_| mount.host_root.clone());
3800        MountRoot::new(host_root, mount.container_root.clone())
3801            .container_path(path)
3802            .map(|path| path.to_string())
3803            .map_err(|source| {
3804                TerminalError::SandboxSetup(format!(
3805                    "{} is outside the container workspace mount: {source}",
3806                    path.display()
3807                ))
3808            })
3809    };
3810    committed_git_environment(committed, &mut environment, spell)?;
3811    let mut preamble = String::new();
3812    for (name, value) in &environment {
3813        writeln!(preamble, "export {name}={}", shell_words::quote(value))
3814            .expect("a string cannot fail a write");
3815    }
3816    Ok(preamble)
3817}
3818
3819#[cfg(not(unix))]
3820fn container_git_preamble(
3821    _committed: &[CommittingWorktree],
3822    _mount: Option<&MountRoot>,
3823) -> Result<String, TerminalError> {
3824    Ok(String::new())
3825}
3826
3827/// Exports the worktree map of a main shell's commands, each path spelled
3828/// the way `spell` resolves it for the command's context: a host path
3829/// locally, a container path inside a container.
3830///
3831/// The map only describes paths the host resolved when the grant was made;
3832/// a program of the embedder's that runs `git` in a committing worktree
3833/// reads the worktree's host-owned repository entry from it, so nothing a
3834/// subagent wrote decides what program git runs. A subagent shell holds
3835/// none.
3836fn committed_git_environment(
3837    committed: &[CommittingWorktree],
3838    environment: &mut Vec<(String, String)>,
3839    spell: impl Fn(&Path) -> Result<String, TerminalError>,
3840) -> Result<(), TerminalError> {
3841    if committed.is_empty() {
3842        return Ok(());
3843    }
3844    environment.push((
3845        "AITHER_GIT_WORKTREES_COUNT".to_string(),
3846        committed.len().to_string(),
3847    ));
3848    for (index, worktree) in committed.iter().enumerate() {
3849        environment.push((
3850            format!("AITHER_GIT_WORKTREE_PATH_{index}"),
3851            spell(worktree.worktree())?,
3852        ));
3853        environment.push((
3854            format!("AITHER_GIT_WORKTREE_GITDIR_{index}"),
3855            spell(worktree.git_dir())?,
3856        ));
3857    }
3858    Ok(())
3859}
3860
3861/// The grant a command's jobserver fifo needs: it writes tokens back to it.
3862#[cfg(all(unix, feature = "jobserver"))]
3863pub fn job_fifo_grant(path: &Path) -> heel::Result<heel::Grant> {
3864    Ok(heel::Grant::new(
3865        crate::spawn::resolved(path)?,
3866        heel::Access::WRITE,
3867    ))
3868}
3869
3870/// Runs a command on the host: sandboxed through the terminal's [`Sandbox`],
3871/// or with host access for an approved `unsafe` one.
3872async fn execute_local_background<E: Executor + Clone + 'static>(
3873    context: LocalBackgroundExecution<'_, E>,
3874) -> Result<std::process::Output, TerminalError> {
3875    // What this one command adds to the sandbox: its jobserver variables and
3876    // fifo grant, and the worktree map of a main shell.
3877    let mut environment = Vec::new();
3878    #[cfg_attr(not(all(unix, feature = "jobserver")), allow(unused_mut))]
3879    let mut grants = Vec::new();
3880    #[cfg(all(unix, feature = "jobserver"))]
3881    if let Some(fifo) = &context.job_fifo {
3882        grants.push(
3883            job_fifo_grant(fifo.path())
3884                .map_err(|error| TerminalError::SandboxSetup(error.to_string()))?,
3885        );
3886        environment.extend(fifo.environment());
3887    }
3888    committed_git_environment(context.committed, &mut environment, |path| {
3889        Ok(path.display().to_string())
3890    })?;
3891    let sandbox = match context.mode {
3892        SandboxMode::Sandboxed => context.sandbox.clone(),
3893        SandboxMode::Unsandboxed => context.sandbox.clone().unconfined(),
3894    };
3895
3896    let launch_script = launch_script(context.interpreter, context.script, context.task_id)?;
3897    let launch = build_terminal_launch(
3898        context.shell,
3899        &launch_script,
3900        context.carry.and_then(|carry| carry.report.as_deref()),
3901    )?;
3902    let (program, args) = match launch {
3903        TerminalLaunch::Direct { program, args } | TerminalLaunch::Shell { program, args } => {
3904            (program, args)
3905        }
3906    };
3907
3908    let mut spec = context.lifetime.applied_to(
3909        SpawnSpec::new(program)
3910            .args(args)
3911            .env(environment)
3912            .launch_info(context.info.clone()),
3913    );
3914    spec = spec
3915        .grants(grants.into_iter().map(crate::SpawnGrant::Host))
3916        .ipc(context.ipc.and_then(|ipc| ipc.router(&context.info)));
3917    if let Some(start) = context.carry.and_then(|carry| carry.start.as_deref()) {
3918        spec = spec.cwd(start);
3919    }
3920    let LocalSpawn {
3921        child,
3922        tree,
3923        sandbox: _sandbox,
3924    } = sandbox.spawn_local(spec).await?;
3925
3926    let pid = child.id();
3927    context
3928        .job_registry
3929        .register_with_tree(
3930            pid,
3931            context.task_id,
3932            context.execution_id,
3933            context.script,
3934            context.interpreter,
3935            context.mode,
3936            None,
3937            Some(tree.clone()),
3938            crate::JobPlace::Host,
3939        )
3940        .await;
3941
3942    let output = collect_local_process_output(
3943        child,
3944        context.executor,
3945        context.job_registry,
3946        context.task_id,
3947        LocalJob {
3948            pid,
3949            tree,
3950            lifetime: context.lifetime,
3951            startup: context.background_startup,
3952        },
3953        "missing stdout pipe for local process",
3954        "missing stderr pipe for local process",
3955    )
3956    .await?;
3957
3958    Ok(output)
3959}
3960
3961/// How long a command's descendants may outlive its top-level shell, and
3962/// what the command reads on stdin.
3963///
3964/// Both follow from whether the call waits for the command: nothing feeds a
3965/// call that waits, so its stdin is the null device, and a background job's
3966/// is a pipe the agent feeds through the input tool. [`Self::applied_to`] is
3967/// the one place a spawn takes them from, on every backend.
3968#[derive(Clone)]
3969enum JobLifetime {
3970    /// None: the survivors are killed and reported on `alerts`, as those of
3971    /// the command `task_id` that the tool call `call` ran. Its stdin reads
3972    /// EOF at once, and still does once the call promotes it to a job past
3973    /// the foreground window.
3974    Foreground {
3975        alerts: EventSender,
3976        task_id: String,
3977        call: Option<CallIdentity>,
3978    },
3979    /// All of them: the job runs until its whole tree has exited. Its stdin
3980    /// is a pipe, and a reader blocked on it is reported through `stdin`
3981    /// where the backend can watch it.
3982    Background { stdin: StdinAlerts },
3983}
3984
3985impl JobLifetime {
3986    /// `spec` spawned under this lifetime: what the backend does with the
3987    /// descendants its top-level process leaves, and its stdin.
3988    const fn applied_to(&self, spec: SpawnSpec) -> SpawnSpec {
3989        let (tree, stdin) = match self {
3990            Self::Foreground { .. } => (TreeLifetime::Foreground, Pipe::Null),
3991            Self::Background { .. } => (TreeLifetime::Background, Pipe::Piped),
3992        };
3993        spec.lifetime(tree).stdio(SpawnStdio {
3994            stdin,
3995            stdout: Pipe::Piped,
3996            stderr: Pipe::Piped,
3997        })
3998    }
3999
4000    /// Where a reader blocked on the job's stdin pipe is reported; `None` for
4001    /// a foreground command, which has no pipe.
4002    const fn stdin_alerts(&self) -> Option<&StdinAlerts> {
4003        match self {
4004            Self::Foreground { .. } => None,
4005            Self::Background { stdin } => Some(stdin),
4006        }
4007    }
4008
4009    /// Reports `killed` as the descendants a foreground command left; a
4010    /// background job's are never killed, so it reports nothing.
4011    async fn report_descendants_killed(&self, killed: Vec<JobProcess>) {
4012        let Self::Foreground {
4013            alerts,
4014            task_id,
4015            call,
4016        } = self
4017        else {
4018            return;
4019        };
4020        let _ = alerts
4021            .send(ShellEvent::DescendantsKilled(DescendantsKilled {
4022                agent: alerts.agent().clone(),
4023                task_id: task_id.clone(),
4024                call: call.clone(),
4025                processes: killed,
4026            }))
4027            .await;
4028    }
4029}
4030
4031/// Where a background job's stdin alerts go: the job of `task_id`, running
4032/// `script`.
4033#[derive(Clone)]
4034struct StdinAlerts {
4035    tx: EventSender,
4036    task_id: String,
4037    script: String,
4038}
4039
4040impl StdinAlerts {
4041    /// Raises an alert for each signal a stdin watch sends, until the watch
4042    /// ends.
4043    async fn relay(self, signals: async_channel::Receiver<StdinWatchSignal>) {
4044        while let Ok(signal) = signals.recv().await {
4045            match signal {
4046                StdinWatchSignal::Blocked => self.raise().await,
4047                StdinWatchSignal::Failed(error) => self.raise_failure(error).await,
4048            }
4049        }
4050    }
4051
4052    async fn raise(&self) {
4053        debug!(task_id = %self.task_id, "background job is blocked on stdin");
4054        let _ = self
4055            .tx
4056            .send(ShellEvent::StdinBlocked(StdinBlocked {
4057                agent: self.tx.agent().clone(),
4058                task_id: self.task_id.clone(),
4059                script: self.script.clone(),
4060            }))
4061            .await;
4062    }
4063
4064    /// Tells the agent this job's stdin watch died: no blocked-on-stdin
4065    /// alert can come for it anymore.
4066    async fn raise_failure(&self, error: String) {
4067        warn!(task_id = %self.task_id, error = %error, "stdin watch failed");
4068        let _ = self
4069            .tx
4070            .send(ShellEvent::StdinWatchFailed(StdinWatchFailed {
4071                agent: self.tx.agent().clone(),
4072                task_id: self.task_id.clone(),
4073                script: self.script.clone(),
4074                error,
4075            }))
4076            .await;
4077    }
4078}
4079
4080/// Watches one local background job's stdin pipe for a waiting reader.
4081pub struct LocalStdinWatch {
4082    probe: LocalStdinProbe,
4083    feed: FeedCounter,
4084    detector: EpisodeDetector,
4085    signals: async_channel::Sender<StdinWatchSignal>,
4086}
4087
4088impl LocalStdinWatch {
4089    /// A watch of the pipe `probe` looks at that `feed` counts the writes to,
4090    /// reporting on `signals`.
4091    pub(crate) fn new(
4092        probe: LocalStdinProbe,
4093        feed: FeedCounter,
4094        signals: async_channel::Sender<StdinWatchSignal>,
4095    ) -> Self {
4096        Self {
4097            probe,
4098            feed,
4099            detector: EpisodeDetector::default(),
4100            signals,
4101        }
4102    }
4103
4104    /// Probes the pipe every [`STDIN_WATCH_INTERVAL`] and signals one
4105    /// [`StdinWatchSignal::Blocked`] per blocking episode, for as long as the
4106    /// future is polled.
4107    async fn run(mut self) -> std::convert::Infallible {
4108        loop {
4109            async_io::Timer::after(STDIN_WATCH_INTERVAL).await;
4110            let Self {
4111                probe,
4112                feed,
4113                mut detector,
4114                signals,
4115            } = self;
4116            let fed = feed.count();
4117            let (probe, observed) = blocking::unblock(move || {
4118                let observed = probe.probe();
4119                (probe, observed)
4120            })
4121            .await;
4122            match observed {
4123                Ok(observed) => {
4124                    if detector.observe(fed, observed) {
4125                        let _ = signals.send(StdinWatchSignal::Blocked).await;
4126                    }
4127                }
4128                Err(error) => {
4129                    // Detection cannot run: surface it once, then park — the
4130                    // job's exit still ends the race in
4131                    // `wait_for_local_process_exit`.
4132                    let _ = signals
4133                        .send(StdinWatchSignal::Failed(error.to_string()))
4134                        .await;
4135                    std::future::pending::<()>().await;
4136                }
4137            }
4138            self = Self {
4139                probe,
4140                feed,
4141                detector,
4142                signals,
4143            };
4144        }
4145    }
4146}
4147
4148async fn collect_local_process_output<E: Executor + Clone + 'static>(
4149    mut child: LocalChild,
4150    executor: E,
4151    job_registry: &JobRegistry,
4152    task_id: &IdLease,
4153    job: LocalJob<'_>,
4154    missing_stdout_message: &'static str,
4155    missing_stderr_message: &'static str,
4156) -> Result<std::process::Output, TerminalError> {
4157    let LocalJob {
4158        pid,
4159        tree,
4160        lifetime,
4161        startup,
4162    } = job;
4163    // A background job's stdin pipe is fed through the registry and watched;
4164    // a foreground command reads the null device and has none.
4165    let mut stdin_watch = None;
4166    if let Some(alerts) = lifetime.stdin_alerts() {
4167        let stdin = child.take_stdin().ok_or_else(|| {
4168            TerminalError::Execution("missing stdin pipe for local process".into())
4169        })?;
4170        let feed = FeedCounter::default();
4171        let probe = LocalStdinProbe::new(pid, &stdin)
4172            .map_err(|error| TerminalError::Execution(format!("stdin probe: {error}")))?;
4173        let (signal_tx, signal_rx) = async_channel::unbounded();
4174        executor.spawn(alerts.clone().relay(signal_rx)).detach();
4175        stdin_watch = Some(LocalStdinWatch::new(probe, feed.clone(), signal_tx));
4176        job_registry
4177            .attach_terminal_input(task_id, write_chunks(stdin, feed))
4178            .await;
4179    }
4180    // Only now: a job that has a pipe takes input from the moment its call
4181    // can name it.
4182    startup.report_ready().await;
4183
4184    let stdout = child
4185        .take_stdout()
4186        .ok_or_else(|| TerminalError::Execution(missing_stdout_message.into()))?;
4187    let stderr = child
4188        .take_stderr()
4189        .ok_or_else(|| TerminalError::Execution(missing_stderr_message.into()))?;
4190
4191    let (chunk_tx, chunk_rx) = async_channel::unbounded();
4192    spawn_terminal_reader(stdout, chunk_tx.clone(), false);
4193    spawn_terminal_reader(stderr, chunk_tx.clone(), true);
4194    drop(chunk_tx);
4195    executor
4196        .spawn(drain_terminal_chunks(
4197            job_registry.clone(),
4198            task_id.downgrade(),
4199            chunk_rx,
4200        ))
4201        .detach();
4202
4203    // The root stays unreaped until its tree is gone, so its pid and process
4204    // group stay reserved while the job's descendants are tracked by them.
4205    let exited = match wait_for_local_process_exit(&mut child, stdin_watch).await {
4206        Ok(exited) => exited,
4207        Err(error) => {
4208            tree.finish().await;
4209            job_registry.close_stdout(task_id).await;
4210            job_registry.close_stderr(task_id).await;
4211            return Err(error);
4212        }
4213    };
4214    let descendants = end_descendants(&tree, &lifetime).await;
4215    // The task ends first: afterwards the root's pid may belong to anyone.
4216    tree.finish().await;
4217    let (status, report) = match exited {
4218        Some(status) => (Ok(status), None),
4219        None => match child.wait_reported().await {
4220            Ok((status, report)) => (Ok(status), report),
4221            Err(error) => (Err(TerminalError::Execution(error.to_string())), None),
4222        },
4223    };
4224    let _ = &report;
4225    #[cfg(target_os = "linux")]
4226    if let Some(report) = report {
4227        let killed: Vec<JobProcess> = report
4228            .killed
4229            .into_iter()
4230            .map(|process| JobProcess {
4231                pid: process.pid,
4232                name: process.name,
4233            })
4234            .collect();
4235        if !killed.is_empty() {
4236            info!(
4237                killed = killed.len(),
4238                "the supervisor killed the finished command's descendants"
4239            );
4240            lifetime.report_descendants_killed(killed).await;
4241        }
4242    }
4243    let status = match (descendants, status) {
4244        (Ok(()), Ok(status)) => status,
4245        (Err(error), _) | (Ok(()), Err(error)) => {
4246            job_registry.close_stdout(task_id).await;
4247            job_registry.close_stderr(task_id).await;
4248            job_registry.fail(task_id, &error.detail(), None).await;
4249            return Err(error);
4250        }
4251    };
4252    wait_for_terminal_stream_close(job_registry, task_id).await;
4253    let (stdout, stderr) = job_registry.terminal_output(task_id).await.ok_or_else(|| {
4254        TerminalError::Execution(format!("missing terminal output for task {task_id}"))
4255    })?;
4256    let output = std::process::Output {
4257        status,
4258        stdout,
4259        stderr,
4260    };
4261
4262    Ok(output)
4263}
4264
4265/// A local job's process tree, how long its descendants may live, and where
4266/// its start is reported once it takes input.
4267struct LocalJob<'a> {
4268    /// The root process's id, for the stdin probe: the registry never
4269    /// identifies the job by it.
4270    pid: u32,
4271    tree: JobTree,
4272    lifetime: JobLifetime,
4273    startup: &'a BackgroundStartup,
4274}
4275
4276/// The teardown budget a job's supervisor gives its kills: the time to
4277/// freeze the tree, deliver `SIGKILL` and see every killed process exit.
4278/// Generous relative to the few milliseconds a `SIGKILL` exit takes, since a
4279/// too-short budget reports survivors that are merely still exiting.
4280#[cfg(target_os = "linux")]
4281pub const SUPERVISED_REAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
4282
4283/// A spawned local job: the plain `heel` child on platforms without a
4284/// supervisor, or a `heel supervise`-supervised one on Linux, where the
4285/// supervisor is the command's parent and owns its whole tree.
4286pub enum LocalChild {
4287    /// Everywhere but Linux: the sandboxed process itself.
4288    #[cfg_attr(target_os = "linux", allow(dead_code))]
4289    Plain(heel::Child),
4290    /// Linux, foreground lifetime: `wait` yields the command's status and
4291    /// the teardown's report of what it killed.
4292    #[cfg(target_os = "linux")]
4293    Foreground(heel::supervisor::SupervisedChild<heel::supervisor::Foreground>),
4294    /// Linux, background lifetime: `wait` ends only once the last descendant
4295    /// of the command has exited.
4296    #[cfg(target_os = "linux")]
4297    Background(heel::supervisor::SupervisedChild<heel::supervisor::Background>),
4298}
4299
4300impl LocalChild {
4301    /// The spawned process's id: the supervisor's on Linux.
4302    pub(crate) fn id(&self) -> u32 {
4303        match self {
4304            Self::Plain(child) => child.id(),
4305            #[cfg(target_os = "linux")]
4306            Self::Foreground(child) => child.id(),
4307            #[cfg(target_os = "linux")]
4308            Self::Background(child) => child.id(),
4309        }
4310    }
4311
4312    pub(crate) fn take_stdin(&mut self) -> Option<std::fs::File> {
4313        match self {
4314            Self::Plain(child) => child.take_stdin(),
4315            #[cfg(target_os = "linux")]
4316            Self::Foreground(child) => child.take_stdin(),
4317            #[cfg(target_os = "linux")]
4318            Self::Background(child) => child.take_stdin(),
4319        }
4320    }
4321
4322    pub(crate) fn take_stdout(&mut self) -> Option<std::fs::File> {
4323        match self {
4324            Self::Plain(child) => child.take_stdout(),
4325            #[cfg(target_os = "linux")]
4326            Self::Foreground(child) => child.take_stdout(),
4327            #[cfg(target_os = "linux")]
4328            Self::Background(child) => child.take_stdout(),
4329        }
4330    }
4331
4332    pub(crate) fn take_stderr(&mut self) -> Option<std::fs::File> {
4333        match self {
4334            Self::Plain(child) => child.take_stderr(),
4335            #[cfg(target_os = "linux")]
4336            Self::Foreground(child) => child.take_stderr(),
4337            #[cfg(target_os = "linux")]
4338            Self::Background(child) => child.take_stderr(),
4339        }
4340    }
4341
4342    /// A handle to the supervisor owning the job's tree.
4343    #[cfg(target_os = "linux")]
4344    pub(crate) fn tree_control(&self) -> TreeControl {
4345        match self {
4346            Self::Foreground(child) => child.tree_control(),
4347            #[cfg(target_os = "linux")]
4348            Self::Background(child) => child.tree_control(),
4349            Self::Plain(_) => unreachable!("a supervised spawn returns no plain child"),
4350        }
4351    }
4352
4353    /// Waits the job out, yielding the command's status and, for a
4354    /// supervised foreground job, the supervisor's teardown report: what it
4355    /// found still running under the command and killed.
4356    pub(crate) async fn wait_reported(
4357        &mut self,
4358    ) -> Result<(std::process::ExitStatus, Option<TreeReport>), heel::Error> {
4359        match self {
4360            Self::Plain(child) => Ok((child.wait().await?, None)),
4361            #[cfg(target_os = "linux")]
4362            Self::Foreground(child) => {
4363                let exit = child.wait().await?;
4364                Ok((exit.status, Some(exit.report)))
4365            }
4366            #[cfg(target_os = "linux")]
4367            Self::Background(child) => Ok((child.wait().await?, None)),
4368        }
4369    }
4370}
4371
4372/// Applies the rule that a job's descendants live exactly as long as the job,
4373/// after its top-level shell exited.
4374///
4375/// A foreground command's surviving descendants are killed and reported in one
4376/// [`ShellEvent::DescendantsKilled`]; a background job stays running until every
4377/// descendant has exited, which its timeout, `terminal_kill` and the registry's
4378/// kills end by killing the tree.
4379async fn end_descendants(tree: &JobTree, lifetime: &JobLifetime) -> Result<(), TerminalError> {
4380    match lifetime {
4381        JobLifetime::Foreground { .. } => {
4382            let killed = tree
4383                .kill_descendants()
4384                .await
4385                .map_err(|error| TerminalError::Execution(error.to_string()))?;
4386            if !killed.is_empty() {
4387                info!(
4388                    killed = killed.len(),
4389                    "killed descendants of a finished foreground command"
4390                );
4391                lifetime.report_descendants_killed(killed).await;
4392            }
4393            Ok(())
4394        }
4395        JobLifetime::Background { .. } => tree
4396            .wait_descendants_exit()
4397            .await
4398            .map_err(|error| TerminalError::Execution(error.to_string())),
4399    }
4400}
4401
4402/// Waits for the child to exit, raising stdin alerts meanwhile.
4403///
4404/// On Unix the child is only observed to have exited and stays unreaped (the
4405/// answer is `None`); the caller waits for it once its tree is gone. Windows
4406/// has no such state and answers the exit status.
4407#[cfg_attr(unix, allow(clippy::needless_pass_by_ref_mut))]
4408pub async fn wait_for_local_process_exit(
4409    child: &mut LocalChild,
4410    stdin_watch: Option<LocalStdinWatch>,
4411) -> Result<Option<std::process::ExitStatus>, TerminalError> {
4412    #[cfg(unix)]
4413    let exit = async {
4414        crate::process_tree::wait_for_exit(child.id())
4415            .await
4416            .map(|()| None)
4417            .map_err(|error| TerminalError::Execution(error.to_string()))
4418    };
4419    #[cfg(not(unix))]
4420    let exit = async {
4421        child
4422            .wait_reported()
4423            .await
4424            .map(|(status, _)| Some(status))
4425            .map_err(|error| TerminalError::Execution(error.to_string()))
4426    };
4427    let Some(stdin_watch) = stdin_watch else {
4428        return exit.await;
4429    };
4430    futures_lite::future::or(exit, async { match stdin_watch.run().await {} }).await
4431}
4432
4433/// A container command's script as the shell hands it to the sandbox. A main
4434/// terminal's worktree map travels inside it as exports. A command that
4435/// carries its directory reports the directory it ended in.
4436fn container_job_script(
4437    committed: &[CommittingWorktree],
4438    workspace: Option<&MountRoot>,
4439    report: Option<&ContainerPath>,
4440    script: &str,
4441) -> Result<String, TerminalError> {
4442    let preamble = container_git_preamble(committed, workspace)?;
4443    let script = if preamble.is_empty() {
4444        script.to_string()
4445    } else {
4446        format!("{preamble}{script}")
4447    };
4448    match report {
4449        Some(report) => carry_cwd_script(&script, report.as_str()),
4450        None => Ok(script),
4451    }
4452}
4453
4454/// Runs a command in a container through a [`Sandbox`] on the container's
4455/// backend, and answers what the job produced.
4456async fn execute_container_job<E: Executor + Clone + 'static>(
4457    context: ContainerJobExecution<'_, E>,
4458) -> Result<std::process::Output, TerminalError> {
4459    let result = spawn_container_job(&context).await;
4460    // The exec has ended, killed or not: the relay stops feeding the fifo and
4461    // returns its tokens once the job's last process holding it is gone.
4462    #[cfg(all(unix, feature = "jobserver"))]
4463    drop(context.job_fifo);
4464    result
4465}
4466
4467async fn spawn_container_job<E: Executor + Clone + 'static>(
4468    context: &ContainerJobExecution<'_, E>,
4469) -> Result<std::process::Output, TerminalError> {
4470    // The spec's variables are exported after the sandbox's source's, so they
4471    // win over a source variable of the same name, as they do for a local
4472    // command.
4473    #[cfg_attr(not(all(unix, feature = "jobserver")), allow(unused_mut))]
4474    let mut environment = vec![(
4475        crate::memory::JOB_MARKER_ENV.to_string(),
4476        context.task_id.to_string(),
4477    )];
4478    #[cfg_attr(not(all(unix, feature = "jobserver")), allow(unused_mut))]
4479    let mut grants = Vec::new();
4480    #[cfg(all(unix, feature = "jobserver"))]
4481    if let Some(fifo) = &context.job_fifo {
4482        environment.extend(fifo.environment());
4483        // The build tools write tokens back to the fifo.
4484        grants.push(crate::SpawnGrant::Container {
4485            path: fifo.path().clone(),
4486            access: heel::Access::WRITE,
4487        });
4488    }
4489    let runtime = context.container_runtime;
4490    let sandbox = context.sandbox.clone();
4491
4492    let carry = context.carry;
4493    let script = container_job_script(
4494        context.committed,
4495        runtime.workspace_mount(),
4496        carry
4497            .and_then(|carry| carry.container.as_ref())
4498            .and_then(|container| container.report.as_ref()),
4499        &launch_script(context.interpreter, context.script, context.task_id)?,
4500    )?;
4501    let mut spec = context.lifetime.applied_to(
4502        SpawnSpec::script(script)
4503            .env(environment)
4504            .launch_info(context.info.clone())
4505            .grants(grants)
4506            .ipc(context.ipc.and_then(|ipc| ipc.router(&context.info))),
4507    );
4508    if let Some(carry) = carry.filter(|carry| carry.container.is_some())
4509        && let Some(start) = &carry.start
4510    {
4511        spec = spec.cwd(start);
4512    }
4513    let child = sandbox.spawn(spec).await?;
4514    run_spawned_job(
4515        child,
4516        SpawnedJob {
4517            executor: context.executor.clone(),
4518            job_registry: context.job_registry,
4519            background_startup: context.background_startup,
4520            place: crate::JobPlace::Container,
4521            task_id: context.task_id,
4522            execution_id: context.execution_id,
4523            script: context.script,
4524            interpreter: context.interpreter,
4525            mode: context.mode,
4526            lifetime: context.lifetime.clone(),
4527        },
4528    )
4529    .await
4530}
4531
4532/// The status of a process a kill ended, for a backend that has none to
4533/// report: ended by `SIGKILL`.
4534fn killed_exit_status() -> std::process::ExitStatus {
4535    #[cfg(unix)]
4536    {
4537        std::os::unix::process::ExitStatusExt::from_raw(libc::SIGKILL)
4538    }
4539    #[cfg(windows)]
4540    {
4541        std::os::windows::process::ExitStatusExt::from_raw(1)
4542    }
4543}
4544
4545/// Moves the chunks of a spawned process's stream to `tx` until the stream
4546/// ends, then says it closed.
4547async fn forward_stream(
4548    stream: async_channel::Receiver<Vec<u8>>,
4549    tx: async_channel::Sender<TerminalChunk>,
4550    is_stderr: bool,
4551) {
4552    while let Ok(bytes) = stream.recv().await {
4553        let chunk = if is_stderr {
4554            TerminalChunk::Stderr(bytes)
4555        } else {
4556            TerminalChunk::Stdout(bytes)
4557        };
4558        if tx.send(chunk).await.is_err() {
4559            return;
4560        }
4561    }
4562    let _ = tx
4563        .send(if is_stderr {
4564            TerminalChunk::StderrClosed
4565        } else {
4566            TerminalChunk::StdoutClosed
4567        })
4568        .await;
4569}
4570
4571/// Runs a command on an SSH server through a [`Sandbox`] on the server's
4572/// backend: a default-mode command runs the managed shell under the server's
4573/// `heel`, an `unsafe` one runs it directly.
4574async fn execute_ssh_background<E: Executor + Clone + 'static>(
4575    context: SshBackgroundExecution<'_, E>,
4576) -> Result<std::process::Output, TerminalError> {
4577    // Only what the spec names travels to a server: the sandbox's own
4578    // environment, source and grants never leave this machine.
4579    let sandbox = context
4580        .sandbox
4581        .clone()
4582        .with_backend(crate::Backend::Ssh {
4583            server: context.server.clone(),
4584            heel: context.heel.map(str::to_owned),
4585            launch: context.launch.clone(),
4586        })
4587        .with_ssh_client(context.client.clone());
4588    let sandbox = match context.mode {
4589        SandboxMode::Sandboxed => sandbox,
4590        SandboxMode::Unsandboxed => sandbox.unconfined(),
4591    };
4592    let script = launch_script(context.interpreter, context.script, context.task_id)?;
4593    // No `.ipc(..)`: a server has no way back to this machine, and its
4594    // backend refuses a router with `SpawnError::Unsupported`.
4595    let child = sandbox
4596        .spawn(
4597            context
4598                .lifetime
4599                .applied_to(SpawnSpec::script(script).launch_info(context.info.clone())),
4600        )
4601        .await?;
4602    run_spawned_job(
4603        child,
4604        SpawnedJob {
4605            executor: context.executor,
4606            job_registry: context.job_registry,
4607            background_startup: context.background_startup,
4608            // The local `ssh` process stands for a job that runs on the
4609            // remote host, whose memory is never judged.
4610            place: crate::JobPlace::Remote,
4611            task_id: context.task_id,
4612            execution_id: context.execution_id,
4613            script: context.script,
4614            interpreter: context.interpreter,
4615            mode: context.mode,
4616            lifetime: context.lifetime,
4617        },
4618    )
4619    .await
4620}
4621
4622/// A job whose process a [`Sandbox`] spawned, and where its results go.
4623struct SpawnedJob<'a, E> {
4624    executor: E,
4625    job_registry: &'a JobRegistry,
4626    background_startup: &'a BackgroundStartup,
4627    place: crate::JobPlace,
4628    task_id: &'a IdLease,
4629    execution_id: &'a str,
4630    script: &'a str,
4631    interpreter: Interpreter,
4632    mode: SandboxMode,
4633    /// How long its descendants live, and where a reader blocked on its
4634    /// stdin pipe is alerted, for a child whose backend watches it.
4635    lifetime: JobLifetime,
4636}
4637
4638/// Registers a spawned child as a job, streams its output into the registry
4639/// and answers what it produced when it ended.
4640async fn run_spawned_job<E: Executor + Clone + 'static>(
4641    mut child: crate::SandboxedChild,
4642    job: SpawnedJob<'_, E>,
4643) -> Result<std::process::Output, TerminalError> {
4644    let stdout = child
4645        .take_stdout()
4646        .ok_or_else(|| TerminalError::Execution("missing stdout pipe for the process".into()))?;
4647    let stderr = child
4648        .take_stderr()
4649        .ok_or_else(|| TerminalError::Execution("missing stderr pipe for the process".into()))?;
4650    let stdin = child.take_stdin();
4651    let stdin_blocked = child.take_stdin_blocked();
4652    let child = Arc::new(child);
4653
4654    let pid = child.id();
4655    job.job_registry
4656        .register_at(
4657            job.place,
4658            pid,
4659            job.task_id,
4660            job.execution_id,
4661            job.script,
4662            job.interpreter,
4663            job.mode,
4664        )
4665        .await;
4666    if let Some(stdin) = stdin {
4667        job.job_registry
4668            .attach_terminal_input(job.task_id, stdin)
4669            .await;
4670    }
4671    if let (Some(signals), Some(alerts)) = (stdin_blocked, job.lifetime.stdin_alerts()) {
4672        job.executor.spawn(alerts.clone().relay(signals)).detach();
4673    }
4674    // A kill of the job ends the whole process tree, wherever it runs.
4675    let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
4676    job.job_registry
4677        .attach_kill_switch(job.task_id, kill_tx)
4678        .await;
4679    let killed = Arc::clone(&child);
4680    job.executor
4681        .spawn(async move {
4682            if kill_rx.recv().await.is_ok()
4683                && let Err(error) = killed.kill().await
4684            {
4685                warn!(%error, "ending the job failed");
4686            }
4687        })
4688        .detach();
4689    job.background_startup.report_ready().await;
4690
4691    let (chunk_tx, chunk_rx) = async_channel::unbounded();
4692    for (stream, is_stderr) in [(stdout, false), (stderr, true)] {
4693        job.executor
4694            .spawn(forward_stream(stream, chunk_tx.clone(), is_stderr))
4695            .detach();
4696    }
4697    drop(chunk_tx);
4698    job.executor
4699        .spawn(drain_terminal_chunks(
4700            job.job_registry.clone(),
4701            job.task_id.downgrade(),
4702            chunk_rx,
4703        ))
4704        .detach();
4705
4706    let status = match child.wait().await {
4707        crate::ChildExit::Exited(status) => status,
4708        // A kill ended it, and the backend has no status to report: what it
4709        // wrote before is the job's output, and the registry knows the cause.
4710        crate::ChildExit::Killed => killed_exit_status(),
4711        crate::ChildExit::Failed(error) => {
4712            job.job_registry.close_stdout(job.task_id).await;
4713            job.job_registry.close_stderr(job.task_id).await;
4714            job.job_registry.fail(job.task_id, &error, None).await;
4715            return Err(TerminalError::Execution(error));
4716        }
4717    };
4718    if matches!(job.lifetime, JobLifetime::Foreground { .. })
4719        && let Descendants::Killed(killed) = child.descendants_killed().await
4720        && !killed.is_empty()
4721    {
4722        info!(
4723            killed = killed.len(),
4724            "killed descendants of a finished foreground command"
4725        );
4726        job.lifetime.report_descendants_killed(killed).await;
4727    }
4728    wait_for_terminal_stream_close(job.job_registry, job.task_id).await;
4729    let (stdout, stderr) = job
4730        .job_registry
4731        .terminal_output(job.task_id)
4732        .await
4733        .ok_or_else(|| {
4734            TerminalError::Execution(format!("missing terminal output for task {}", job.task_id))
4735        })?;
4736    Ok(std::process::Output {
4737        status,
4738        stdout,
4739        stderr,
4740    })
4741}
4742
4743/// Prepends a source's env pairs to `script` as `export` statements, for
4744/// backends (container exec) whose channel accepts only a script — never an
4745/// env channel. Names are validated so a provider can't inject shell syntax.
4746pub fn inject_env_exports(
4747    script: String,
4748    env_source: Option<&Arc<dyn EnvSource>>,
4749    launch: &crate::LaunchInfo,
4750) -> Result<String, TerminalError> {
4751    let Some(source) = env_source else {
4752        return Ok(script);
4753    };
4754    let mut rendered = String::new();
4755    for (name, value) in source.env(launch) {
4756        if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
4757            || name.chars().next().is_some_and(|c| c.is_ascii_digit())
4758        {
4759            return Err(TerminalError::Execution(format!(
4760                "invalid environment variable name for container exec: {name}"
4761            )));
4762        }
4763        rendered.push_str("export ");
4764        rendered.push_str(&name);
4765        rendered.push('=');
4766        rendered.push_str(&shell_escape(&value));
4767        rendered.push('\n');
4768    }
4769    rendered.push_str(&script);
4770    Ok(rendered)
4771}
4772
4773pub fn shell_escape(value: &str) -> String {
4774    let escaped = value.replace('\'', "'\"'\"'");
4775    let mut output = String::with_capacity(escaped.len() + 2);
4776    output.push('\'');
4777    output.push_str(&escaped);
4778    output.push('\'');
4779    output
4780}
4781
4782#[derive(Template)]
4783#[template(path = "container_setup.sh", escape = "none")]
4784struct ContainerSetupTemplate<'a> {
4785    setup: &'a str,
4786    script: &'a str,
4787}
4788
4789#[derive(Template)]
4790#[template(path = "container_start_dir.sh", escape = "none")]
4791struct ContainerStartDirTemplate<'a> {
4792    escaped_directory: &'a str,
4793    script: &'a str,
4794}
4795
4796/// `script` entered in `directory` first: a confined command's sandbox is
4797/// rooted at its own directory, and the directory the command was asked to
4798/// start in is entered inside it.
4799pub fn start_in_container_directory(
4800    script: &str,
4801    directory: &ContainerPath,
4802) -> Result<String, TerminalError> {
4803    ContainerStartDirTemplate {
4804        escaped_directory: &shell_escape(directory.as_str()),
4805        script,
4806    }
4807    .render()
4808    .map_err(|error| {
4809        TerminalError::Execution(format!(
4810            "failed to render the container start directory: {error}"
4811        ))
4812    })
4813}
4814
4815/// Working directory container executions run their scripts in.
4816pub const CONTAINER_EXEC_WORKING_DIR: &str = "/workspace";
4817
4818/// The sandbox a subagent's command runs in inside a container, as container
4819/// paths: the main agent's commands run unconfined because the container is its
4820/// boundary, but a subagent's keep the per-command sandbox they have on the
4821/// host — write access to its own space and its granted paths only.
4822#[derive(Clone, Debug, PartialEq, Eq)]
4823pub struct ContainerConfinement {
4824    pub(crate) working_dir: ContainerPath,
4825    /// What the sandbox may reach beyond the working directory.
4826    pub(crate) grants: Vec<(ContainerPath, heel::Access)>,
4827}
4828
4829/// Where a container command runs: the mounted tools, the exec's working
4830/// directory and, for a subagent, its sandbox.
4831#[derive(Clone, Copy)]
4832struct ContainerRunScope<'a> {
4833    tools_dir: &'a ContainerPath,
4834    working_dir: &'a str,
4835    confinement: Option<&'a ContainerConfinement>,
4836}
4837
4838#[derive(Template)]
4839#[template(path = "container_heel_run.sh", escape = "none")]
4840struct ContainerHeelRunTemplate<'a> {
4841    escaped_working_dir: &'a str,
4842    escaped_tools_dir: &'a str,
4843    /// Set for a subagent: the isolation level and grants replacing the
4844    /// container-wide permissive one.
4845    escaped_grants: Option<Vec<String>>,
4846    /// The embedder's shell words, expanded by the exec's shell.
4847    sandbox_args: &'a [String],
4848    nice: Option<u8>,
4849    io_priority: Option<&'static str>,
4850    escaped_script: &'a str,
4851}
4852
4853/// Renders the command that runs `script` inside the container at the
4854/// configured scheduling priority.
4855///
4856/// The priority goes through heel's own sandbox configuration: the container
4857/// image's `heel` binary runs the script under `heel run`, so the settings are
4858/// the same flags the CLI takes everywhere — `nice`/`ionice` are never
4859/// reimplemented here. The command resolves the image's `heel` itself and
4860/// fails when the image lacks one; `working_dir` is the exact directory the
4861/// execution runs in, matching the directory the container exec applies.
4862///
4863/// The container is already the isolation boundary, so the invocation asks for
4864/// `permissive` isolation: the script keeps the filesystem permissions it had
4865/// as the container caller. The ruleset still exec-denies everything outside
4866/// the system directories, so `--executable` grants the mounted tools
4867/// directory read-execute — without it every prepared tool fails with
4868/// Permission denied. `PATH` and `HOME` are forwarded, so the script sees the
4869/// environment a setup prepared. Networking keeps heel's deny-all default.
4870/// `sandbox_args` are the embedder's own words for the command line.
4871fn heel_run_container_command(
4872    script: &str,
4873    priority: ProcessPriority,
4874    sandbox_args: &[String],
4875    scope: ContainerRunScope<'_>,
4876) -> Result<String, TerminalError> {
4877    let ContainerRunScope {
4878        tools_dir,
4879        working_dir,
4880        confinement,
4881    } = scope;
4882    let nice = match priority.cpu() {
4883        CpuPriority::Nice(level) => Some(level.get()),
4884        CpuPriority::Normal => None,
4885    };
4886    let io_priority = match priority.io() {
4887        IoPriority::Utility => Some("utility"),
4888        IoPriority::Background => Some("background"),
4889        IoPriority::Normal => None,
4890    };
4891    // A subagent runs in its own space with heel's default isolation (that space
4892    // writable, the rest readable) plus its granted paths.
4893    let working_dir =
4894        confinement.map_or(working_dir, |confinement| confinement.working_dir.as_str());
4895    let escaped_grants = confinement.map(|confinement| {
4896        confinement
4897            .grants
4898            .iter()
4899            .map(|(path, access)| shell_escape(&format!("{path}={access}")))
4900            .collect()
4901    });
4902    let escaped_working_dir = shell_escape(working_dir);
4903    let escaped_tools_dir = shell_escape(tools_dir.as_str());
4904    let escaped_script = shell_escape(script);
4905    ContainerHeelRunTemplate {
4906        escaped_working_dir: &escaped_working_dir,
4907        escaped_tools_dir: &escaped_tools_dir,
4908        escaped_grants,
4909        sandbox_args,
4910        nice,
4911        io_priority,
4912        escaped_script: &escaped_script,
4913    }
4914    .render()
4915    .map_err(|error| {
4916        TerminalError::Execution(format!("failed to render container heel command: {error}"))
4917    })
4918}
4919
4920fn prioritized_container_script(
4921    script: &str,
4922    priority: ProcessPriority,
4923    tools_dir: &ContainerPath,
4924    working_dir: &str,
4925    confinement: Option<&ContainerConfinement>,
4926) -> Result<String, TerminalError> {
4927    if priority.is_normal() && confinement.is_none() {
4928        return Ok(script.to_string());
4929    }
4930    heel_run_container_command(
4931        script,
4932        priority,
4933        &[],
4934        ContainerRunScope {
4935            tools_dir,
4936            working_dir,
4937            confinement,
4938        },
4939    )
4940}
4941
4942/// The script a container exec runs for `script`: `setup` first, outside the
4943/// sandbox, and then `script` in the sandbox the priority and confinement ask
4944/// for, with the setup's sandbox arguments.
4945pub fn wrap_container_script(
4946    script: &str,
4947    setup: Option<&ExecSetup>,
4948    priority: ProcessPriority,
4949    tools_dir: &ContainerPath,
4950    working_dir: &str,
4951    confinement: Option<&ContainerConfinement>,
4952) -> Result<String, TerminalError> {
4953    let Some(setup) = setup else {
4954        return prioritized_container_script(script, priority, tools_dir, working_dir, confinement);
4955    };
4956    let script = if priority.is_normal() && confinement.is_none() {
4957        script.to_string()
4958    } else {
4959        heel_run_container_command(
4960            script,
4961            priority,
4962            &setup.sandbox_args,
4963            ContainerRunScope {
4964                tools_dir,
4965                working_dir,
4966                confinement,
4967            },
4968        )?
4969    };
4970    ContainerSetupTemplate {
4971        setup: &setup.script,
4972        script: &script,
4973    }
4974    .render()
4975    .map_err(|error| TerminalError::Execution(format!("failed to render container setup: {error}")))
4976}
4977
4978fn preview_first_lines(data: &[u8], max_lines: usize) -> (String, bool) {
4979    if data.is_empty() || max_lines == 0 {
4980        return (String::new(), !data.is_empty() && max_lines == 0);
4981    }
4982
4983    let text = String::from_utf8_lossy(data);
4984    let mut preview = String::new();
4985    let mut total_lines = 0usize;
4986
4987    for line in text.lines() {
4988        total_lines += 1;
4989        if total_lines <= max_lines {
4990            if !preview.is_empty() {
4991                preview.push('\n');
4992            }
4993            preview.push_str(line);
4994        }
4995    }
4996
4997    let truncated = total_lines > max_lines;
4998    (preview, truncated)
4999}
5000
5001enum TerminalChunk {
5002    Stdout(Vec<u8>),
5003    Stderr(Vec<u8>),
5004    StdoutClosed,
5005    StderrClosed,
5006}
5007
5008fn spawn_terminal_reader<R>(reader: R, tx: async_channel::Sender<TerminalChunk>, is_stderr: bool)
5009where
5010    R: Read + Send + 'static,
5011{
5012    read_chunks(reader, move |chunk| {
5013        let chunk = match (chunk, is_stderr) {
5014            (Some(bytes), false) => TerminalChunk::Stdout(bytes),
5015            (Some(bytes), true) => TerminalChunk::Stderr(bytes),
5016            (None, false) => TerminalChunk::StdoutClosed,
5017            (None, true) => TerminalChunk::StderrClosed,
5018        };
5019        let _ = tx.send_blocking(chunk);
5020    });
5021}
5022
5023/// Moves a job's output into its registry until the readers let go of `rx`.
5024///
5025/// The job's lease is held weakly, and each chunk hands the registry a strong
5026/// one of its own: the readers drop their senders some time after their
5027/// streams closed, and by then the job's flow, which waits only for the
5028/// closes, may have answered its call, which must find the word free.
5029async fn drain_terminal_chunks(
5030    job_registry: JobRegistry,
5031    task_id: WeakIdLease,
5032    rx: async_channel::Receiver<TerminalChunk>,
5033) {
5034    while let Ok(chunk) = rx.recv().await {
5035        // The flow holds the lease until both streams closed: one gone means
5036        // the job ended, and its output has nowhere to go.
5037        let Some(task_id) = task_id.upgrade() else {
5038            return;
5039        };
5040        match chunk {
5041            TerminalChunk::Stdout(bytes) => {
5042                job_registry
5043                    .append_output(task_id, TerminalStream::Stdout, bytes)
5044                    .await;
5045            }
5046            TerminalChunk::Stderr(bytes) => {
5047                job_registry
5048                    .append_output(task_id, TerminalStream::Stderr, bytes)
5049                    .await;
5050            }
5051            TerminalChunk::StdoutClosed => {
5052                job_registry
5053                    .close_output(task_id, TerminalStream::Stdout)
5054                    .await;
5055            }
5056            TerminalChunk::StderrClosed => {
5057                job_registry
5058                    .close_output(task_id, TerminalStream::Stderr)
5059                    .await;
5060            }
5061        }
5062    }
5063}
5064
5065async fn wait_for_terminal_stream_close(job_registry: &JobRegistry, task_id: &str) {
5066    while !job_registry.terminal_streams_closed(task_id).await {
5067        async_io::Timer::after(Duration::from_millis(10)).await;
5068    }
5069}
5070
5071/// Errors that can occur during terminal execution.
5072///
5073/// The variants carry the facts; the `Display` texts are for logs and
5074/// diagnostics, and the model never reads them: it reads what
5075/// [`ShellWording::run_failure`] makes of the error. The `String` of
5076/// [`Execution`](Self::Execution) and [`SandboxSetup`](Self::SandboxSetup) is
5077/// the detail the failing backend reported, not a sentence of the shell's.
5078#[derive(Debug, thiserror::Error)]
5079#[non_exhaustive]
5080pub enum TerminalError {
5081    /// The task that runs the script ended before it registered or answered.
5082    #[error("the task running the script ended without answering")]
5083    TaskLost,
5084    /// Execution environment or mode is not configured.
5085    #[error("invalid terminal execution target: {0}")]
5086    InvalidTarget(String),
5087    /// `location` names no configured SSH server.
5088    #[error("no SSH server named `{0}` is configured")]
5089    UnknownLocation(String),
5090    /// A default-mode command names a server that has no `heel` to sandbox it.
5091    #[error("default mode runs under `heel`, which `{0}` does not have")]
5092    NoRemoteSandbox(String),
5093    /// The server's preparation failed; the next command naming it prepares
5094    /// it again.
5095    #[error(transparent)]
5096    SshPrepare(#[from] crate::ssh::SshPrepareError),
5097    /// The approver denied the script; the model reads the reason it gave.
5098    #[error("{0}")]
5099    Denied(String),
5100
5101    /// The script needs approval, and neither its call nor the terminal has
5102    /// an approver to give it.
5103    #[error(
5104        "approval for `{0}` is required to run this script, but no approver is configured for this terminal"
5105    )]
5106    NoApprover(ApprovalKind),
5107
5108    /// Asking for approval failed or was cancelled.
5109    #[error(transparent)]
5110    Approval(#[from] ApprovalError),
5111
5112    /// Sandbox setup failed.
5113    #[error("sandbox setup failed: {0}")]
5114    SandboxSetup(String),
5115
5116    /// Script execution failed.
5117    #[error("execution failed: {0}")]
5118    Execution(String),
5119
5120    /// IO error.
5121    #[error("io error: {0}")]
5122    Io(#[from] std::io::Error),
5123
5124    /// Jobserver pool or broker error.
5125    #[cfg(all(unix, feature = "jobserver"))]
5126    #[error(transparent)]
5127    Jobserver(#[from] crate::jobserver::JobserverError),
5128}
5129
5130impl TerminalError {
5131    /// What the failure reports, without the frame its `Display` puts around
5132    /// it: the text a job's registry status carries, which the embedder
5133    /// words inside its own.
5134    #[must_use]
5135    pub fn detail(&self) -> Cow<'_, str> {
5136        match self {
5137            Self::InvalidTarget(detail)
5138            | Self::UnknownLocation(detail)
5139            | Self::NoRemoteSandbox(detail)
5140            | Self::Denied(detail)
5141            | Self::SandboxSetup(detail)
5142            | Self::Execution(detail) => Cow::Borrowed(detail),
5143            other => Cow::Owned(other.to_string()),
5144        }
5145    }
5146}
5147
5148impl From<crate::SpawnError> for TerminalError {
5149    fn from(error: crate::SpawnError) -> Self {
5150        match error {
5151            crate::SpawnError::Setup(message) => Self::SandboxSetup(message),
5152            crate::SpawnError::Start(message) => Self::Execution(message),
5153            error @ crate::SpawnError::Unsupported { .. } => Self::Execution(error.to_string()),
5154        }
5155    }
5156}
5157
5158impl<E> std::fmt::Debug for Shell<E> {
5159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5160        f.debug_struct("Shell")
5161            .field("working_dir", &self.working_dir)
5162            .finish_non_exhaustive()
5163    }
5164}
5165
5166#[cfg(test)]
5167mod tests {
5168    use crate::ContainerLaunch;
5169    use std::io::Write;
5170    use std::time::Duration;
5171
5172    use super::*;
5173    use crate::GitDirAccess;
5174    use crate::JobInputTool;
5175    use crate::ShellWording;
5176    #[cfg(unix)]
5177    use crate::builtin::JobInputArgs;
5178    use crate::output::empty_stream;
5179    use crate::shell_session::{ContainerExecOutcome, ExecLifetime};
5180    use crate::test_wording::TestWording;
5181    #[cfg(unix)]
5182    use heel::DenyAll;
5183    use heel::NiceLevel;
5184
5185    #[cfg(all(unix, feature = "connectivity"))]
5186    mod outage;
5187
5188    #[cfg(unix)]
5189    mod ssh;
5190
5191    /// The tool that writes to the stdin of `jobs`' jobs.
5192    fn input_tool(jobs: Jobs) -> JobInputTool {
5193        JobInputTool::new(
5194            crate::test_wording::job_tools().input,
5195            jobs,
5196            TestWording::any(),
5197        )
5198    }
5199
5200    /// A stdin whose drop reports that the writer thread holding it ended.
5201    struct DropSignal(async_channel::Sender<()>);
5202
5203    impl Write for DropSignal {
5204        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
5205            Ok(bytes.len())
5206        }
5207
5208        fn flush(&mut self) -> std::io::Result<()> {
5209            Ok(())
5210        }
5211    }
5212
5213    impl Drop for DropSignal {
5214        fn drop(&mut self) {
5215            let _ = self.0.send_blocking(());
5216        }
5217    }
5218
5219    /// A finished job's stdin writer thread exits instead of blocking on its
5220    /// channel forever.
5221    #[tokio::test]
5222    async fn finished_job_ends_its_stdin_writer_thread() {
5223        use executor_core::{Executor as _, Task as _};
5224        let (registry, service) =
5225            crate::job_registry::job_registry_channel(crate::output_policy::fixture::policy());
5226        executor_core::tokio::TokioGlobal
5227            .spawn(async move { service.serve().await })
5228            .detach();
5229        registry
5230            .register(
5231                9001,
5232                &crate::test_ids::lease("writer"),
5233                "exec-writer",
5234                "cat",
5235                SandboxMode::Sandboxed,
5236                None,
5237            )
5238            .await;
5239        let (ended_tx, ended_rx) = async_channel::bounded::<()>(1);
5240        let input_tx = write_chunks(DropSignal(ended_tx), FeedCounter::default());
5241        registry
5242            .attach_terminal_input(&crate::test_ids::lease("writer"), input_tx)
5243            .await;
5244        registry
5245            .terminal_input("writer", b"hi\n".to_vec())
5246            .await
5247            .expect("a running job takes input");
5248        assert!(ended_rx.is_empty(), "the writer lives while the job runs");
5249
5250        registry
5251            .complete(&crate::test_ids::lease("writer"), 0, None)
5252            .await;
5253
5254        tokio::time::timeout(Duration::from_secs(10), ended_rx.recv())
5255            .await
5256            .expect("the writer thread must end once the job finishes")
5257            .expect("the writer reports its end");
5258    }
5259
5260    /// The programs a test container's launch names.
5261    fn test_container_launch() -> ContainerLaunch {
5262        ContainerLaunch::new(
5263            ContainerPath::root().join("opt/tools/bin"),
5264            ContainerPath::root().join("opt/tools/bin/bash"),
5265        )
5266    }
5267
5268    /// A sandbox on `runtime`, working in `directory`.
5269    fn container_sandbox(runtime: &ContainerShellRuntime, directory: &Path) -> Sandbox {
5270        Sandbox::new(
5271            Backend::Container {
5272                runtime: runtime.clone(),
5273                launch: test_container_launch(),
5274            },
5275            executor_core::tokio::TokioGlobal,
5276            directory,
5277        )
5278    }
5279
5280    async fn fresh_terminal(dir: &Path) -> Shell<executor_core::tokio::TokioGlobal> {
5281        Shell::new_exact(
5282            dir,
5283            executor_core::tokio::TokioGlobal,
5284            crate::limits::fixture::limits(),
5285            crate::output_policy::fixture::policy(),
5286            TestWording::any(),
5287            crate::test_wording::job_tools(),
5288        )
5289        .await
5290        .expect("terminal tool should initialize")
5291    }
5292
5293    /// A detached call answered as the model reads it.
5294    trait CallDetached {
5295        async fn call_detached(&self, arguments: ShellArgs) -> aither_core::Result<ToolResult>;
5296    }
5297
5298    impl<E: Executor + Clone + 'static> CallDetached for Shell<E> {
5299        async fn call_detached(&self, arguments: ShellArgs) -> aither_core::Result<ToolResult> {
5300            self.call(
5301                ShellArgs {
5302                    background: true,
5303                    ..arguments
5304                },
5305                ToolContext::new(),
5306            )
5307            .await
5308        }
5309    }
5310
5311    fn render_terminal_result(result: &ToolResult) -> String {
5312        result.render_for_model()
5313    }
5314
5315    fn started_task_id(receiver: &ShellEvents) -> String {
5316        let started = receiver.take_started();
5317        assert_eq!(started.len(), 1, "expected one started-task event");
5318        started[0].task_id.clone()
5319    }
5320
5321    #[cfg(unix)]
5322    #[test]
5323    fn shell_launch_runs_the_managed_bash_without_startup_files() {
5324        let script = "printf '%s\\n' hello | cat";
5325        let (program, args) = shell_launch("/tools/bin/bash", script);
5326
5327        assert_eq!(program, "/tools/bin/bash");
5328        assert_eq!(args[..3], ["--noprofile", "--norc", "-c"]);
5329        assert!(args[3].ends_with(script));
5330        assert_eq!(args.len(), 4);
5331    }
5332
5333    #[test]
5334    fn host_programs_run_without_a_shell() {
5335        for name in ["grep", "sed", "awk", "find"] {
5336            assert_eq!(
5337                direct_command(&format!("{name} x")).unwrap(),
5338                Some((name.to_string(), vec!["x".to_string()]))
5339            );
5340        }
5341    }
5342
5343    /// A shell expands `$` and backquotes inside double quotes, so a script
5344    /// using them there runs in one; single quotes and a backslash keep them
5345    /// literal, so such a script still runs directly.
5346    #[test]
5347    fn an_expansion_inside_double_quotes_runs_in_a_shell() {
5348        for script in [
5349            "echo \"$TMPDIR|$HOME\"",
5350            "echo \"${HOME-unset}\"",
5351            "echo \"`pwd`\"",
5352        ] {
5353            assert_eq!(direct_command(script).unwrap(), None, "{script}");
5354        }
5355        for (script, arg) in [("echo '$HOME'", "$HOME"), ("echo \"\\$HOME\"", "$HOME")] {
5356            assert_eq!(
5357                direct_command(script).unwrap(),
5358                Some(("echo".to_string(), vec![arg.to_string()])),
5359                "{script}"
5360            );
5361        }
5362    }
5363
5364    #[test]
5365    fn inject_env_exports_prepends_valid_pairs() {
5366        let source: Option<Arc<dyn EnvSource>> = Some(Arc::new(vec![
5367            ("MY_KEY".to_string(), "it's".to_string()),
5368            ("OTHER".to_string(), "x".to_string()),
5369        ]));
5370        let rendered = inject_env_exports(
5371            "echo hi".to_string(),
5372            source.as_ref(),
5373            &crate::LaunchInfo::default(),
5374        )
5375        .expect("valid env names should render");
5376        assert_eq!(
5377            rendered,
5378            "export MY_KEY='it'\"'\"'s'\nexport OTHER='x'\necho hi"
5379        );
5380    }
5381
5382    #[test]
5383    fn inject_env_exports_rejects_shell_syntax_names() {
5384        let source: Option<Arc<dyn EnvSource>> =
5385            Some(Arc::new(vec![("BAD;name".to_string(), "x".to_string())]));
5386        let launch = crate::LaunchInfo::default();
5387        assert!(inject_env_exports("echo hi".to_string(), source.as_ref(), &launch).is_err());
5388        assert_eq!(
5389            inject_env_exports("echo hi".to_string(), None, &launch)
5390                .expect("no source passes through"),
5391            "echo hi"
5392        );
5393    }
5394
5395    fn output_text(output: &CommandStream) -> Option<&str> {
5396        match output {
5397            CommandStream::Inline { text } => Some(text.as_str()),
5398            CommandStream::Stored { preview, .. } => Some(preview.as_str()),
5399            CommandStream::Image { .. } => None,
5400        }
5401    }
5402
5403    async fn wait_for_completed_task(receiver: &ShellEvents, task_id: &str) -> JobEnded {
5404        tokio::time::timeout(Duration::from_secs(5), async {
5405            loop {
5406                if let Some(task) = receiver
5407                    .take_completed()
5408                    .into_iter()
5409                    .find(|task| task.info.task_id == task_id)
5410                {
5411                    return task;
5412                }
5413                tokio::time::sleep(Duration::from_millis(50)).await;
5414            }
5415        })
5416        .await
5417        .expect("background task should complete after terminal input")
5418    }
5419
5420    #[tokio::test]
5421    async fn test_terminal_args_defaults() {
5422        let args: ShellArgs = serde_json::from_str(
5423            r#"{"description":"print a greeting","script":"echo hello","timeout":30}"#,
5424        )
5425        .unwrap();
5426        assert_eq!(args.resolution, MediaResolution::Auto);
5427        assert_eq!(args.sandbox, SandboxMode::Sandboxed);
5428        assert!(!args.background);
5429    }
5430
5431    #[test]
5432    fn background_preview_keeps_leading_indentation() {
5433        assert_eq!(
5434            background_preview("  col a  col b\nrow\n\n"),
5435            "  col a  col b\nrow"
5436        );
5437        assert_eq!(background_preview(" \n\t\n"), "");
5438    }
5439
5440    fn inline(text: &str) -> CommandStream {
5441        CommandStream::Inline {
5442            text: text.to_string(),
5443        }
5444    }
5445
5446    fn completed(
5447        stdout: CommandStream,
5448        stderr: Option<CommandStream>,
5449        exit_code: i32,
5450    ) -> CommandResult {
5451        CommandResult {
5452            stdout,
5453            stderr,
5454            outcome: CommandOutcome::Exited { code: exit_code },
5455            interruptions: Vec::new(),
5456        }
5457    }
5458
5459    #[test]
5460    fn completed_command_exit_zero_is_the_bare_output() {
5461        let result = completed(inline("done"), None, 0)
5462            .into_tool_result()
5463            .unwrap();
5464        assert_eq!(result.render_for_model(), "done\n");
5465        assert_eq!(
5466            result.command().map(|command| &command.outcome),
5467            Some(&CommandOutcome::Exited { code: 0 })
5468        );
5469    }
5470
5471    #[test]
5472    fn completed_command_without_any_output_says_so() {
5473        assert_eq!(
5474            completed(empty_stream(), None, 0).render_for_model(),
5475            "(no output)\n"
5476        );
5477    }
5478
5479    #[test]
5480    fn completed_command_non_zero_exit_with_stderr() {
5481        let result = completed(inline("partial"), Some(inline("oops")), 2);
5482        assert_eq!(
5483            result.render_for_model(),
5484            "partial\nstderr:\noops\nExit code: 2.\n"
5485        );
5486    }
5487
5488    #[test]
5489    fn completed_command_stderr_only_has_no_contradicting_placeholder() {
5490        assert_eq!(
5491            completed(empty_stream(), Some(inline("oops")), 2).render_for_model(),
5492            "stderr:\noops\nExit code: 2.\n"
5493        );
5494    }
5495
5496    #[tokio::test]
5497    async fn test_terminal_args_parsing() {
5498        let args: ShellArgs = serde_json::from_str(
5499            r#"{"description":"sleep in background","script":"sleep 5","timeout":30,"background":true}"#,
5500        )
5501        .unwrap();
5502        assert_eq!(args.timeout, 30);
5503        assert_eq!(args.script, "sleep 5");
5504        assert!(args.background);
5505
5506        let missing_timeout = serde_json::from_str::<ShellArgs>(
5507            r#"{"description":"sleep in background","script":"sleep 5"}"#,
5508        )
5509        .unwrap_err();
5510        assert!(missing_timeout.to_string().contains("timeout"));
5511
5512        let missing_description =
5513            serde_json::from_str::<ShellArgs>(r#"{"script":"echo hello","timeout":1}"#)
5514                .unwrap_err();
5515        assert!(missing_description.to_string().contains("description"));
5516    }
5517
5518    #[test]
5519    fn terminal_args_schema_lists_required_fields() {
5520        let schema = serde_json::to_value(schemars::schema_for!(ShellArgs)).unwrap();
5521        let properties = schema["properties"].as_object().expect("object schema");
5522        for field in [
5523            "description",
5524            "script",
5525            "timeout",
5526            "max_lines",
5527            "background",
5528        ] {
5529            assert!(
5530                properties.contains_key(field),
5531                "{field} missing from schema {schema}"
5532            );
5533        }
5534        let required = schema["required"].as_array().expect("required list");
5535        for field in ["description", "script", "timeout"] {
5536            assert!(
5537                required.iter().any(|name| name == field),
5538                "{field} not required in {schema}"
5539            );
5540        }
5541        assert!(
5542            !required.iter().any(|name| name == "background"),
5543            "background must not be required in {schema}"
5544        );
5545    }
5546
5547    /// The lifetime of a foreground command whose facts go to `alerts`.
5548    fn foreground_lifetime(alerts: EventSender) -> JobLifetime {
5549        JobLifetime::Foreground {
5550            alerts,
5551            task_id: "probe".to_string(),
5552            call: None,
5553        }
5554    }
5555
5556    /// The tools bin directory a container execution passes to the wrapper.
5557    fn container_tools_dir() -> ContainerPath {
5558        test_container_launch().bin_dir().clone()
5559    }
5560
5561    /// The commands of a router that serves each of `names`, taking no
5562    /// positional arguments.
5563    fn ipc_commands(names: &[&str]) -> heel::ipc::IpcCommands {
5564        let declarations = names
5565            .iter()
5566            .map(|name| {
5567                (
5568                    *name,
5569                    serde_json::json!({"positional_args": [], "stdin_arg": null}),
5570                )
5571            })
5572            .collect::<std::collections::BTreeMap<_, _>>();
5573        serde_json::from_value(serde_json::json!(declarations)).expect("valid IPC commands")
5574    }
5575
5576    /// `script` wrapped with the IPC setup for `commands` at `host:port`.
5577    fn wrap_with_ipc(
5578        script: &str,
5579        commands: &heel::ipc::IpcCommands,
5580        endpoint: (&str, u16),
5581        priority: ProcessPriority,
5582    ) -> Result<String, TerminalError> {
5583        let setup = crate::spawn::container_ipc::exec_setup(commands, endpoint.0, endpoint.1)?;
5584        wrap_container_script(
5585            script,
5586            Some(&setup),
5587            priority,
5588            &container_tools_dir(),
5589            CONTAINER_EXEC_WORKING_DIR,
5590            None,
5591        )
5592    }
5593
5594    #[test]
5595    fn wrap_container_script_refreshes_command_hash_table() {
5596        let wrapped = wrap_with_ipc(
5597            "websearch \"gold price\"",
5598            &ipc_commands(&["websearch"]),
5599            ("host.docker.internal", 9000),
5600            ProcessPriority::default(),
5601        )
5602        .expect("wrap script");
5603        assert!(wrapped.contains("hash -r;"));
5604        assert!(wrapped.contains("AITHER_IPC_DIR"));
5605        assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
5606    }
5607
5608    #[test]
5609    fn wrap_container_script_preserves_user_script_semantics() {
5610        let script = "echo '$5,040' && subagent art_direction --prompt-file tmp/prompt.md";
5611        let wrapped = wrap_with_ipc(
5612            script,
5613            &ipc_commands(&["subagent"]),
5614            ("host.docker.internal", 9000),
5615            ProcessPriority::default(),
5616        )
5617        .expect("wrap script");
5618        assert!(wrapped.contains(script));
5619        assert!(!wrapped.contains("set -euo pipefail"));
5620    }
5621
5622    #[test]
5623    fn wrap_container_script_renders_expected_endpoint() {
5624        let wrapped = wrap_with_ipc(
5625            "environment --query deployment",
5626            &ipc_commands(&["environment", "session"]),
5627            ("host.containers.internal", 43123),
5628            ProcessPriority::default(),
5629        )
5630        .expect("wrap script");
5631        assert!(wrapped.contains("tcp://host.containers.internal:43123"));
5632        assert!(wrapped.contains(
5633            r#"shims --dir "$AITHER_IPC_DIR" --commands '{"environment":{"positional_args":[],"stdin_arg":null,"raw_args":false},"session":{"positional_args":[],"stdin_arg":null,"raw_args":false}}'"#
5634        ));
5635    }
5636
5637    /// The shims are written from the declarations, so a command's
5638    /// positional and stdin arguments reach the container, where a shim
5639    /// that knew only the name would pass neither.
5640    #[test]
5641    fn wrap_container_script_carries_the_commands_declarations() {
5642        let commands: heel::ipc::IpcCommands =
5643            serde_json::from_str(r#"{"issue":{"positional_args":["number"],"stdin_arg":"body"}}"#)
5644                .expect("valid IPC commands");
5645        let wrapped = wrap_with_ipc(
5646            "issue",
5647            &commands,
5648            ("host.docker.internal", 9000),
5649            ProcessPriority::default(),
5650        )
5651        .expect("wrap script");
5652        assert!(wrapped.contains(
5653            r#"--commands '{"issue":{"positional_args":["number"],"stdin_arg":"body","raw_args":false}}'"#
5654        ));
5655        assert!(!wrapped.contains("printf"));
5656    }
5657
5658    /// Approves every request, and records what it was asked.
5659    #[derive(Clone, Default)]
5660    struct Approvals {
5661        asked: Arc<Mutex<Vec<ApprovalRequest>>>,
5662        /// Denies with this reason instead of approving.
5663        deny: Option<&'static str>,
5664    }
5665
5666    impl Approvals {
5667        fn denying(reason: &'static str) -> Self {
5668            Self {
5669                deny: Some(reason),
5670                ..Self::default()
5671            }
5672        }
5673
5674        fn asked(&self) -> Vec<ApprovalRequest> {
5675            self.asked.lock().unwrap().clone()
5676        }
5677    }
5678
5679    impl Approver for Approvals {
5680        fn approve(
5681            &self,
5682            request: ApprovalRequest,
5683        ) -> impl Future<Output = Result<Approval, aither_core::llm::tool::ApproverFailure>> + Send
5684        {
5685            self.asked.lock().unwrap().push(request);
5686            std::future::ready(Ok(self.deny.map_or(Approval::Approved, |reason| {
5687                Approval::Denied {
5688                    reason: reason.to_string(),
5689                }
5690            })))
5691        }
5692    }
5693
5694    /// Approves everything it is asked.
5695    struct ApproveAll;
5696
5697    impl Approver for ApproveAll {
5698        fn approve(
5699            &self,
5700            _request: ApprovalRequest,
5701        ) -> impl Future<Output = Result<Approval, aither_core::llm::tool::ApproverFailure>> + Send
5702        {
5703            std::future::ready(Ok(Approval::Approved))
5704        }
5705    }
5706
5707    /// Decides the same way on every script.
5708    struct Decide(ScriptDecision);
5709
5710    impl crate::ScriptPolicy for Decide {
5711        type State = ();
5712
5713        fn check(
5714            &self,
5715            _script: &crate::ScriptCheck<'_>,
5716            (): &(),
5717        ) -> impl Future<Output = ScriptDecision> + Send {
5718            std::future::ready(self.0.clone())
5719        }
5720    }
5721
5722    /// A local terminal in `dir` whose script policies are `decisions`,
5723    /// asking `approver` for what needs approval.
5724    #[cfg(unix)]
5725    async fn approval_tool(
5726        dir: &Path,
5727        decisions: impl IntoIterator<Item = ScriptDecision>,
5728        approver: Option<Approvals>,
5729    ) -> Shell<executor_core::tokio::TokioGlobal> {
5730        let tool = fresh_terminal(dir).await.with_test_policies(
5731            decisions
5732                .into_iter()
5733                .map(|decision| crate::AnyScriptPolicy::new(Decide(decision)))
5734                .collect(),
5735        );
5736        match approver {
5737            Some(approver) => tool.with_approver(approver),
5738            None => tool,
5739        }
5740    }
5741
5742    #[cfg(unix)]
5743    fn unsandboxed_args(script: &str) -> ShellArgs {
5744        ShellArgs {
5745            sandbox: SandboxMode::Unsandboxed,
5746            ..terminal_args("run outside the sandbox", script)
5747        }
5748    }
5749
5750    /// A script that runs outside the sandbox and that no policy decided is
5751    /// asked about; a script inside the sandbox is not.
5752    #[cfg(unix)]
5753    #[tokio::test]
5754    async fn an_unsandboxed_script_with_only_passes_is_asked() {
5755        let dir = tempfile::tempdir().expect("temp dir should be created");
5756        let approvals = Approvals::default();
5757        let tool = approval_tool(dir.path(), [ScriptDecision::Pass], Some(approvals.clone())).await;
5758
5759        tool.call(terminal_args("inside", "true"), ToolContext::new())
5760            .await
5761            .expect("a sandboxed script with only passes runs");
5762        assert_eq!(approvals.asked(), []);
5763
5764        tool.call(unsandboxed_args("true"), ToolContext::new())
5765            .await
5766            .expect("the approver approved");
5767        let asked = approvals.asked();
5768        assert_eq!(asked.len(), 1);
5769        assert_eq!(asked[0].kind().as_str(), "unsandboxed");
5770        assert_eq!(asked[0].subject(), "true");
5771    }
5772
5773    /// An `Allow` runs a script that crosses the boundary without asking;
5774    /// a denied `Ask` keeps it from running and its reason reaches the
5775    /// caller.
5776    #[cfg(unix)]
5777    #[tokio::test]
5778    async fn an_allow_runs_and_a_denied_ask_does_not() {
5779        let dir = tempfile::tempdir().expect("temp dir should be created");
5780        let approvals = Approvals::default();
5781        let allowed =
5782            approval_tool(dir.path(), [ScriptDecision::Allow], Some(approvals.clone())).await;
5783        allowed
5784            .call(unsandboxed_args("true"), ToolContext::new())
5785            .await
5786            .expect("an allowed script runs");
5787        assert_eq!(approvals.asked(), [], "an allow asks nobody");
5788
5789        let dir = tempfile::tempdir().expect("temp dir should be created");
5790        let marker = dir.path().join("ran");
5791        let denying = Approvals::denying("not today");
5792        let ask = ScriptDecision::Ask(ApprovalRequest::new(ApprovalKind::new("test"), "touch ran"));
5793        let asking = approval_tool(
5794            dir.path(),
5795            [ScriptDecision::Allow, ask],
5796            Some(denying.clone()),
5797        )
5798        .await;
5799        let error = asking
5800            .call(
5801                terminal_args("touch the marker", &format!("touch {}", marker.display())),
5802                ToolContext::new(),
5803            )
5804            .await
5805            .expect_err("the approver denied the script");
5806        assert!(error.to_string().contains("not today"), "{error}");
5807        assert_eq!(denying.asked().len(), 1);
5808        assert!(!marker.exists(), "a denied script does not run");
5809    }
5810
5811    /// The approver of the call that carries the script is asked before the
5812    /// terminal's own, and a call without one falls back to the terminal's;
5813    /// with neither the script does not run.
5814    #[cfg(unix)]
5815    #[tokio::test]
5816    async fn an_ask_goes_to_the_calls_approver_then_the_terminals() {
5817        let dir = tempfile::tempdir().expect("temp dir should be created");
5818        let terminals = Approvals::default();
5819        let tool = approval_tool(dir.path(), [], Some(terminals.clone())).await;
5820        let calls = Approvals::denying("the call's approver decides");
5821        let error = tool
5822            .call(
5823                unsandboxed_args("true"),
5824                ToolContext::new().with_approver(AnyApprover::new(calls.clone())),
5825            )
5826            .await
5827            .expect_err("the call's approver denied the script");
5828        assert!(
5829            error.to_string().contains("the call's approver decides"),
5830            "{error}"
5831        );
5832        assert_eq!((calls.asked().len(), terminals.asked().len()), (1, 0));
5833
5834        tool.run_background(ShellArgs {
5835            background: true,
5836            ..unsandboxed_args("true")
5837        })
5838        .await
5839        .expect("a call with no approver falls back to the terminal's");
5840        assert_eq!(terminals.asked().len(), 1);
5841
5842        let dir = tempfile::tempdir().expect("temp dir should be created");
5843        let bare = approval_tool(dir.path(), [], None).await;
5844        let error = bare
5845            .call(unsandboxed_args("true"), ToolContext::new())
5846            .await
5847            .expect_err("nobody can approve the script");
5848        assert!(error.to_string().contains("no approver"), "{error}");
5849    }
5850
5851    #[test]
5852    fn sandbox_is_sandboxed_or_unsandboxed_and_location_replaces_the_ssh_arguments() {
5853        for (text, mode) in [
5854            ("\"sandboxed\"", SandboxMode::Sandboxed),
5855            ("\"unsandboxed\"", SandboxMode::Unsandboxed),
5856        ] {
5857            assert_eq!(serde_json::from_str::<SandboxMode>(text).unwrap(), mode);
5858        }
5859        for removed in ["\"default\"", "\"unsafe\"", "\"ssh\""] {
5860            assert!(serde_json::from_str::<SandboxMode>(removed).is_err());
5861        }
5862        let args: ShellArgs = serde_json::from_value(serde_json::json!({
5863            "description": "list the build host",
5864            "script": "ls",
5865            "timeout": 30,
5866            "location": "build",
5867        }))
5868        .unwrap();
5869        assert_eq!(args.location.as_deref(), Some("build"));
5870        assert_eq!(args.sandbox, SandboxMode::Sandboxed);
5871        let schema = serde_json::to_value(schemars::schema_for!(ShellArgs)).unwrap();
5872        assert!(schema["properties"].get("ssh_server_id").is_none());
5873        assert!(schema["properties"].get("location").is_some());
5874    }
5875
5876    #[tokio::test]
5877    async fn child_terminal_isolates_jobs() {
5878        let dir = tempfile::tempdir().expect("temp dir should be created");
5879        let tool = fresh_terminal(dir.path()).await;
5880        tool.job_registry()
5881            .register(
5882                424_242,
5883                &crate::test_ids::lease("parent"),
5884                "parent-execution",
5885                "sleep 30",
5886                SandboxMode::Sandboxed,
5887                None,
5888            )
5889            .await;
5890
5891        let child = tool
5892            .subagent_without_grant()
5893            .await
5894            .expect("an empty grant is always given");
5895        assert!(child.job_registry().list().await.is_empty());
5896        assert_eq!(tool.job_registry().list().await.len(), 1);
5897    }
5898
5899    /// A subagent's events name its path and the main shell's the root, on
5900    /// the one handle the two share.
5901    #[cfg(unix)]
5902    #[tokio::test]
5903    async fn events_name_the_agent_whose_shell_raised_them() {
5904        let dir = tempfile::tempdir().expect("temp dir should be created");
5905        let tool = fresh_terminal(dir.path()).await;
5906        let events = tool.background_receiver();
5907        let child = tool
5908            .subagent_without_grant()
5909            .await
5910            .expect("an empty grant is always given");
5911        let grandchild = child
5912            .subagent(SubagentGrant::new(), None, "reviewer")
5913            .await
5914            .expect("an empty grant is always given");
5915
5916        for shell in [&tool, &child, &grandchild] {
5917            shell
5918                .run_background(background_args("a job", "sleep 60"))
5919                .await
5920                .expect("the job starts");
5921        }
5922        let started = events.take_started();
5923        let paths: Vec<_> = started.iter().map(|event| event.agent().clone()).collect();
5924        assert_eq!(
5925            paths,
5926            [
5927                AgentPath::main(),
5928                AgentPath::main().child("worker"),
5929                AgentPath::main().child("worker").child("reviewer"),
5930            ]
5931        );
5932
5933        for shell in [&tool, &child, &grandchild] {
5934            shell.jobs().kill_all().await;
5935        }
5936        let mut ended: Vec<_> = Vec::new();
5937        for _ in 0..3 {
5938            ended.push(ShellEvent::JobEnded(Box::new(
5939                events.recv_completed().await,
5940            )));
5941        }
5942        let mut paths: Vec<_> = ended
5943            .iter()
5944            .map(|event| event.agent().to_string())
5945            .collect();
5946        paths.sort();
5947        assert_eq!(paths, ["main", "worker", "worker/reviewer"]);
5948    }
5949
5950    /// The last handle of a subagent's shell going kills its running jobs.
5951    #[cfg(unix)]
5952    #[tokio::test]
5953    async fn dropping_the_last_handle_of_a_subagent_shell_ends_its_job() {
5954        let dir = tempfile::tempdir().expect("temp dir should be created");
5955        let tool = fresh_terminal(dir.path()).await;
5956        let child = tool
5957            .subagent_without_grant()
5958            .await
5959            .expect("an empty grant is always given");
5960        let job = child
5961            .run_background(background_args("a job", "sleep 60"))
5962            .await
5963            .expect("the job starts");
5964
5965        // A clone keeps the jobs: only the last handle's drop kills them.
5966        let clone = child.clone();
5967        drop(child);
5968        async_io::Timer::after(Duration::from_millis(300)).await;
5969        assert!(matches!(job.info().await.status, crate::JobStatus::Running));
5970        drop(clone);
5971
5972        let result = tokio::time::timeout(Duration::from_secs(30), job.wait())
5973            .await
5974            .expect("the job ends once its shell is gone")
5975            .expect("the job reports its end");
5976        assert!(
5977            !matches!(result.outcome, crate::RunOutcome::Exited { code: 0 }),
5978            "the job was killed, not run to its end: {result:?}"
5979        );
5980    }
5981
5982    /// A main shell's jobs outlive its handles, so an embedder can rebuild it
5983    /// with its background commands running.
5984    #[cfg(unix)]
5985    #[tokio::test]
5986    async fn dropping_a_main_shell_leaves_its_job_running() {
5987        let dir = tempfile::tempdir().expect("temp dir should be created");
5988        let tool = fresh_terminal(dir.path()).await;
5989        let events = tool.background_receiver();
5990        let jobs = tool.jobs();
5991        tool.run_background(background_args("a job", "sleep 60"))
5992            .await
5993            .expect("the job starts");
5994        let task_id = started_task_id(&events);
5995        drop(tool);
5996
5997        async_io::Timer::after(Duration::from_millis(500)).await;
5998        let listed = jobs.list().await;
5999        assert!(
6000            matches!(
6001                listed.as_slice(),
6002                [job] if job.task_id == task_id && matches!(job.status, crate::JobStatus::Running)
6003            ),
6004            "the job keeps running: {listed:?}"
6005        );
6006        jobs.kill_all().await;
6007    }
6008
6009    /// Background terminal arguments for `script`.
6010    #[cfg(unix)]
6011    fn background_args(description: &str, script: &str) -> ShellArgs {
6012        ShellArgs {
6013            description: description.to_string(),
6014            script: script.to_string(),
6015            interpreter: Interpreter::Shell,
6016            sandbox: SandboxMode::Sandboxed,
6017            location: None,
6018            resolution: MediaResolution::Auto,
6019            max_lines: Some(50),
6020            raw: false,
6021            timeout: 30,
6022            background: true,
6023        }
6024    }
6025
6026    /// A command's task id, the file its background output goes to and a
6027    /// subagent's space are each named by a word leased from the terminal's
6028    /// allocator, which the subagent's terminal shares; the stored output and
6029    /// the space give their words back once the terminals holding them drop.
6030    #[cfg(unix)]
6031    #[tokio::test]
6032    async fn model_facing_names_are_leased_from_the_terminal_allocator() {
6033        let ids = crate::test_ids::RecordingIds::default();
6034        let dir = tempfile::tempdir().expect("temp dir should be created");
6035        let terminal = fresh_terminal(dir.path())
6036            .await
6037            .with_id_allocator(ids.allocator());
6038
6039        let receiver = terminal.background_receiver();
6040        terminal
6041            .run_background(background_args("print a line", "echo leased"))
6042            .await
6043            .expect("terminal call should succeed");
6044        let [started] = <[_; 1]>::try_from(receiver.take_started()).expect("one started task");
6045        assert_eq!(ids.leased(), ["alfa", "bravo"]);
6046        assert_eq!(started.task_id, "alfa");
6047        assert_eq!(started.output_file.url, "outputs/bravo.txt");
6048        receiver.recv_completed().await;
6049
6050        let child = terminal
6051            .subagent_without_grant()
6052            .await
6053            .expect("an empty grant is always given");
6054        assert_eq!(ids.leased(), ["alfa", "bravo", "charlie"]);
6055        assert_eq!(
6056            child
6057                .working_dir()
6058                .file_name()
6059                .and_then(|name| name.to_str()),
6060            Some("charlie")
6061        );
6062        // The child's terminal leases from the parent's allocator.
6063        let from_child = child.id_allocator().lease().expect("a free word");
6064        assert_eq!(&*from_child, "delta");
6065        drop(from_child);
6066
6067        drop((child, terminal, receiver));
6068        for _ in 0..500 {
6069            let released = ids.released();
6070            if released.iter().any(|word| word == "bravo")
6071                && released.iter().any(|word| word == "charlie")
6072            {
6073                return;
6074            }
6075            async_io::Timer::after(Duration::from_millis(10)).await;
6076        }
6077        panic!(
6078            "the output file and the space keep their words: {:?} released",
6079            ids.released()
6080        );
6081    }
6082
6083    /// A terminal leasing its model-facing names from `ids`.
6084    #[cfg(unix)]
6085    async fn terminal_leasing_from(
6086        dir: &Path,
6087        ids: AnyIdAllocator,
6088    ) -> Shell<executor_core::tokio::TokioGlobal> {
6089        fresh_terminal(dir).await.with_id_allocator(ids)
6090    }
6091
6092    /// A foreground command gives its task id back by the time its call
6093    /// returns, so commands run one after another never exhaust the words.
6094    #[cfg(unix)]
6095    #[tokio::test]
6096    async fn foreground_commands_one_after_another_never_exhaust_the_ids() {
6097        let dir = tempfile::tempdir().expect("temp dir should be created");
6098        let ids = AnyIdAllocator::new(aither_core::WordAllocator::new(["river"]));
6099        let terminal = terminal_leasing_from(dir.path(), ids.clone()).await;
6100        for run in 0..4 {
6101            let result = terminal
6102                .call(
6103                    ShellArgs {
6104                        background: false,
6105                        ..background_args("finish at once", "exit 0")
6106                    },
6107                    ToolContext::new(),
6108                )
6109                .await
6110                .unwrap_or_else(|error| panic!("run {run} should get the one word: {error}"));
6111            assert!(!result.is_error(), "{result:?}");
6112        }
6113        assert!(
6114            terminal.job_registry().list().await.is_empty(),
6115            "a returned result leaves nothing to address"
6116        );
6117        assert_eq!(&*ids.lease().expect("river is free"), "river");
6118    }
6119
6120    /// A background job keeps its task id while the agent can still address
6121    /// it, and gives it back once its completion is delivered; after that,
6122    /// the id answers as an unknown task and can be leased again.
6123    #[cfg(unix)]
6124    #[tokio::test]
6125    async fn a_finished_background_job_gives_its_id_back_once_its_completion_is_delivered() {
6126        let dir = tempfile::tempdir().expect("temp dir should be created");
6127        let ids = AnyIdAllocator::new(aither_core::WordAllocator::new(["river", "stone"]));
6128        let terminal = terminal_leasing_from(dir.path(), ids.clone()).await;
6129        let receiver = terminal.background_receiver();
6130        let jobs = terminal.job_registry();
6131        terminal
6132            .run_background(background_args("print a line", "echo done"))
6133            .await
6134            .expect("terminal call should succeed");
6135        let [started] = <[_; 1]>::try_from(receiver.take_started()).expect("one started task");
6136        assert_eq!(started.task_id, "river");
6137        assert_eq!(started.output_file.url, "outputs/stone.txt");
6138
6139        let completed = tokio::time::timeout(Duration::from_secs(30), receiver.recv_completed())
6140            .await
6141            .expect("the job should deliver its completion");
6142        let pending = jobs
6143            .get_by_task_id("river")
6144            .await
6145            .expect("an undelivered completion keeps the job");
6146        assert!(pending.status.completion_pending(), "{pending:?}");
6147        assert!(
6148            ids.lease().is_err(),
6149            "the job and its output hold both words"
6150        );
6151
6152        drop(completed);
6153        assert!(jobs.list().await.is_empty(), "a delivered job is forgotten");
6154        assert!(jobs.terminal_read("river", 0, 1024).await.is_err());
6155        assert!(!jobs.kill_by_task_id("river").await);
6156        // The job's flow lets go of the word as it ends.
6157        for _ in 0..500 {
6158            if let Ok(again) = ids.lease() {
6159                assert_eq!(&*again, "river");
6160                return;
6161            }
6162            async_io::Timer::after(Duration::from_millis(10)).await;
6163        }
6164        panic!("a delivered job keeps its word");
6165    }
6166
6167    // These four drive a real sandbox running `/bin/pwd`. `heel` reports
6168    // `UnsupportedPlatform` off Unix, and the binary they run does not exist
6169    // there either, so there is nothing for them to exercise on Windows.
6170    #[cfg(unix)]
6171    #[tokio::test]
6172    async fn sandboxed_command_output_executes_pwd() {
6173        let dir = tempfile::tempdir().expect("temp dir should be created");
6174        let config = heel::SandboxConfig::builder()
6175            .network(DenyAll)
6176            .working_dir(
6177                std::fs::canonicalize(dir.path()).unwrap_or_else(|_| dir.path().to_path_buf()),
6178            )
6179            .security(heel::SecurityConfig::interactive())
6180            .build();
6181        let sandbox =
6182            heel::Sandbox::with_config_and_executor(config, executor_core::tokio::TokioGlobal)
6183                .await
6184                .expect("sandbox should initialize");
6185
6186        let output = sandbox
6187            .command("/bin/pwd")
6188            .output()
6189            .await
6190            .expect("sandbox command output should succeed");
6191        eprintln!("PWD OUTPUT STATUS: {:?}", output.status);
6192        eprintln!(
6193            "PWD OUTPUT STDOUT: {:?}",
6194            String::from_utf8_lossy(&output.stdout)
6195        );
6196        assert_eq!(output.status.code(), Some(0));
6197    }
6198
6199    #[cfg(unix)]
6200    #[tokio::test]
6201    async fn sandboxed_terminal_executes_pwd() {
6202        let dir = tempfile::tempdir().expect("temp dir should be created");
6203        let tool = fresh_terminal(dir.path()).await;
6204        let job_registry = tool.job_registry();
6205        let (startup_tx, _startup_rx) = async_channel::bounded(1);
6206        let result = execute_script_standalone(StandaloneExecution {
6207            ipc: None,
6208            sandbox: tool.sandbox.clone(),
6209            executor: executor_core::tokio::TokioGlobal,
6210            committed: Vec::new(),
6211            job_registry,
6212            task_id: crate::test_ids::lease("probe"),
6213            info: crate::LaunchInfo::default(),
6214            execution_id: "exec-test".to_string(),
6215            background: false,
6216            carry: None,
6217            carried_dir: None,
6218            script: "/bin/pwd".to_string(),
6219            interpreter: Interpreter::Shell,
6220            mode: SandboxMode::Sandboxed,
6221            backend: ExecutionBackend::Local {
6222                shell: Arc::from(TEST_HOST_SHELL),
6223            },
6224            lifetime: foreground_lifetime(ShellEvents::new().sender(AgentPath::main())),
6225            background_startup: BackgroundStartup::new(startup_tx),
6226            #[cfg(all(unix, feature = "jobserver"))]
6227            jobserver: None,
6228            expect: OutputFormat::Text,
6229            resolution: MediaResolution::Auto,
6230            outputs: tool.output_store().clone(),
6231            max_lines: 50,
6232            stdout: StdoutTreatment::Cleaned(OutputTreatment::Command),
6233        })
6234        .await;
6235        match result {
6236            Ok((ok, _settled)) => {
6237                eprintln!("PWD RESULT: {ok:?}");
6238                assert_eq!(ok.exit_code, 0, "unexpected terminal result: {ok:?}");
6239            }
6240            Err(error) => panic!("sandboxed pwd should succeed, got error: {error}"),
6241        }
6242    }
6243
6244    /// A sandboxed terminal command is confined by the live grants: a
6245    /// writable path takes a write and a readable-only one does not.
6246    #[cfg(unix)]
6247    #[tokio::test]
6248    async fn a_sandboxed_command_is_confined_by_the_live_grants() {
6249        let dir = tempfile::tempdir().expect("temp dir should be created");
6250        let writable = tempfile::tempdir().unwrap();
6251        let readable = tempfile::tempdir().unwrap();
6252        let tool = fresh_terminal(dir.path()).await;
6253        let working_dir = tool.working_dir().clone();
6254        let writable_paths = vec![writable.path().to_path_buf()];
6255        let readable_paths = vec![readable.path().to_path_buf()];
6256
6257        let written = writable.path().join("written");
6258        let refused = readable.path().join("refused");
6259        let script = format!(
6260            "touch {} && echo write-ok; touch {} && echo read-write-ok; true",
6261            written.display(),
6262            refused.display(),
6263        );
6264        let job_registry = tool.job_registry();
6265        let (startup_tx, _startup_rx) = async_channel::bounded(1);
6266        let result = execute_script_standalone(StandaloneExecution {
6267            ipc: None,
6268            sandbox: tool
6269                .sandbox
6270                .clone()
6271                .with_working_dir(working_dir)
6272                .with_grants(test_grants(
6273                    GitDirAccess::ReadWrite,
6274                    writable_paths,
6275                    readable_paths,
6276                    Vec::new(),
6277                )),
6278            executor: executor_core::tokio::TokioGlobal,
6279            committed: Vec::new(),
6280            job_registry,
6281            task_id: crate::test_ids::lease("policy"),
6282            info: crate::LaunchInfo::default(),
6283            execution_id: "exec-policy".to_string(),
6284            background: false,
6285            carry: None,
6286            carried_dir: None,
6287            script,
6288            interpreter: Interpreter::Shell,
6289            mode: SandboxMode::Sandboxed,
6290            backend: ExecutionBackend::Local {
6291                shell: Arc::from(TEST_HOST_SHELL),
6292            },
6293            lifetime: foreground_lifetime(ShellEvents::new().sender(AgentPath::main())),
6294            background_startup: BackgroundStartup::new(startup_tx),
6295            #[cfg(all(unix, feature = "jobserver"))]
6296            jobserver: None,
6297            expect: OutputFormat::Text,
6298            resolution: MediaResolution::Auto,
6299            outputs: tool.output_store().clone(),
6300            max_lines: 50,
6301            stdout: StdoutTreatment::Cleaned(OutputTreatment::Command),
6302        })
6303        .await
6304        .expect("the sandboxed script runs");
6305        let stdout = output_text(&result.0.stdout).expect("inline stdout");
6306        let mut lines = stdout.lines();
6307        assert_eq!(lines.next(), Some("write-ok"));
6308        assert_eq!(lines.next(), None, "a readable-only path stays read-only");
6309        assert!(written.exists() && !refused.exists());
6310    }
6311
6312    /// The grants of a session whose git directory access is `git_dir`: the
6313    /// session's own for `ReadWrite`, a child's view for `ReadOnly`.
6314    #[cfg(unix)]
6315    fn test_grants(
6316        git_dir: GitDirAccess,
6317        writable: Vec<PathBuf>,
6318        readable: Vec<PathBuf>,
6319        read_denied: Vec<PathBuf>,
6320    ) -> Grants {
6321        match git_dir {
6322            GitDirAccess::ReadOnly => Grants::new().derived(crate::GrantSnapshot {
6323                readable,
6324                writable,
6325                read_denied,
6326                git_dir,
6327            }),
6328            GitDirAccess::ReadWrite => {
6329                let grants = Grants::new();
6330                for path in writable {
6331                    grants.add_writable(path);
6332                }
6333                for path in readable {
6334                    grants.add_readable(path);
6335                }
6336                for path in read_denied {
6337                    grants.deny_read(path);
6338                }
6339                grants
6340            }
6341        }
6342    }
6343
6344    /// Runs `script` in a sandboxed session with the given grants and returns
6345    /// its standard output. Runs the pinned heel.
6346    #[cfg(unix)]
6347    async fn sandboxed_stdout(
6348        writable_paths: Vec<PathBuf>,
6349        readable_paths: Vec<PathBuf>,
6350        script: String,
6351    ) -> String {
6352        sandboxed_stdout_with(
6353            GitDirAccess::ReadWrite,
6354            writable_paths,
6355            readable_paths,
6356            Vec::new(),
6357            script,
6358        )
6359        .await
6360    }
6361
6362    /// [`sandboxed_stdout`] for a terminal whose grants give a writable
6363    /// worktree's git directory `git_dir` access.
6364    #[cfg(unix)]
6365    async fn sandboxed_stdout_with(
6366        git_dir: GitDirAccess,
6367        writable_paths: Vec<PathBuf>,
6368        readable_paths: Vec<PathBuf>,
6369        read_denied_paths: Vec<PathBuf>,
6370        script: String,
6371    ) -> String {
6372        let dir = tempfile::tempdir().expect("temp dir should be created");
6373        let tool = fresh_terminal(dir.path()).await;
6374        let (startup_tx, _startup_rx) = async_channel::bounded(1);
6375        let result = execute_script_standalone(StandaloneExecution {
6376            ipc: None,
6377            // The embedder's persistence denylist, the session's own
6378            // directory exempt.
6379            sandbox: tool
6380                .sandbox
6381                .clone()
6382                .with_write_denylist(heel::WriteDenylist::persistence().except(
6383                    std::fs::canonicalize(dir.path()).expect("the session directory exists"),
6384                ))
6385                .with_grants(test_grants(
6386                    git_dir,
6387                    writable_paths,
6388                    readable_paths,
6389                    read_denied_paths,
6390                )),
6391            executor: executor_core::tokio::TokioGlobal,
6392            committed: Vec::new(),
6393            job_registry: tool.job_registry(),
6394            task_id: crate::test_ids::lease("grants"),
6395            info: crate::LaunchInfo::default(),
6396            execution_id: "exec-grants".to_string(),
6397            background: false,
6398            carry: None,
6399            carried_dir: None,
6400            script,
6401            interpreter: Interpreter::Shell,
6402            mode: SandboxMode::Sandboxed,
6403            backend: ExecutionBackend::Local {
6404                shell: Arc::from(TEST_HOST_SHELL),
6405            },
6406            lifetime: foreground_lifetime(ShellEvents::new().sender(AgentPath::main())),
6407            background_startup: BackgroundStartup::new(startup_tx),
6408            #[cfg(all(unix, feature = "jobserver"))]
6409            jobserver: None,
6410            expect: OutputFormat::Text,
6411            resolution: MediaResolution::Auto,
6412            outputs: tool.output_store().clone(),
6413            max_lines: 200,
6414            stdout: StdoutTreatment::Cleaned(OutputTreatment::Command),
6415        })
6416        .await
6417        .expect("the sandboxed script runs");
6418        output_text(&result.0.stdout)
6419            .expect("inline stdout")
6420            .to_string()
6421    }
6422
6423    /// A sandboxed command reads an ordinary file outside every granted path.
6424    #[cfg(unix)]
6425    #[tokio::test(flavor = "multi_thread")]
6426    async fn sandboxed_commands_read_outside_the_granted_paths() {
6427        let outside = tempfile::tempdir().unwrap();
6428        let file = std::fs::canonicalize(outside.path())
6429            .unwrap()
6430            .join("ordinary.txt");
6431        std::fs::write(&file, "ordinary-content").unwrap();
6432        let stdout = sandboxed_stdout(
6433            Vec::new(),
6434            Vec::new(),
6435            format!("cat {} 2>&1; true", file.display()),
6436        )
6437        .await;
6438        assert!(stdout.contains("ordinary-content"), "{stdout}");
6439    }
6440
6441    /// The credential table applies by absolute path although the sandbox
6442    /// sets `HOME` to the session directory. Checks the credential stores
6443    /// that exist in the real home.
6444    #[cfg(unix)]
6445    #[tokio::test(flavor = "multi_thread")]
6446    async fn sandboxed_commands_cannot_read_home_credentials() {
6447        let home = PathBuf::from(std::env::var_os("HOME").expect("HOME is set"));
6448        let stores: Vec<PathBuf> = [".ssh", ".config/gh"]
6449            .into_iter()
6450            .map(|store| home.join(store))
6451            .filter(|store| store.is_dir())
6452            .collect();
6453        if stores.is_empty() {
6454            eprintln!("no ~/.ssh or ~/.config/gh in this home; nothing to deny");
6455            return;
6456        }
6457        for store in stores {
6458            assert!(
6459                std::fs::read_dir(&store).is_ok(),
6460                "the host reads {}",
6461                store.display()
6462            );
6463            let stdout = sandboxed_stdout(
6464                Vec::new(),
6465                Vec::new(),
6466                format!("ls {} 2>&1; echo rc=$?", store.display()),
6467            )
6468            .await;
6469            assert!(
6470                stdout.contains("rc=1") || stdout.contains("rc=2"),
6471                "{} must be unreadable: {stdout}",
6472                store.display()
6473            );
6474            assert!(
6475                stdout.to_lowercase().contains("not permitted")
6476                    || stdout.to_lowercase().contains("denied"),
6477                "{} must be refused by the sandbox: {stdout}",
6478                store.display()
6479            );
6480        }
6481    }
6482
6483    /// A path the embedder adds is denied, while a sibling stays readable.
6484    #[cfg(unix)]
6485    #[tokio::test(flavor = "multi_thread")]
6486    async fn sandboxed_commands_cannot_read_embedder_denied_paths() {
6487        let fake_home = tempfile::tempdir().unwrap();
6488        let fake_home = std::fs::canonicalize(fake_home.path()).unwrap();
6489        let secret = fake_home.join("vault");
6490        std::fs::create_dir(&secret).unwrap();
6491        std::fs::write(secret.join("key"), "vault-secret").unwrap();
6492        std::fs::write(fake_home.join("notes"), "plain-notes").unwrap();
6493        let stdout = sandboxed_stdout_with(
6494            GitDirAccess::ReadWrite,
6495            Vec::new(),
6496            Vec::new(),
6497            vec![secret.clone()],
6498            format!(
6499                "cat {}/key 2>&1; echo rc=$?; cat {}/notes 2>&1",
6500                secret.display(),
6501                fake_home.display()
6502            ),
6503        )
6504        .await;
6505        assert!(!stdout.contains("vault-secret"), "{stdout}");
6506        assert!(!stdout.contains("rc=0"), "{stdout}");
6507        assert!(stdout.contains("plain-notes"), "{stdout}");
6508    }
6509
6510    /// Runs the host's `git` in `dir`; the caller's environment keeps the
6511    /// user's configuration out.
6512    #[cfg(unix)]
6513    fn host_git(dir: &Path, args: &[&str]) {
6514        let status = std::process::Command::new("git")
6515            .current_dir(dir)
6516            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
6517            .args(args)
6518            .status()
6519            .expect("git runs");
6520        assert!(status.success(), "git {args:?} in {}", dir.display());
6521    }
6522
6523    /// A repository `main` with a linked worktree `linked`, under a fresh
6524    /// canonical temporary directory.
6525    #[cfg(unix)]
6526    fn repository_with_linked_worktree() -> (tempfile::TempDir, PathBuf, PathBuf) {
6527        let base = tempfile::tempdir().unwrap();
6528        let root = std::fs::canonicalize(base.path()).unwrap();
6529        let main = root.join("main");
6530        let linked = root.join("linked");
6531        std::fs::create_dir(&main).unwrap();
6532        host_git(&main, &["init", "-q", "-b", "main"]);
6533        host_git(&main, &["commit", "-q", "--allow-empty", "-m", "root"]);
6534        host_git(&main, &["worktree", "add", "-q", "../linked"]);
6535        (base, main, linked)
6536    }
6537
6538    /// Under strict isolation git works in a granted linked worktree: its
6539    /// repository is outside the worktree, and the session grants it after
6540    /// git's back-links confirm the pointer.
6541    #[cfg(unix)]
6542    #[tokio::test]
6543    async fn git_commits_in_a_granted_linked_worktree() {
6544        let (_base, main, linked) = repository_with_linked_worktree();
6545        let script = format!(
6546            "cd {linked} && git status --short 2>&1 && echo changed > file && git add file 2>&1 \
6547             && git -c user.name=t -c user.email=t@t commit -q -m inside 2>&1 && echo committed; true",
6548            linked = linked.display(),
6549        );
6550        let stdout = sandboxed_stdout(vec![linked.clone()], Vec::new(), script).await;
6551        assert_eq!(stdout.lines().last(), Some("committed"), "{stdout}");
6552        let subject = std::process::Command::new("git")
6553            .current_dir(&main)
6554            .args(["log", "-1", "--format=%s", "linked"])
6555            .output()
6556            .unwrap();
6557        assert_eq!(String::from_utf8_lossy(&subject.stdout).trim(), "inside");
6558    }
6559
6560    /// A subagent's terminal holding a plain worktree grant reads the main
6561    /// repository's git data and cannot write it: `git commit` fails and the
6562    /// branch stays where it was. The session's own terminal commits (above).
6563    #[cfg(unix)]
6564    #[tokio::test]
6565    async fn a_derived_terminal_reads_but_cannot_commit_in_a_plain_worktree_grant() {
6566        let (_base, main, linked) = repository_with_linked_worktree();
6567        let tip = |branch: &str| {
6568            let output = std::process::Command::new("git")
6569                .current_dir(&main)
6570                .args(["rev-parse", branch])
6571                .output()
6572                .unwrap();
6573            String::from_utf8_lossy(&output.stdout).trim().to_string()
6574        };
6575        let before = tip("linked");
6576        let script = format!(
6577            "cd {linked} && git status --short >/dev/null 2>&1 && echo status-ok; \
6578             git log -1 --format=%s 2>&1 | head -n 1; \
6579             echo changed > file; git add file 2>&1; \
6580             git -c user.name=t -c user.email=t@t commit -q -m inside 2>&1 && echo committed; true",
6581            linked = linked.display(),
6582        );
6583        let stdout = sandboxed_stdout_with(
6584            GitDirAccess::ReadOnly,
6585            vec![linked.clone()],
6586            Vec::new(),
6587            Vec::new(),
6588            script,
6589        )
6590        .await;
6591        assert!(stdout.lines().any(|line| line == "status-ok"), "{stdout}");
6592        assert!(stdout.lines().any(|line| line == "root"), "{stdout}");
6593        assert!(!stdout.contains("committed"), "{stdout}");
6594        assert_eq!(tip("linked"), before, "{stdout}");
6595    }
6596
6597    /// The grants a subagent's terminal derives give worktree git data read
6598    /// access; the session's own give it write access.
6599    #[test]
6600    fn only_derived_grants_read_worktree_git_data() {
6601        let parent = Grants::new();
6602        assert_eq!(parent.snapshot().git_dir, GitDirAccess::ReadWrite);
6603        let derived = parent.derived(crate::GrantSnapshot {
6604            writable: vec![PathBuf::from("/w")],
6605            ..Default::default()
6606        });
6607        assert_eq!(derived.snapshot().git_dir, GitDirAccess::ReadOnly);
6608    }
6609
6610    /// In a read-write repository the persistence paths stay unwritable, in a
6611    /// linked worktree's common git directory too, while git still commits.
6612    #[cfg(unix)]
6613    #[tokio::test]
6614    async fn git_persistence_paths_are_unwritable_in_granted_repositories() {
6615        let (_base, main, linked) = repository_with_linked_worktree();
6616        let attempt = |repository: &Path, work: &Path| {
6617            format!(
6618                "cd {work} && echo '#!/bin/sh' > {hook} 2>/dev/null && echo hook-written; \
6619                 echo '[alias]' >> {config} 2>/dev/null && echo config-written; \
6620                 echo changed > file && git add file 2>&1 \
6621                 && git -c user.name=t -c user.email=t@t commit -q -m inside 2>&1 && echo committed; true",
6622                work = work.display(),
6623                hook = repository.join(".git/hooks/pre-commit").display(),
6624                config = repository.join(".git/config").display(),
6625            )
6626        };
6627        for (repository, work, writable) in [
6628            (&main, &main, vec![main.clone()]),
6629            (&main, &linked, vec![linked.clone()]),
6630        ] {
6631            let stdout = sandboxed_stdout(writable, Vec::new(), attempt(repository, work)).await;
6632            assert_eq!(stdout.lines().last(), Some("committed"), "{stdout}");
6633            assert!(!stdout.contains("written"), "{stdout}");
6634            assert!(!main.join(".git/hooks/pre-commit").exists());
6635        }
6636    }
6637
6638    /// The persistence table forbids creating a `.git` in a granted
6639    /// directory: a new repository there is refused, one in the session
6640    /// directory (see the committing subagent's clone test) is not.
6641    #[cfg(unix)]
6642    #[tokio::test]
6643    async fn a_new_repository_in_a_granted_workdir_is_refused() {
6644        let base = tempfile::tempdir().unwrap();
6645        let root = std::fs::canonicalize(base.path()).unwrap();
6646        let script = format!(
6647            "cd {root} && if git init fresh >/dev/null 2>&1; then echo init-succeeded; fi; true",
6648            root = root.display()
6649        );
6650        let stdout = sandboxed_stdout(vec![root.clone()], Vec::new(), script).await;
6651        assert!(!stdout.contains("init-succeeded"), "{stdout}");
6652        assert!(!root.join("fresh/.git/config").exists(), "{stdout}");
6653    }
6654
6655    /// A readable linked worktree brings its repository with read access:
6656    /// git reads, and nothing is written.
6657    #[cfg(unix)]
6658    #[tokio::test]
6659    async fn a_readable_linked_worktree_reads_its_repository() {
6660        let (_base, _main, linked) = repository_with_linked_worktree();
6661        let script = format!(
6662            "cd {linked} && git log -1 --format=%s 2>&1; true",
6663            linked = linked.display(),
6664        );
6665        let stdout = sandboxed_stdout(Vec::new(), vec![linked.clone()], script).await;
6666        assert_eq!(stdout.lines().last(), Some("root"), "{stdout}");
6667    }
6668
6669    /// A `.git` file anyone can write names whatever it likes: without
6670    /// matching back-links it adds no grant, and git there gets nothing of
6671    /// the repository it points at.
6672    #[cfg(unix)]
6673    #[tokio::test]
6674    async fn a_forged_git_pointer_adds_no_grant() {
6675        let (base, main, linked) = repository_with_linked_worktree();
6676        let root = std::fs::canonicalize(base.path()).unwrap();
6677        let entry = main.join(".git/worktrees/linked");
6678        let forged = root.join("forged");
6679        std::fs::create_dir(&forged).unwrap();
6680        // The real entry of another worktree: its `gitdir` names `linked`,
6681        // not `forged`.
6682        std::fs::write(
6683            forged.join(".git"),
6684            format!("gitdir: {}\n", entry.display()),
6685        )
6686        .unwrap();
6687        // A pointer straight at the repository, and one at nothing.
6688        let direct = root.join("direct");
6689        std::fs::create_dir(&direct).unwrap();
6690        std::fs::write(
6691            direct.join(".git"),
6692            format!("gitdir: {}\n", main.join(".git").display()),
6693        )
6694        .unwrap();
6695        let writable = vec![forged.clone(), direct.clone()];
6696        for path in &writable {
6697            assert!(
6698                crate::subagent::confirmed_common_dir(path).await.is_none(),
6699                "{} confirmed",
6700                path.display()
6701            );
6702        }
6703        assert_eq!(
6704            crate::subagent::confirmed_common_dir(&linked).await,
6705            Some(main.join(".git")),
6706        );
6707        assert_eq!(
6708            crate::spawn::host::linked_worktree_grants(&writable, &[], GitDirAccess::ReadWrite)
6709                .await
6710                .unwrap()
6711                .len(),
6712            0
6713        );
6714
6715        // Reads are open under the read denylist policy, so the grant is
6716        // probed by what it would make writable: the repository, directly and
6717        // through git run in the forged worktree.
6718        let planted = main.join(".git/forged_probe");
6719        let script = format!(
6720            "echo x > {planted} 2>&1; git -C {forged} update-ref refs/heads/forged_probe HEAD 2>&1; \
6721             git -C {direct} update-ref refs/heads/direct_probe HEAD 2>&1; true",
6722            planted = planted.display(),
6723            forged = forged.display(),
6724            direct = direct.display(),
6725        );
6726        sandboxed_stdout(writable, Vec::new(), script).await;
6727        assert!(!planted.exists(), "the repository became writable");
6728        for branch in ["forged_probe", "direct_probe"] {
6729            assert!(
6730                !main.join(".git/refs/heads").join(branch).exists(),
6731                "git wrote {branch} into the repository through a forged pointer"
6732            );
6733        }
6734    }
6735
6736    #[cfg(unix)]
6737    #[tokio::test]
6738    async fn failed_command_reports_nonzero_exit_code() {
6739        let dir = tempfile::tempdir().expect("temp dir should be created");
6740        let tool = fresh_terminal(dir.path()).await;
6741
6742        let result = tool
6743            .call(
6744                ShellArgs {
6745                    description: "exit with non-zero status".to_string(),
6746                    script: "exit 42".to_string(),
6747                    interpreter: Interpreter::Shell,
6748                    sandbox: SandboxMode::Sandboxed,
6749                    location: None,
6750                    resolution: MediaResolution::Auto,
6751                    max_lines: Some(50),
6752                    raw: false,
6753                    timeout: 30,
6754                    background: false,
6755                },
6756                ToolContext::new(),
6757            )
6758            .await
6759            .expect("terminal call should not be promoted to transport error on non-zero exit");
6760
6761        assert!(
6762            !result.is_error(),
6763            "non-zero exit must not produce ToolResult::Error, got: {result:?}"
6764        );
6765        assert_eq!(
6766            render_terminal_result(&result),
6767            "(no output)\nExit code: 42.\n"
6768        );
6769        assert_eq!(
6770            result.command().map(|command| &command.outcome),
6771            Some(&CommandOutcome::Exited { code: 42 })
6772        );
6773    }
6774
6775    /// What a host reading the registry can tell: whether the session still
6776    /// owes its agent a turn.
6777    fn host_sees_owed_turn(jobs: &[crate::JobInfo]) -> bool {
6778        jobs.iter()
6779            .any(|job| job.status == JobStatus::Running || job.status.completion_pending())
6780    }
6781
6782    #[cfg(unix)]
6783    #[tokio::test]
6784    async fn a_detached_job_reads_pending_until_its_completion_is_taken() {
6785        let dir = tempfile::tempdir().expect("temp dir should be created");
6786        let tool = fresh_terminal(dir.path()).await;
6787        let receiver = tool.background_receiver();
6788        let jobs = tool.job_registry();
6789
6790        tool.run_background(ShellArgs {
6791            description: "finish at once".to_string(),
6792            script: "exit 3".to_string(),
6793            interpreter: Interpreter::Shell,
6794            sandbox: SandboxMode::Sandboxed,
6795            location: None,
6796            resolution: MediaResolution::Auto,
6797            max_lines: Some(50),
6798            raw: false,
6799            timeout: 30,
6800            background: true,
6801        })
6802        .await
6803        .expect("terminal call should succeed");
6804        let task_id = started_task_id(&receiver);
6805
6806        // The agent's receiver is the gate: the completion it receives is
6807        // held, not yet taken, while the host reads the registry.
6808        let completed = tokio::time::timeout(Duration::from_secs(30), receiver.recv_completed())
6809            .await
6810            .expect("the job should deliver its completion");
6811        assert_eq!(completed.info.task_id, task_id);
6812        let held = jobs.list().await;
6813        assert!(
6814            held.iter().all(|job| job.status != JobStatus::Running),
6815            "the job has finished: {held:?}"
6816        );
6817        assert!(
6818            host_sees_owed_turn(&held),
6819            "a finished job whose completion the agent has not taken reads as done: {held:?}"
6820        );
6821
6822        // The agent takes the completion; the registry serves the take
6823        // before the list that follows it, and forgets the job.
6824        drop(completed);
6825        let taken = jobs.list().await;
6826        assert!(taken.is_empty(), "{taken:?}");
6827        assert!(!host_sees_owed_turn(&taken), "{taken:?}");
6828        assert!(
6829            jobs.get_by_task_id(&task_id).await.is_none(),
6830            "a delivered job's id is unknown"
6831        );
6832    }
6833
6834    #[cfg(unix)]
6835    #[tokio::test]
6836    async fn background_terminal_accepts_terminal_input() {
6837        let dir = tempfile::tempdir().expect("temp dir should be created");
6838        let tool = fresh_terminal(dir.path()).await;
6839        let background_receiver = tool.background_receiver();
6840        let input_tool = input_tool(tool.jobs());
6841
6842        let result = tool
6843            .call_detached(ShellArgs {
6844                description: "wait for terminal input and echo it back".to_string(),
6845                script: "printf 'name? '; read name; printf 'hello %s\\n' \"$name\"".to_string(),
6846                interpreter: Interpreter::Shell,
6847                sandbox: SandboxMode::Sandboxed,
6848                location: None,
6849                resolution: MediaResolution::Auto,
6850                max_lines: Some(50),
6851                raw: false,
6852                timeout: 30,
6853                background: true,
6854            })
6855            .await
6856            .expect("terminal call should succeed");
6857
6858        let rendered = render_terminal_result(&result);
6859        assert!(
6860            rendered.contains("Started in background as task '"),
6861            "{rendered}"
6862        );
6863        let task_id = started_task_id(&tool.background_receiver());
6864
6865        input_tool
6866            .call(
6867                JobInputArgs {
6868                    task_id: task_id.clone(),
6869                    input: "lexo".to_string(),
6870                    append_newline: true,
6871                },
6872                ToolContext::new(),
6873            )
6874            .await
6875            .expect("terminal_input should succeed");
6876
6877        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
6878        let terminal_result = completed
6879            .result
6880            .expect("background task should complete successfully after stdin input");
6881        let stdout =
6882            output_text(&terminal_result.stdout).expect("completed task should include stdout");
6883        assert!(
6884            stdout.contains("hello lexo"),
6885            "stdin input should reach the terminal process, got: {stdout}"
6886        );
6887    }
6888
6889    /// A job is read, waited for and killed through its handle, and an
6890    /// unchanged read is data.
6891    #[cfg(unix)]
6892    #[tokio::test]
6893    async fn a_job_handle_reads_waits_and_kills() {
6894        let dir = tempfile::tempdir().expect("temp dir should be created");
6895        let tool = fresh_terminal(dir.path()).await;
6896        let events = tool.background_receiver();
6897        let jobs = tool.jobs();
6898
6899        let args = |script: &str| ShellArgs {
6900            background: true,
6901            timeout: 60,
6902            ..terminal_args("a job", script)
6903        };
6904        tool.run_background(args("printf done; exit 3"))
6905            .await
6906            .expect("the job starts");
6907        let finished = jobs
6908            .get(&started_task_id(&events))
6909            .await
6910            .expect("the shell holds the job");
6911        let result = finished.wait().await.expect("the job ends");
6912        assert_eq!(result.outcome, crate::RunOutcome::Exited { code: 3 });
6913        assert_eq!(output_text(&result.stdout), Some("done"));
6914
6915        tool.run_background(args("sleep 60"))
6916            .await
6917            .expect("the job starts");
6918        let sleeping = jobs
6919            .get(&started_task_id(&events))
6920            .await
6921            .expect("the shell holds the job");
6922        let first = sleeping.read(0, 1024).await.expect("the job reads");
6923        let cursor = first.into_delta().expect("a first read is a delta").cursor;
6924        assert_eq!(
6925            sleeping.read(cursor, 1024).await,
6926            Ok(crate::JobRead::Unchanged {
6927                task_id: sleeping.task_id().to_owned()
6928            }),
6929            "a repeat read is a poll"
6930        );
6931        // The read tool refuses a poll with a typed reason the loop can
6932        // tell from a read.
6933        let read_tool = crate::JobReadTool::new(
6934            crate::test_wording::job_tools().read,
6935            jobs.clone(),
6936            TestWording::any(),
6937            crate::output_policy::fixture::policy(),
6938        );
6939        let refusal = read_tool
6940            .call(
6941                crate::JobReadArgs {
6942                    task_id: sleeping.task_id().to_owned(),
6943                    cursor,
6944                    max_bytes: None,
6945                },
6946                ToolContext::new(),
6947            )
6948            .await
6949            .expect_err("a repeat read is refused");
6950        let refusal = refusal
6951            .downcast_ref::<crate::Refused<crate::UnchangedRead>>()
6952            .expect("the refusal is typed");
6953        assert_eq!(refusal.reason().task_id, sleeping.task_id());
6954        assert!(
6955            refusal.text().contains("produced no new output"),
6956            "{refusal}"
6957        );
6958        assert_eq!(jobs.kill_all().await, 1);
6959        let killed = sleeping.wait().await.expect("the killed job ends");
6960        assert_eq!(
6961            killed.outcome,
6962            crate::RunOutcome::Killed(crate::KillCause::User)
6963        );
6964        assert!(
6965            jobs.list()
6966                .await
6967                .iter()
6968                .all(|job| !matches!(job.status, JobStatus::Running))
6969        );
6970    }
6971
6972    /// A result the call returned, and a run, are no job's end: nothing is
6973    /// raised for them, so a caller that never reads events piles up none.
6974    #[cfg(unix)]
6975    #[tokio::test(flavor = "multi_thread")]
6976    async fn a_foreground_result_and_a_run_raise_no_job_end() {
6977        let dir = tempfile::tempdir().expect("temp dir should be created");
6978        let tool = configured_test_terminal(
6979            dir.path(),
6980            Duration::from_secs(10),
6981            Duration::from_secs(60),
6982            Duration::from_secs(60),
6983        )
6984        .await;
6985        let events = tool.background_receiver();
6986        tool.call(terminal_args("a call", "printf done"), ToolContext::new())
6987            .await
6988            .expect("the call returns its result");
6989        let start = std::fs::canonicalize(dir.path()).expect("the directory resolves");
6990        tool.run(Script::new("printf done", start, Duration::from_secs(30)))
6991            .await
6992            .expect("the run ends");
6993        assert!(events.is_empty(), "no event was raised");
6994    }
6995
6996    /// A job read through its handle owes its agent no turn, and the handle
6997    /// keeps the job after its completion was taken.
6998    #[cfg(unix)]
6999    #[tokio::test(flavor = "multi_thread")]
7000    async fn a_waited_job_owes_its_agent_nothing_and_its_handle_keeps_it() {
7001        let dir = tempfile::tempdir().expect("temp dir should be created");
7002        let tool = configured_test_terminal(
7003            dir.path(),
7004            Duration::from_secs(10),
7005            Duration::from_secs(60),
7006            Duration::from_secs(60),
7007        )
7008        .await;
7009        let events = tool.background_receiver();
7010        let jobs = tool.jobs();
7011        let args = ShellArgs {
7012            background: true,
7013            ..terminal_args("a job", "sleep 1; printf done")
7014        };
7015        tool.run_background(args).await.expect("the job starts");
7016        let job = jobs
7017            .get(&started_task_id(&events))
7018            .await
7019            .expect("the shell holds the job");
7020        let result = job.wait().await.expect("the job ends");
7021        assert_eq!(result.outcome, crate::RunOutcome::Exited { code: 0 });
7022        let ended = events.recv_completed().await;
7023        assert!(ended.pending.is_none(), "a waiter took the completion");
7024        drop(ended);
7025        // The handle holds the job, which still reads and waits.
7026        let again = job.wait().await.expect("the held job waits again");
7027        assert_eq!(output_text(&again.stdout), Some("done"));
7028        assert_eq!(jobs.list().await.len(), 1);
7029        drop(job);
7030    }
7031
7032    #[cfg(unix)]
7033    #[tokio::test]
7034    async fn killing_background_terminal_kills_descendant_processes() {
7035        let dir = tempfile::tempdir().expect("temp dir should be created");
7036        let tool = fresh_terminal(dir.path()).await;
7037        let child_pid_path = dir.path().join("child.pid");
7038
7039        let result = tool
7040            .call_detached(ShellArgs {
7041                description: "start a descendant process".to_string(),
7042                script: "sleep 30 & echo $! > child.pid; wait".to_string(),
7043                interpreter: Interpreter::Shell,
7044                sandbox: SandboxMode::Sandboxed,
7045                location: None,
7046                resolution: MediaResolution::Auto,
7047                max_lines: Some(50),
7048                raw: false,
7049                timeout: 30,
7050                background: true,
7051            })
7052            .await
7053            .expect("terminal call should succeed");
7054        let rendered = render_terminal_result(&result);
7055        assert!(
7056            rendered.contains("Started in background as task '"),
7057            "{rendered}"
7058        );
7059
7060        let mut child_pid = None;
7061        for _ in 0..100 {
7062            // `echo $! > child.pid` creates the file before writing to it,
7063            // so a successful read can still yield empty or partial
7064            // content — poll until the pid actually parses.
7065            let parsed = match async_fs::read_to_string(&child_pid_path).await {
7066                Ok(value) => value.trim().parse::<i32>().ok(),
7067                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
7068                Err(error) => panic!("failed to read child pid: {error}"),
7069            };
7070            if let Some(pid) = parsed {
7071                child_pid = Some(pid);
7072                break;
7073            }
7074            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
7075        }
7076        let child_pid = child_pid.expect("descendant pid should be written before timeout");
7077
7078        assert_eq!(tool.job_registry().kill_running().await, 1);
7079
7080        for _ in 0..100 {
7081            let exists = unsafe { libc::kill(child_pid, 0) } == 0;
7082            if !exists {
7083                return;
7084            }
7085            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
7086        }
7087        panic!("descendant process {child_pid} survived terminal cancellation");
7088    }
7089
7090    #[cfg(unix)]
7091    fn terminal_args(description: &str, script: &str) -> ShellArgs {
7092        ShellArgs {
7093            description: description.to_string(),
7094            script: script.to_string(),
7095            interpreter: Interpreter::Shell,
7096            sandbox: SandboxMode::Sandboxed,
7097            location: None,
7098            resolution: MediaResolution::Auto,
7099            max_lines: Some(50),
7100            raw: false,
7101            timeout: 30,
7102            background: false,
7103        }
7104    }
7105
7106    /// Starts `script` as a background job and returns its task id.
7107    #[cfg(unix)]
7108    async fn start_background_job(
7109        tool: &Shell<executor_core::tokio::TokioGlobal>,
7110        script: &str,
7111    ) -> String {
7112        let job = tool
7113            .run_background(ShellArgs {
7114                background: true,
7115                ..terminal_args("background job", script)
7116            })
7117            .await
7118            .expect("terminal should start the job");
7119        job.task_id().to_owned()
7120    }
7121
7122    /// Python terminal arguments for `code`.
7123    #[cfg(unix)]
7124    fn python_args(code: &str) -> ShellArgs {
7125        ShellArgs {
7126            interpreter: Interpreter::Python,
7127            ..terminal_args("run python", code)
7128        }
7129    }
7130
7131    #[cfg(unix)]
7132    #[tokio::test(flavor = "multi_thread")]
7133    async fn python_runs_and_a_raised_exception_carries_file_line_numbers() {
7134        let dir = tempfile::tempdir().expect("temp dir should be created");
7135        let tool = configured_test_terminal(
7136            dir.path(),
7137            Duration::from_secs(20),
7138            Duration::from_secs(60),
7139            Duration::from_secs(600),
7140        )
7141        .await;
7142
7143        let ok = tool
7144            .call(
7145                python_args("import sys\nprint(sys.version_info[0] * 6)"),
7146                ToolContext::new(),
7147            )
7148            .await
7149            .expect("python should run");
7150        let ok = ok.command().expect("a command result");
7151        assert_eq!(ok.outcome, CommandOutcome::Exited { code: 0 });
7152        assert_eq!(output_text(&ok.stdout).map(str::trim), Some("18"));
7153
7154        let failed = tool
7155            .call(
7156                python_args("x = 1\nraise ValueError('boom')"),
7157                ToolContext::new(),
7158            )
7159            .await
7160            .expect("a raising script is still a result");
7161        let failed = failed.command().expect("a command result");
7162        assert_eq!(failed.outcome, CommandOutcome::Exited { code: 1 });
7163        let stderr = failed
7164            .stderr
7165            .as_ref()
7166            .and_then(output_text)
7167            .expect("the traceback is on stderr");
7168        assert!(stderr.contains("line 2"), "{stderr}");
7169        assert!(stderr.contains("ValueError: boom"), "{stderr}");
7170    }
7171
7172    #[cfg(unix)]
7173    #[tokio::test(flavor = "multi_thread")]
7174    async fn python_background_job_is_read_and_killed_like_a_shell_job() {
7175        let dir = tempfile::tempdir().expect("temp dir should be created");
7176        let tool = configured_test_terminal(
7177            dir.path(),
7178            Duration::from_secs(10),
7179            Duration::from_secs(60),
7180            Duration::from_secs(600),
7181        )
7182        .await;
7183        let receiver = tool.background_receiver();
7184        let job = tool
7185            .run_background(python_args(
7186                "import time\nprint('ready', flush=True)\ntime.sleep(60)",
7187            ))
7188            .await
7189            .expect("python should start detached");
7190        let task_id = job.task_id().to_owned();
7191        assert_eq!(started_task_id(&receiver), task_id);
7192
7193        let jobs = tool.job_registry().list().await;
7194        let job = jobs
7195            .iter()
7196            .find(|job| job.task_id == task_id)
7197            .expect("the job is recorded");
7198        assert_eq!(job.interpreter, Interpreter::Python);
7199        assert!(job.script.contains("time.sleep(60)"), "{}", job.script);
7200
7201        let handle = tool
7202            .jobs()
7203            .get(&task_id)
7204            .await
7205            .expect("the shell holds the job");
7206        let deadline = std::time::Instant::now() + Duration::from_secs(20);
7207        loop {
7208            let read = handle.read(0, 4096).await.expect("the job reads");
7209            if read
7210                .into_delta()
7211                .is_some_and(|delta| String::from_utf8_lossy(&delta.bytes).contains("ready"))
7212            {
7213                break;
7214            }
7215            assert!(
7216                std::time::Instant::now() < deadline,
7217                "the job never printed"
7218            );
7219            tokio::time::sleep(Duration::from_millis(100)).await;
7220        }
7221        drop(handle);
7222
7223        assert!(tool.job_registry().kill_by_task_id(&task_id).await);
7224        wait_for_completed_task(&receiver, &task_id).await;
7225    }
7226
7227    #[cfg(unix)]
7228    #[tokio::test]
7229    async fn unsafe_python_asks_for_approval_with_its_code() {
7230        let dir = tempfile::tempdir().expect("temp dir should be created");
7231        let refusing = Approvals::denying("no");
7232        let tool = approval_tool(dir.path(), [], Some(refusing.clone())).await;
7233
7234        let code = "import os\nprint(os.getcwd())";
7235        let refused = tool
7236            .call(
7237                ShellArgs {
7238                    sandbox: SandboxMode::Unsandboxed,
7239                    ..python_args(code)
7240                },
7241                ToolContext::new(),
7242            )
7243            .await;
7244        assert!(refused.is_err(), "the refused approval stops the run");
7245        let asked = refusing.asked();
7246        assert_eq!(asked.len(), 1);
7247        assert_eq!(asked[0].subject(), code);
7248    }
7249
7250    #[cfg(unix)]
7251    #[tokio::test(flavor = "multi_thread")]
7252    async fn omitting_language_runs_shell() {
7253        let args: ShellArgs = serde_json::from_value(serde_json::json!({
7254            "description": "print",
7255            "script": "echo $((6 * 7))",
7256            "timeout": 30,
7257        }))
7258        .expect("language is optional");
7259        assert_eq!(args.interpreter, Interpreter::Shell);
7260
7261        let dir = tempfile::tempdir().expect("temp dir should be created");
7262        let tool = configured_test_terminal(
7263            dir.path(),
7264            Duration::from_secs(20),
7265            Duration::from_secs(60),
7266            Duration::from_secs(600),
7267        )
7268        .await;
7269        let result = tool
7270            .call(args, ToolContext::new())
7271            .await
7272            .expect("shell should run");
7273        let command = result.command().expect("a command result");
7274        assert_eq!(output_text(&command.stdout).map(str::trim), Some("42"));
7275    }
7276
7277    /// Collects the alerts that arrive within `window`.
7278    #[cfg(unix)]
7279    async fn alerts_within(receiver: &ShellEvents, window: Duration) -> Vec<ShellEvent> {
7280        let deadline = std::time::Instant::now() + window;
7281        let mut alerts = Vec::new();
7282        while std::time::Instant::now() < deadline {
7283            alerts.extend(receiver.take_job_alerts());
7284            tokio::time::sleep(Duration::from_millis(50)).await;
7285        }
7286        alerts
7287    }
7288
7289    /// The program a [`ModelExec`] plays for every command, whatever the
7290    /// script names.
7291    #[cfg(unix)]
7292    #[derive(Debug, Clone, Copy)]
7293    enum Modelled {
7294        /// `cat`: copies its stdin to its stdout until EOF.
7295        Cat,
7296        /// `cat; sleep`: `cat`, then runs until it is killed.
7297        CatThenSleep,
7298        /// `read name; printf 'hello %s\n' "$name"`.
7299        ReadName,
7300        /// [`RG_INPUT_PROBE`]: what `rg` given no path would search.
7301        RgInput,
7302    }
7303
7304    /// A container exec that plays its program as a container runs it: the
7305    /// process's stdin is the exec's attached stream, a pipe, unless the
7306    /// script reads the null device first, and a background exec reports a
7307    /// read that waits on that stream as its stdin watch would.
7308    #[cfg(unix)]
7309    struct ModelExec(Modelled);
7310
7311    #[cfg(unix)]
7312    impl crate::ContainerExec for ModelExec {
7313        fn exec(
7314            &self,
7315            _container_id: &str,
7316            _script: &str,
7317            _working_dir: &str,
7318            _kill_rx: Receiver<()>,
7319            _stdin_rx: Receiver<Vec<u8>>,
7320            _lifetime: ExecLifetime,
7321        ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
7322        {
7323            std::future::ready(Err("a job streams its output".to_string()))
7324        }
7325
7326        async fn exec_streamed(
7327            &self,
7328            _container_id: &str,
7329            script: &str,
7330            _working_dir: &str,
7331            kill_rx: Receiver<()>,
7332            stdin_rx: Receiver<Vec<u8>>,
7333            stdout: Sender<Vec<u8>>,
7334            lifetime: ExecLifetime,
7335        ) -> Result<ContainerExecOutcome, String> {
7336            let redirect = crate::spawn::script_reading(Pipe::Null, String::new())
7337                .expect("the null stdin redirect renders");
7338            let null_stdin = script.contains(redirect.trim_end());
7339            match self.0 {
7340                Modelled::Cat | Modelled::CatThenSleep => {
7341                    // The null device is at its end at once.
7342                    if !null_stdin {
7343                        while let Ok(bytes) = stdin_rx.recv().await {
7344                            let _ = stdout.send(bytes).await;
7345                        }
7346                    }
7347                    if matches!(self.0, Modelled::CatThenSleep) {
7348                        let _ = kill_rx.recv().await;
7349                        return Ok(ContainerExecOutcome::Killed);
7350                    }
7351                }
7352                Modelled::ReadName => {
7353                    let name = if null_stdin {
7354                        Vec::new()
7355                    } else {
7356                        if let ExecLifetime::Background { stdin_blocked } = &lifetime {
7357                            let _ = stdin_blocked.send(StdinWatchSignal::Blocked).await;
7358                        }
7359                        stdin_rx.recv().await.unwrap_or_default()
7360                    };
7361                    let name = String::from_utf8_lossy(&name);
7362                    let _ = stdout
7363                        .send(format!("hello {}\n", name.trim_end()).into_bytes())
7364                        .await;
7365                }
7366                // `rg` reads a stdin that is a file, a FIFO or a socket.
7367                Modelled::RgInput => {
7368                    let searched: &[u8] = if null_stdin {
7369                        b"directory\n"
7370                    } else {
7371                        b"stdin\n"
7372                    };
7373                    let _ = stdout.send(searched.to_vec()).await;
7374                }
7375            }
7376            Ok(ContainerExecOutcome::Completed {
7377                output: std::process::Output {
7378                    status: std::os::unix::process::ExitStatusExt::from_raw(0),
7379                    stdout: Vec::new(),
7380                    stderr: Vec::new(),
7381                },
7382                killed: Vec::new(),
7383            })
7384        }
7385    }
7386
7387    /// A shell whose home backend is a container that plays `program` for
7388    /// every command, waiting `foreground_wait` in the foreground.
7389    #[cfg(unix)]
7390    async fn modelled_container_terminal(
7391        dir: &Path,
7392        program: Modelled,
7393        foreground_wait: Duration,
7394    ) -> Shell<executor_core::tokio::TokioGlobal> {
7395        let runtime = ContainerShellRuntime::new(
7396            "aither-test-stdin",
7397            crate::HostRoute::new(
7398                "host.docker.internal",
7399                std::net::IpAddr::from([127, 0, 0, 1]),
7400            )
7401            .expect("loopback is routable"),
7402            crate::AnyContainerExec::new(Arc::new(ModelExec(program))),
7403        );
7404        let tool = Shell::new_exact_on(
7405            container_sandbox(&runtime, dir),
7406            executor_core::tokio::TokioGlobal,
7407            crate::limits::fixture::limits(),
7408            crate::output_policy::fixture::policy(),
7409            TestWording::any(),
7410            crate::test_wording::job_tools(),
7411        )
7412        .await
7413        .expect("terminal tool should initialize");
7414        tool.limits.foreground_wait.set_normal(foreground_wait);
7415        tool.limits.timeout_cap.set(Duration::from_secs(60));
7416        tool.limits.long_job_alert.set(Duration::from_secs(600));
7417        tool
7418    }
7419
7420    /// Python that prints what `rg` given no path would search, by the rule
7421    /// `rg` follows: its stdin when that is a regular file, a FIFO or a
7422    /// socket, otherwise the working directory.
7423    #[cfg(unix)]
7424    const RG_INPUT_PROBE: &str = "import os, stat; mode = os.fstat(0).st_mode; print('stdin' if stat.S_ISREG(mode) or stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode) else 'directory')";
7425
7426    /// A foreground command's stdin is the null device, so `rg` given no
7427    /// path searches the working directory; a background job's is a pipe.
7428    #[cfg(unix)]
7429    async fn rg_searches_the_directory_only_in_the_foreground(
7430        tool: &Shell<executor_core::tokio::TokioGlobal>,
7431    ) {
7432        let result = tool
7433            .call(python_args(RG_INPUT_PROBE), ToolContext::new())
7434            .await
7435            .expect("the foreground probe runs");
7436        let command = result.command().expect("a command result");
7437        assert_eq!(command.outcome, CommandOutcome::Exited { code: 0 });
7438        assert_eq!(
7439            output_text(&command.stdout).map(str::trim),
7440            Some("directory")
7441        );
7442
7443        let job = tool
7444            .run_background(ShellArgs {
7445                background: true,
7446                ..python_args(RG_INPUT_PROBE)
7447            })
7448            .await
7449            .expect("the background probe starts");
7450        let result = job.wait().await.expect("the background probe ends");
7451        assert_eq!(output_text(&result.stdout).map(str::trim), Some("stdin"));
7452    }
7453
7454    /// A foreground `cat` returns at once with empty output: nothing feeds a
7455    /// call that waits, so it is never promoted for want of input.
7456    #[cfg(unix)]
7457    async fn a_foreground_cat_returns_at_once_with_empty_output(
7458        tool: &Shell<executor_core::tokio::TokioGlobal>,
7459    ) {
7460        let started = std::time::Instant::now();
7461        let result = tool
7462            .call(
7463                terminal_args("read all of stdin", "cat"),
7464                ToolContext::new(),
7465            )
7466            .await
7467            .expect("terminal call should succeed");
7468        let command = result.command().expect("a command result");
7469        assert_eq!(command.outcome, CommandOutcome::Exited { code: 0 });
7470        assert!(
7471            output_text(&command.stdout).is_some_and(str::is_empty) && command.stderr.is_none(),
7472            "{command:?}"
7473        );
7474        assert!(
7475            started.elapsed() < Duration::from_secs(10),
7476            "cat read EOF at once, well inside the foreground window"
7477        );
7478    }
7479
7480    /// A foreground command promoted past the window keeps the stdin it
7481    /// started with: input to it is refused, saying why, and nothing alerts
7482    /// that it waits for input.
7483    #[cfg(unix)]
7484    async fn a_promoted_foreground_job_refuses_input(
7485        tool: &Shell<executor_core::tokio::TokioGlobal>,
7486        script: &str,
7487    ) {
7488        let events = tool.background_receiver();
7489        let result = tool
7490            .call(
7491                terminal_args("read stdin, then keep running", script),
7492                ToolContext::new(),
7493            )
7494            .await
7495            .expect("terminal call should succeed");
7496        let command = result.command().expect("a command result");
7497        let CommandOutcome::Running { task_id, .. } = &command.outcome else {
7498            panic!(
7499                "a command still running at the window is promoted, got {:?}",
7500                command.outcome
7501            );
7502        };
7503
7504        let refusal = input_tool(tool.jobs())
7505            .call(
7506                JobInputArgs {
7507                    task_id: task_id.clone(),
7508                    input: "lexo".to_string(),
7509                    append_newline: true,
7510                },
7511                ToolContext::new(),
7512            )
7513            .await
7514            .expect_err("a promoted foreground job takes no input");
7515        let refusal = refusal
7516            .downcast_ref::<crate::Refused<CallRefusal>>()
7517            .expect("the refusal is typed");
7518        assert_eq!(
7519            refusal.reason(),
7520            &CallRefusal::NoStdin {
7521                task_id: task_id.clone()
7522            }
7523        );
7524        assert!(
7525            refusal.text().contains("started in the foreground"),
7526            "{refusal}"
7527        );
7528        assert!(
7529            events.take_job_alerts().is_empty(),
7530            "a job without a stdin pipe raises no stdin alert"
7531        );
7532        assert!(
7533            tool.job_registry().kill_by_task_id(task_id).await,
7534            "the promoted job still runs"
7535        );
7536    }
7537
7538    #[cfg(unix)]
7539    #[tokio::test(flavor = "multi_thread")]
7540    async fn a_local_foreground_rg_searches_the_working_directory() {
7541        let dir = tempfile::tempdir().expect("temp dir should be created");
7542        let tool = configured_test_terminal(
7543            dir.path(),
7544            Duration::from_secs(30),
7545            Duration::from_secs(60),
7546            Duration::from_secs(600),
7547        )
7548        .await;
7549        rg_searches_the_directory_only_in_the_foreground(&tool).await;
7550    }
7551
7552    #[cfg(unix)]
7553    #[tokio::test(flavor = "multi_thread")]
7554    async fn a_container_foreground_rg_searches_the_working_directory() {
7555        let dir = tempfile::tempdir().expect("temp dir should be created");
7556        let tool =
7557            modelled_container_terminal(dir.path(), Modelled::RgInput, Duration::from_secs(30))
7558                .await;
7559        rg_searches_the_directory_only_in_the_foreground(&tool).await;
7560    }
7561
7562    #[cfg(unix)]
7563    #[tokio::test(flavor = "multi_thread")]
7564    async fn a_local_foreground_cat_returns_at_once() {
7565        let dir = tempfile::tempdir().expect("temp dir should be created");
7566        let tool = configured_test_terminal(
7567            dir.path(),
7568            Duration::from_secs(30),
7569            Duration::from_secs(60),
7570            Duration::from_secs(600),
7571        )
7572        .await;
7573        a_foreground_cat_returns_at_once_with_empty_output(&tool).await;
7574    }
7575
7576    #[cfg(unix)]
7577    #[tokio::test(flavor = "multi_thread")]
7578    async fn a_container_foreground_cat_returns_at_once() {
7579        let dir = tempfile::tempdir().expect("temp dir should be created");
7580        let tool =
7581            modelled_container_terminal(dir.path(), Modelled::Cat, Duration::from_secs(30)).await;
7582        a_foreground_cat_returns_at_once_with_empty_output(&tool).await;
7583    }
7584
7585    #[cfg(unix)]
7586    #[tokio::test(flavor = "multi_thread")]
7587    async fn a_promoted_local_foreground_job_refuses_input() {
7588        let dir = tempfile::tempdir().expect("temp dir should be created");
7589        let tool = configured_test_terminal(
7590            dir.path(),
7591            Duration::from_secs(1),
7592            Duration::from_secs(60),
7593            Duration::from_secs(600),
7594        )
7595        .await;
7596        a_promoted_foreground_job_refuses_input(&tool, "cat; sleep 30").await;
7597    }
7598
7599    #[cfg(unix)]
7600    #[tokio::test(flavor = "multi_thread")]
7601    async fn a_promoted_container_foreground_job_refuses_input() {
7602        let dir = tempfile::tempdir().expect("temp dir should be created");
7603        let tool =
7604            modelled_container_terminal(dir.path(), Modelled::CatThenSleep, Duration::from_secs(1))
7605                .await;
7606        a_promoted_foreground_job_refuses_input(&tool, "cat; sleep 30").await;
7607    }
7608
7609    #[cfg(unix)]
7610    #[tokio::test(flavor = "multi_thread")]
7611    async fn a_container_background_job_blocked_on_stdin_yields_one_alert() {
7612        let dir = tempfile::tempdir().expect("temp dir should be created");
7613        let tool =
7614            modelled_container_terminal(dir.path(), Modelled::ReadName, Duration::from_secs(10))
7615                .await;
7616        background_reader_alerts_once_and_resumes_when_fed(
7617            &tool,
7618            "read name; printf 'hello %s\\n' \"$name\"",
7619        )
7620        .await;
7621    }
7622
7623    /// A container command's exec carries the commands the shell's provider
7624    /// serves for that launch. (No container runs here: the exec is a fake
7625    /// that records the script it was given, so the serving of the answer is
7626    /// covered by `container_ipc_bridge_round_trips_a_command_over_tcp`.)
7627    #[cfg(unix)]
7628    #[tokio::test(flavor = "multi_thread")]
7629    async fn a_container_command_is_given_the_providers_router_for_its_launch() {
7630        struct RecordingExec(Sender<String>);
7631
7632        impl crate::ContainerExec for RecordingExec {
7633            fn exec(
7634                &self,
7635                _container_id: &str,
7636                _script: &str,
7637                _working_dir: &str,
7638                _kill_rx: Receiver<()>,
7639                _stdin_rx: Receiver<Vec<u8>>,
7640                _lifetime: ExecLifetime,
7641            ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
7642            {
7643                std::future::ready(Err("a job streams its output".to_string()))
7644            }
7645
7646            async fn exec_streamed(
7647                &self,
7648                _container_id: &str,
7649                script: &str,
7650                _working_dir: &str,
7651                _kill_rx: Receiver<()>,
7652                _stdin_rx: Receiver<Vec<u8>>,
7653                _stdout: Sender<Vec<u8>>,
7654                _lifetime: ExecLifetime,
7655            ) -> Result<ContainerExecOutcome, String> {
7656                self.0.send(script.to_owned()).await.unwrap();
7657                Ok(ContainerExecOutcome::Completed {
7658                    output: std::process::Output {
7659                        status: std::os::unix::process::ExitStatusExt::from_raw(0),
7660                        stdout: Vec::new(),
7661                        stderr: Vec::new(),
7662                    },
7663                    killed: Vec::new(),
7664                })
7665            }
7666        }
7667
7668        let dir = tempfile::tempdir().expect("temp dir should be created");
7669        let (job_registry, job_registry_service) =
7670            job_registry_channel(crate::output_policy::fixture::policy());
7671        tokio::spawn(async move { job_registry_service.serve().await });
7672        let (scripts_tx, scripts) = async_channel::unbounded();
7673        let runtime = ContainerShellRuntime::new(
7674            "aither-test-ipc-provider",
7675            crate::HostRoute::new(
7676                "host.docker.internal",
7677                std::net::IpAddr::from([127, 0, 0, 1]),
7678            )
7679            .expect("loopback is routable"),
7680            crate::AnyContainerExec::new(Arc::new(RecordingExec(scripts_tx))),
7681        );
7682        let provider = crate::spawn::ipc_fixture::Recording::default();
7683        let erased = crate::AnyIpcProvider::new(provider.clone());
7684        let info = crate::LaunchInfo::new("probe", None, SandboxMode::Sandboxed);
7685        let (startup_tx, _startup_rx) = async_channel::bounded(1);
7686        let alert_tx = ShellEvents::new().sender(AgentPath::main());
7687        execute_container_job(ContainerJobExecution {
7688            executor: executor_core::tokio::TokioGlobal,
7689            sandbox: &container_sandbox(&runtime, dir.path()),
7690            ipc: Some(&erased),
7691            committed: &[],
7692            task_id: &crate::test_ids::lease("probe"),
7693            info: info.clone(),
7694            execution_id: "exec-test",
7695            script: "probe",
7696            interpreter: Interpreter::Shell,
7697            mode: SandboxMode::Sandboxed,
7698            container_runtime: &runtime,
7699            job_registry: &job_registry,
7700            lifetime: foreground_lifetime(alert_tx),
7701            background_startup: &BackgroundStartup::new(startup_tx),
7702            carry: None,
7703            #[cfg(all(unix, feature = "jobserver"))]
7704            job_fifo: None,
7705        })
7706        .await
7707        .expect("the exec completes");
7708        let script = scripts.recv().await.expect("the exec ran a script");
7709        assert!(script.contains(r#"--commands '{"probe":"#), "{script}");
7710        let launches = provider.launches.lock().unwrap();
7711        assert_eq!(launches.len(), 1);
7712        assert_eq!(launches[0].task_id.as_deref(), Some("probe"));
7713        assert_eq!(launches[0].mode, SandboxMode::Sandboxed);
7714    }
7715
7716    /// With a pool configured, a container command's script exports the
7717    /// jobserver variables naming its own fifo inside the container, and the
7718    /// fifo's relay is told once the command's exec ends.
7719    /// Captures each command's script; plays a jobserver relay that reports
7720    /// ready and records what the host tells it.
7721    #[cfg(all(unix, feature = "jobserver"))]
7722    struct CapturingExec {
7723        scripts: Sender<String>,
7724        relay_heard: Sender<Vec<u8>>,
7725        /// How many execs have started: the first is the jobserver relay.
7726        started: std::sync::atomic::AtomicUsize,
7727    }
7728
7729    #[cfg(all(unix, feature = "jobserver"))]
7730    impl crate::ContainerExec for CapturingExec {
7731        fn exec(
7732            &self,
7733            _container_id: &str,
7734            _script: &str,
7735            _working_dir: &str,
7736            _kill_rx: Receiver<()>,
7737            _stdin_rx: Receiver<Vec<u8>>,
7738            _lifetime: ExecLifetime,
7739        ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
7740        {
7741            std::future::ready(Err("a job streams its output".to_string()))
7742        }
7743
7744        async fn exec_streamed(
7745            &self,
7746            _container_id: &str,
7747            script: &str,
7748            _working_dir: &str,
7749            _kill_rx: Receiver<()>,
7750            stdin_rx: Receiver<Vec<u8>>,
7751            stdout: Sender<Vec<u8>>,
7752            _lifetime: ExecLifetime,
7753        ) -> Result<ContainerExecOutcome, String> {
7754            if self
7755                .started
7756                .fetch_add(1, std::sync::atomic::Ordering::AcqRel)
7757                > 0
7758            {
7759                self.scripts.send(script.to_string()).await.unwrap();
7760                return Ok(ContainerExecOutcome::Completed {
7761                    output: std::process::Output {
7762                        status: std::os::unix::process::ExitStatusExt::from_raw(0),
7763                        stdout: Vec::new(),
7764                        stderr: Vec::new(),
7765                    },
7766                    killed: Vec::new(),
7767                });
7768            }
7769            stdout.send(b"R".to_vec()).await.unwrap();
7770            while let Ok(message) = stdin_rx.recv().await {
7771                let finished = message == b"F";
7772                self.relay_heard.send(message).await.unwrap();
7773                if finished {
7774                    break;
7775                }
7776            }
7777            Err("the relay exits".to_string())
7778        }
7779    }
7780
7781    #[cfg(all(unix, feature = "jobserver"))]
7782    #[tokio::test(flavor = "multi_thread")]
7783    async fn container_command_environment_names_its_own_fifo() {
7784        let dir = tempfile::tempdir().expect("temp dir should be created");
7785        let pool = crate::jobserver::JobPool::create_fifo(dir.path().join("pool.fifo"), 2)
7786            .expect("pool should be created");
7787        let (broker, service) =
7788            crate::jobserver::job_broker_channel(pool, dir.path().join("commands"))
7789                .expect("broker should start");
7790        tokio::spawn(async move { service.serve().await });
7791        let (job_registry, job_registry_service) =
7792            job_registry_channel(crate::output_policy::fixture::policy());
7793        tokio::spawn(async move { job_registry_service.serve().await });
7794        let (scripts_tx, scripts) = async_channel::unbounded();
7795        let (heard_tx, heard) = async_channel::unbounded();
7796        let runtime = ContainerShellRuntime::new(
7797            "aither-test-jobserver",
7798            crate::HostRoute::new(
7799                "host.docker.internal",
7800                std::net::IpAddr::from([127, 0, 0, 1]),
7801            )
7802            .expect("loopback is routable"),
7803            crate::AnyContainerExec::new(Arc::new(CapturingExec {
7804                scripts: scripts_tx,
7805                relay_heard: heard_tx,
7806                started: std::sync::atomic::AtomicUsize::new(0),
7807            })),
7808        );
7809        let job_fifo = crate::container_jobserver::open_container_job_fifo(
7810            &broker,
7811            &runtime,
7812            &test_container_launch().bin_dir().join("python3"),
7813            executor_core::tokio::TokioGlobal,
7814        )
7815        .await
7816        .expect("the relay reports ready");
7817        let fifo_path = job_fifo.path().clone();
7818        let (startup_tx, _startup_rx) = async_channel::bounded(1);
7819        let alert_tx = ShellEvents::new().sender(AgentPath::main());
7820        execute_container_job(ContainerJobExecution {
7821            executor: executor_core::tokio::TokioGlobal,
7822            sandbox: &container_sandbox(&runtime, dir.path()),
7823            ipc: None,
7824            committed: &[],
7825            task_id: &crate::test_ids::lease("probe"),
7826            info: crate::LaunchInfo::default(),
7827            execution_id: "exec-test",
7828            script: "make",
7829            interpreter: Interpreter::Shell,
7830            mode: SandboxMode::Sandboxed,
7831            container_runtime: &runtime,
7832            job_registry: &job_registry,
7833            lifetime: foreground_lifetime(alert_tx),
7834            background_startup: &BackgroundStartup::new(startup_tx),
7835            carry: None,
7836            job_fifo: Some(job_fifo),
7837        })
7838        .await
7839        .expect("the container exec completes");
7840
7841        let script = scripts.recv().await.expect("the command ran");
7842        for name in ["MAKEFLAGS", "CARGO_MAKEFLAGS", "MFLAGS"] {
7843            assert!(
7844                script.contains(&format!("export {name}=")) && script.contains(fifo_path.as_str()),
7845                "{name} names the container fifo: {script}"
7846            );
7847        }
7848        assert!(!script.contains(dir.path().to_str().unwrap()));
7849        // The relay asked for nothing, so all it hears is the finish.
7850        assert_eq!(heard.recv().await.unwrap(), b"F");
7851    }
7852
7853    /// A local background job whose `reader` script blocks on stdin yields
7854    /// exactly one alert until it is fed, and finishes once it is.
7855    #[cfg(unix)]
7856    async fn stdin_reader_alerts_once_and_resumes_when_fed(reader: &str) {
7857        let dir = tempfile::tempdir().expect("temp dir should be created");
7858        let tool = configured_test_terminal(
7859            dir.path(),
7860            Duration::from_secs(10),
7861            Duration::from_secs(60),
7862            Duration::from_secs(600),
7863        )
7864        .await;
7865        background_reader_alerts_once_and_resumes_when_fed(&tool, reader).await;
7866    }
7867
7868    /// A background job of `tool` whose `reader` script blocks on stdin
7869    /// yields exactly one alert until it is fed through the input tool, and
7870    /// finishes once it is.
7871    #[cfg(unix)]
7872    async fn background_reader_alerts_once_and_resumes_when_fed(
7873        tool: &Shell<executor_core::tokio::TokioGlobal>,
7874        reader: &str,
7875    ) {
7876        let background_receiver = tool.background_receiver();
7877        let task_id = start_background_job(tool, reader).await;
7878
7879        let alerts = alerts_within(&background_receiver, Duration::from_secs(8)).await;
7880        assert!(
7881            matches!(
7882                alerts.as_slice(),
7883                [ShellEvent::StdinBlocked(job)] if job.task_id == task_id
7884            ),
7885            "a blocked reader must yield exactly one stdin alert: {alerts:?}"
7886        );
7887
7888        input_tool(tool.jobs())
7889            .call(
7890                JobInputArgs {
7891                    task_id: task_id.clone(),
7892                    input: "lexo".to_string(),
7893                    append_newline: true,
7894                },
7895                ToolContext::new(),
7896            )
7897            .await
7898            .expect("terminal_input should succeed");
7899        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
7900        let terminal_result = completed.result.expect("the fed job should complete");
7901        let stdout =
7902            output_text(&terminal_result.stdout).expect("completed task should include stdout");
7903        assert!(stdout.contains("hello lexo"), "got: {stdout}");
7904        assert!(
7905            background_receiver.take_job_alerts().is_empty(),
7906            "a fed job that finished must not alert again"
7907        );
7908    }
7909
7910    #[cfg(unix)]
7911    #[tokio::test(flavor = "multi_thread")]
7912    async fn background_job_blocked_on_stdin_yields_one_alert() {
7913        stdin_reader_alerts_once_and_resumes_when_fed("read name; printf 'hello %s\\n' \"$name\"")
7914            .await;
7915    }
7916
7917    #[cfg(unix)]
7918    #[tokio::test(flavor = "multi_thread")]
7919    async fn background_grandchild_blocked_on_stdin_yields_one_alert() {
7920        stdin_reader_alerts_once_and_resumes_when_fed(
7921            "( ( read name; printf 'hello %s\\n' \"$name\" ); true )",
7922        )
7923        .await;
7924    }
7925
7926    #[cfg(unix)]
7927    #[tokio::test(flavor = "multi_thread")]
7928    async fn background_job_that_never_reads_stdin_yields_no_alert() {
7929        let dir = tempfile::tempdir().expect("temp dir should be created");
7930        let tool = configured_test_terminal(
7931            dir.path(),
7932            Duration::from_secs(10),
7933            Duration::from_secs(60),
7934            Duration::from_secs(600),
7935        )
7936        .await;
7937        let background_receiver = tool.background_receiver();
7938        let task_id = start_background_job(&tool, "sleep 3; echo finished").await;
7939
7940        let alerts = alerts_within(&background_receiver, Duration::from_secs(4)).await;
7941        assert!(alerts.is_empty(), "no alert expected: {alerts:?}");
7942        wait_for_completed_task(&background_receiver, &task_id).await;
7943    }
7944
7945    /// The nice value `level` steps below this test process lands at, capped
7946    /// at the kernel's lowest priority — the same computation heel applies.
7947    #[cfg(unix)]
7948    fn expected_lowered_nice(level: u8) -> i64 {
7949        // SAFETY: reads the calling process's own nice value.
7950        let current = unsafe { libc::getpriority(libc::PRIO_PROCESS as _, 0) };
7951        i64::from(current + i32::from(level)).min(19)
7952    }
7953
7954    #[cfg(unix)]
7955    fn test_nice_priority() -> ProcessPriority {
7956        ProcessPriority::new(
7957            CpuPriority::Nice(NiceLevel::new(10).expect("nice level 10 is in range")),
7958            IoPriority::Normal,
7959        )
7960    }
7961
7962    /// A terminal with the given shortened limits.
7963    #[cfg(unix)]
7964    async fn configured_test_terminal(
7965        dir: &Path,
7966        foreground_wait: Duration,
7967        timeout_cap: Duration,
7968        alert_after: Duration,
7969    ) -> Shell<executor_core::tokio::TokioGlobal> {
7970        let tool = fresh_terminal(dir).await;
7971        tool.limits.foreground_wait.set_normal(foreground_wait);
7972        tool.limits.timeout_cap.set(timeout_cap);
7973        tool.limits.long_job_alert.set(alert_after);
7974        tool
7975    }
7976
7977    /// A foreground command still running at the window promotes to a
7978    /// background task instead of dying; its `timeout` then kills it with
7979    /// its descendants.
7980    #[cfg(unix)]
7981    #[tokio::test(flavor = "multi_thread")]
7982    async fn foreground_command_still_running_at_the_window_promotes_and_times_out_with_descendants()
7983     {
7984        let dir = tempfile::tempdir().expect("temp dir should be created");
7985        let tool = configured_test_terminal(
7986            dir.path(),
7987            Duration::from_secs(1),
7988            Duration::from_secs(60),
7989            Duration::from_secs(60),
7990        )
7991        .await;
7992        let background_receiver = tool.background_receiver();
7993        let child_pid_path = dir.path().join("child.pid");
7994
7995        let result = tool
7996            .call(
7997                ShellArgs {
7998                    description: "start a descendant process".to_string(),
7999                    script: "sleep 30 & echo $! > child.pid; wait".to_string(),
8000                    interpreter: Interpreter::Shell,
8001                    sandbox: SandboxMode::Sandboxed,
8002                    location: None,
8003                    resolution: MediaResolution::Auto,
8004                    max_lines: Some(50),
8005                    raw: false,
8006                    timeout: 3,
8007                    background: false,
8008                },
8009                ToolContext::new(),
8010            )
8011            .await
8012            .expect("terminal call should succeed");
8013        let rendered = render_terminal_result(&result);
8014        assert!(
8015            rendered.contains("Started in background as task '"),
8016            "the still-running command must promote: {rendered}"
8017        );
8018        let task_id = started_task_id(&background_receiver);
8019
8020        let child_pid = async_fs::read_to_string(&child_pid_path)
8021            .await
8022            .expect("descendant pid file should exist")
8023            .trim()
8024            .parse::<i32>()
8025            .expect("descendant pid should parse");
8026        for _ in 0..500 {
8027            // SAFETY: signal 0 probes process existence.
8028            if unsafe { libc::kill(child_pid, 0) } != 0 {
8029                break;
8030            }
8031            async_io::Timer::after(std::time::Duration::from_millis(20)).await;
8032        }
8033        assert!(
8034            unsafe { libc::kill(child_pid, 0) } != 0,
8035            "descendant process {child_pid} survived the timeout kill"
8036        );
8037
8038        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
8039        let info = tool
8040            .job_registry()
8041            .get_by_task_id(&task_id)
8042            .await
8043            .expect("the finished job stays in the registry");
8044        assert!(
8045            matches!(
8046                info.status,
8047                JobStatus::Killed {
8048                    cause: crate::KillCause::Timeout(_),
8049                    delivery: crate::Delivery::Pending
8050                }
8051            ),
8052            "the promoted job should be killed at its timeout: {completed:?}"
8053        );
8054    }
8055
8056    /// A longer foreground window put in force through the shared handle
8057    /// keeps a command that outlasts the normal window in the foreground, and
8058    /// the normal window applies again once it is restored.
8059    #[cfg(unix)]
8060    #[tokio::test(flavor = "multi_thread")]
8061    async fn a_longer_foreground_window_holds_until_restored() {
8062        let dir = tempfile::tempdir().expect("temp dir should be created");
8063        let tool = configured_test_terminal(
8064            dir.path(),
8065            Duration::from_secs(1),
8066            Duration::from_secs(60),
8067            Duration::from_secs(60),
8068        )
8069        .await;
8070        let wait = tool.foreground_wait();
8071        let run = || async {
8072            let result = tool
8073                .call(
8074                    ShellArgs {
8075                        description: "outlast the normal window".to_string(),
8076                        script: "sleep 2 & wait; echo finished".to_string(),
8077                        interpreter: Interpreter::Shell,
8078                        sandbox: SandboxMode::Sandboxed,
8079                        location: None,
8080                        resolution: MediaResolution::Auto,
8081                        max_lines: Some(50),
8082                        raw: false,
8083                        timeout: 30,
8084                        background: false,
8085                    },
8086                    ToolContext::new(),
8087                )
8088                .await
8089                .expect("terminal call should succeed");
8090            render_terminal_result(&result)
8091        };
8092
8093        wait.extend(Duration::from_secs(20));
8094        let during = run().await;
8095        assert!(
8096            during.contains("finished") && !during.contains("Started in background"),
8097            "the longer window keeps the command in the foreground: {during}"
8098        );
8099
8100        wait.restore();
8101        let after = run().await;
8102        assert!(
8103            after.contains("Started in background as task '"),
8104            "the normal window applies again: {after}"
8105        );
8106    }
8107
8108    /// What a test leaves running after its shell exits.
8109    ///
8110    /// `Plain` is a `sleep` in the shell's process group. `Setsid` is a helper
8111    /// program that calls `setsid` and stays alive, so it also leaves the
8112    /// group and the session. The helper is built here because macOS ships no
8113    /// `setsid` binary, and because the kernel withholds the environment of
8114    /// Apple's own binaries (`sleep`, `perl`), which is what finds a `setsid`
8115    /// descendant once its parent is gone.
8116    #[cfg(unix)]
8117    #[derive(Clone, Copy, Debug)]
8118    enum Descendant {
8119        Plain,
8120        Setsid,
8121    }
8122
8123    /// The name of the `setsid` helper program, and so of its process.
8124    #[cfg(unix)]
8125    const SETSID_HELPER: &str = "setsid-helper";
8126
8127    /// The directory the sandbox may execute programs from: the shell's own
8128    /// working directory.
8129    #[cfg(unix)]
8130    fn exec_dir<E>(tool: &Shell<E>) -> PathBuf {
8131        tool.working_dir.clone()
8132    }
8133
8134    /// Builds the `setsid` helper into `dir` and returns its path. The sandbox
8135    /// executes only what lies under a granted directory, so `dir` is the
8136    /// shell's [`exec_dir`].
8137    #[cfg(unix)]
8138    fn build_setsid_helper(dir: &Path) -> PathBuf {
8139        let source = dir.join("setsid_helper.rs");
8140        std::fs::write(
8141            &source,
8142            "extern \"C\" { fn setsid() -> i32; }\n\
8143             fn main() {\n\
8144                 let seconds: u64 = std::env::args().nth(1).expect(\"seconds\").parse().expect(\"seconds\");\n\
8145                 // SAFETY: `setsid` takes no arguments.\n\
8146                 if unsafe { setsid() } < 0 { std::process::exit(1); }\n\
8147                 std::thread::sleep(std::time::Duration::from_secs(seconds));\n\
8148             }\n",
8149        )
8150        .expect("helper source should be written");
8151        let binary = dir.join(SETSID_HELPER);
8152        let status = std::process::Command::new("rustc")
8153            .arg("--edition=2021")
8154            .arg("-o")
8155            .arg(&binary)
8156            .arg(&source)
8157            .status()
8158            .expect("rustc should run");
8159        assert!(status.success(), "the setsid helper should compile");
8160        binary
8161    }
8162
8163    #[cfg(unix)]
8164    impl Descendant {
8165        /// The name the descendant's process has once it ran `exec`.
8166        const fn process_name(self) -> &'static str {
8167            match self {
8168                Self::Plain => "sleep",
8169                Self::Setsid => SETSID_HELPER,
8170            }
8171        }
8172
8173        /// A command that starts the descendant for `seconds` detached from
8174        /// the shell's output, records its pid in `child.pid` and returns once
8175        /// the child exists.
8176        fn script(self, exec_dir: &Path, seconds: u32) -> String {
8177            // The foreground `sleep` guard refuses a plain `sleep 0.3`, so
8178            // the settle wait is a `kill -0` check on the recorded pid.
8179            match self {
8180                Self::Plain => format!(
8181                    "sleep {seconds} > /dev/null 2>&1 & echo $! > child.pid; until kill -0 \"$(cat child.pid)\" 2>/dev/null; do :; done"
8182                ),
8183                Self::Setsid => format!(
8184                    "'{}' {seconds} > /dev/null 2>&1 & echo $! > child.pid; until kill -0 \"$(cat child.pid)\" 2>/dev/null; do :; done",
8185                    build_setsid_helper(exec_dir).display()
8186                ),
8187            }
8188        }
8189    }
8190
8191    /// The pid `child.pid` in `dir` holds, once the shell wrote it.
8192    #[cfg(unix)]
8193    async fn recorded_child_pid(dir: &Path) -> i32 {
8194        for _ in 0..250 {
8195            // The redirect creates the file before `echo` writes it, so an
8196            // empty read only means the pid is not there yet.
8197            if let Ok(text) = async_fs::read_to_string(dir.join("child.pid")).await
8198                && let Ok(pid) = text.trim().parse()
8199            {
8200                return pid;
8201            }
8202            async_io::Timer::after(Duration::from_millis(20)).await;
8203        }
8204        panic!("the descendant never recorded its pid");
8205    }
8206
8207    /// Whether `pid` is a live process.
8208    #[cfg(unix)]
8209    fn process_exists(pid: i32) -> bool {
8210        // SAFETY: signal 0 probes process existence.
8211        unsafe { libc::kill(pid, 0) == 0 }
8212    }
8213
8214    /// Fails unless `pid` is gone within a few seconds.
8215    #[cfg(unix)]
8216    async fn assert_process_gone(pid: i32, context: &str) {
8217        for _ in 0..250 {
8218            if !process_exists(pid) {
8219                return;
8220            }
8221            async_io::Timer::after(Duration::from_millis(20)).await;
8222        }
8223        panic!("process {pid} survived: {context}");
8224    }
8225
8226    #[cfg(unix)]
8227    async fn foreground_command_leaving_a_descendant_kills_it_and_alerts_once(
8228        descendant: Descendant,
8229    ) {
8230        let dir = tempfile::tempdir().expect("temp dir should be created");
8231        let tool = configured_test_terminal(
8232            dir.path(),
8233            Duration::from_secs(30),
8234            Duration::from_secs(60),
8235            Duration::from_secs(60),
8236        )
8237        .await;
8238        let receiver = tool.background_receiver();
8239
8240        let result = tool
8241            .call(
8242                terminal_args(
8243                    "leave a descendant",
8244                    &descendant.script(&exec_dir(&tool), 300),
8245                ),
8246                ToolContext::new(),
8247            )
8248            .await
8249            .expect("terminal call should succeed");
8250        let command = result.command().expect("terminal returns a command result");
8251        assert!(
8252            matches!(command.outcome, CommandOutcome::Exited { code: 0 }),
8253            "{:?}",
8254            command.outcome
8255        );
8256
8257        let child = recorded_child_pid(tool.working_dir()).await;
8258        assert_process_gone(
8259            child,
8260            &format!("{descendant:?} descendant of a foreground command"),
8261        )
8262        .await;
8263        let alerts = receiver.take_job_alerts();
8264        match alerts.as_slice() {
8265            [ShellEvent::DescendantsKilled(killed)] => {
8266                assert_ne!(killed.task_id(), "");
8267                assert!(killed.call().is_none(), "the call carried no identity");
8268                // The name is read after the freeze, once the child exec'd.
8269                assert_eq!(
8270                    killed
8271                        .processes
8272                        .iter()
8273                        .map(|process| i64::from(process.pid))
8274                        .collect::<Vec<_>>(),
8275                    [i64::from(child)]
8276                );
8277                assert_eq!(killed.processes[0].name, descendant.process_name());
8278            }
8279            other => panic!("expected one descendants-killed alert, got {other:?}"),
8280        }
8281        assert!(
8282            receiver.take_job_alerts().is_empty(),
8283            "the same event must not alert twice"
8284        );
8285    }
8286
8287    #[cfg(unix)]
8288    #[tokio::test(flavor = "multi_thread")]
8289    async fn foreground_command_leaving_a_descendant_kills_it_and_alerts_once_plain() {
8290        foreground_command_leaving_a_descendant_kills_it_and_alerts_once(Descendant::Plain).await;
8291    }
8292
8293    #[cfg(unix)]
8294    #[tokio::test(flavor = "multi_thread")]
8295    async fn foreground_command_leaving_a_setsid_descendant_kills_it_and_alerts_once() {
8296        foreground_command_leaving_a_descendant_kills_it_and_alerts_once(Descendant::Setsid).await;
8297    }
8298
8299    #[cfg(unix)]
8300    #[tokio::test(flavor = "multi_thread")]
8301    async fn foreground_background_jobs_joined_by_wait_run_without_an_alert() {
8302        let dir = tempfile::tempdir().expect("temp dir should be created");
8303        let tool = configured_test_terminal(
8304            dir.path(),
8305            Duration::from_secs(30),
8306            Duration::from_secs(60),
8307            Duration::from_secs(60),
8308        )
8309        .await;
8310        let receiver = tool.background_receiver();
8311
8312        let result = tool
8313            .call(
8314                terminal_args(
8315                    "run two jobs and join them",
8316                    "(sleep 1; echo one > one.txt) & (sleep 1; echo two > two.txt) & wait",
8317                ),
8318                ToolContext::new(),
8319            )
8320            .await
8321            .expect("terminal call should succeed");
8322        let command = result.command().expect("terminal returns a command result");
8323        assert!(
8324            matches!(command.outcome, CommandOutcome::Exited { code: 0 }),
8325            "{:?}",
8326            command.outcome
8327        );
8328        for name in ["one.txt", "two.txt"] {
8329            assert!(
8330                tool.working_dir().join(name).exists(),
8331                "{name} must be written before the command returns"
8332            );
8333        }
8334        assert!(
8335            receiver.take_job_alerts().is_empty(),
8336            "a joined job is no survivor"
8337        );
8338    }
8339
8340    /// Starts the background `script`, waits until its shell has exited with the
8341    /// descendant still alive, and returns the task id and the descendant's pid.
8342    #[cfg(unix)]
8343    async fn background_job_whose_shell_exited(
8344        tool: &Shell<executor_core::tokio::TokioGlobal>,
8345        script: &str,
8346        timeout: u64,
8347    ) -> (String, i32) {
8348        let job = tool
8349            .run_background(ShellArgs {
8350                background: true,
8351                timeout,
8352                ..terminal_args("background job", script)
8353            })
8354            .await
8355            .expect("terminal should start the background job");
8356        let task_id = job.task_id().to_owned();
8357        let child = recorded_child_pid(tool.working_dir()).await;
8358        // Past the shell's exit and several of the tree's checks.
8359        tokio::time::sleep(Duration::from_millis(1200)).await;
8360        assert!(
8361            process_exists(child),
8362            "the descendant must outlive the shell"
8363        );
8364        (task_id, child)
8365    }
8366
8367    #[cfg(unix)]
8368    async fn background_job_stays_running_until_its_descendant_exits(descendant: Descendant) {
8369        let dir = tempfile::tempdir().expect("temp dir should be created");
8370        let tool = configured_test_terminal(
8371            dir.path(),
8372            Duration::from_secs(30),
8373            Duration::from_secs(60),
8374            Duration::from_secs(60),
8375        )
8376        .await;
8377
8378        let (task_id, child) =
8379            background_job_whose_shell_exited(&tool, &descendant.script(&exec_dir(&tool), 3), 30)
8380                .await;
8381        let info = tool
8382            .job_registry()
8383            .get_by_task_id(&task_id)
8384            .await
8385            .expect("the job is registered");
8386        assert_eq!(
8387            info.status,
8388            JobStatus::Running,
8389            "the job runs while its descendant does"
8390        );
8391        assert!(
8392            tool.job_registry()
8393                .format_running_jobs()
8394                .await
8395                .contains(&task_id),
8396            "the running-jobs context lists the job"
8397        );
8398
8399        assert_process_gone(child, "the descendant's own exit").await;
8400        let receiver = tool.background_receiver();
8401        let completed = wait_for_completed_task(&receiver, &task_id).await;
8402        assert!(completed.result.is_ok(), "{completed:?}");
8403        let info = tool
8404            .job_registry()
8405            .get_by_task_id(&task_id)
8406            .await
8407            .expect("the finished job stays in the registry");
8408        assert_eq!(
8409            info.status,
8410            JobStatus::Completed {
8411                exit_code: 0,
8412                delivery: crate::Delivery::Pending
8413            }
8414        );
8415        assert!(
8416            tool.job_registry().format_running_jobs().await.is_empty(),
8417            "a finished job is no longer listed"
8418        );
8419    }
8420
8421    #[cfg(unix)]
8422    #[tokio::test(flavor = "multi_thread")]
8423    async fn background_job_stays_running_until_its_plain_descendant_exits() {
8424        background_job_stays_running_until_its_descendant_exits(Descendant::Plain).await;
8425    }
8426
8427    #[cfg(unix)]
8428    #[tokio::test(flavor = "multi_thread")]
8429    async fn background_job_stays_running_until_its_setsid_descendant_exits() {
8430        background_job_stays_running_until_its_descendant_exits(Descendant::Setsid).await;
8431    }
8432
8433    #[cfg(unix)]
8434    async fn killing_a_background_job_kills_its_descendant(descendant: Descendant) {
8435        let dir = tempfile::tempdir().expect("temp dir should be created");
8436        let tool = configured_test_terminal(
8437            dir.path(),
8438            Duration::from_secs(30),
8439            Duration::from_secs(60),
8440            Duration::from_secs(60),
8441        )
8442        .await;
8443
8444        let (task_id, child) =
8445            background_job_whose_shell_exited(&tool, &descendant.script(&exec_dir(&tool), 300), 30)
8446                .await;
8447        assert!(
8448            tool.job_registry().kill_by_task_id(&task_id).await,
8449            "a job with a live descendant is killable"
8450        );
8451        assert_process_gone(
8452            child,
8453            &format!("terminal_kill of a job with a {descendant:?} descendant"),
8454        )
8455        .await;
8456        let info = tool
8457            .job_registry()
8458            .get_by_task_id(&task_id)
8459            .await
8460            .expect("the killed job stays in the registry");
8461        assert!(
8462            matches!(info.status, JobStatus::Killed { .. }),
8463            "{:?}",
8464            info.status
8465        );
8466    }
8467
8468    #[cfg(unix)]
8469    #[tokio::test(flavor = "multi_thread")]
8470    async fn killing_a_background_job_kills_its_plain_descendant() {
8471        killing_a_background_job_kills_its_descendant(Descendant::Plain).await;
8472    }
8473
8474    #[cfg(unix)]
8475    #[tokio::test(flavor = "multi_thread")]
8476    async fn killing_a_background_job_kills_its_setsid_descendant() {
8477        killing_a_background_job_kills_its_descendant(Descendant::Setsid).await;
8478    }
8479
8480    #[cfg(unix)]
8481    #[tokio::test(flavor = "multi_thread")]
8482    async fn background_timeout_kills_a_descendant_that_outlived_the_shell() {
8483        let dir = tempfile::tempdir().expect("temp dir should be created");
8484        let tool = configured_test_terminal(
8485            dir.path(),
8486            Duration::from_secs(30),
8487            Duration::from_secs(60),
8488            Duration::from_secs(60),
8489        )
8490        .await;
8491
8492        // The timeout fires while the shell is long gone: the job is only its
8493        // descendant by then.
8494        let (task_id, child) = background_job_whose_shell_exited(
8495            &tool,
8496            &Descendant::Setsid.script(&exec_dir(&tool), 300),
8497            2,
8498        )
8499        .await;
8500        assert_process_gone(child, "the timeout of a job whose shell exited").await;
8501        let receiver = tool.background_receiver();
8502        let completed = wait_for_completed_task(&receiver, &task_id).await;
8503        let info = tool
8504            .job_registry()
8505            .get_by_task_id(&task_id)
8506            .await
8507            .expect("the finished job stays in the registry");
8508        assert!(
8509            matches!(
8510                info.status,
8511                JobStatus::Killed {
8512                    cause: crate::KillCause::Timeout(_),
8513                    delivery: crate::Delivery::Pending
8514                }
8515            ),
8516            "{completed:?}"
8517        );
8518    }
8519
8520    #[cfg(unix)]
8521    #[tokio::test(flavor = "multi_thread")]
8522    async fn a_subagents_cleanup_kills_a_descendant_that_outlived_the_shell() {
8523        let dir = tempfile::tempdir().expect("temp dir should be created");
8524        let tool = configured_test_terminal(
8525            dir.path(),
8526            Duration::from_secs(30),
8527            Duration::from_secs(60),
8528            Duration::from_secs(60),
8529        )
8530        .await;
8531
8532        let (_task_id, child) = background_job_whose_shell_exited(
8533            &tool,
8534            &Descendant::Plain.script(&exec_dir(&tool), 300),
8535            30,
8536        )
8537        .await;
8538        // What `kill_running_terminal_jobs` and the subagent run's cleanup call.
8539        assert_eq!(tool.job_registry().kill_running().await, 1);
8540        assert_process_gone(child, "the cleanup of a subagent's job").await;
8541    }
8542
8543    #[cfg(unix)]
8544    #[tokio::test(flavor = "multi_thread")]
8545    async fn terminal_rejects_timeout_above_cap_and_kills_at_timeout() {
8546        let dir = tempfile::tempdir().expect("temp dir should be created");
8547        let tool = configured_test_terminal(
8548            dir.path(),
8549            Duration::from_secs(10),
8550            Duration::from_secs(2),
8551            Duration::from_secs(60),
8552        )
8553        .await;
8554        let background_receiver = tool.background_receiver();
8555        let args = |timeout: u64| ShellArgs {
8556            description: "sleep in the background".to_string(),
8557            script: "sleep 30".to_string(),
8558            interpreter: Interpreter::Shell,
8559            sandbox: SandboxMode::Sandboxed,
8560            location: None,
8561            resolution: MediaResolution::Auto,
8562            max_lines: Some(50),
8563            raw: false,
8564            timeout,
8565            background: true,
8566        };
8567
8568        assert!(
8569            tool.call(args(3), ToolContext::new()).await.is_err(),
8570            "a timeout above the cap must be rejected"
8571        );
8572
8573        let result = tool
8574            .call(args(1), ToolContext::new())
8575            .await
8576            .expect("a timeout within the cap should start the job");
8577        let rendered = render_terminal_result(&result);
8578        assert!(
8579            rendered.contains("Started in background as task '"),
8580            "{rendered}"
8581        );
8582        let task_id = started_task_id(&background_receiver);
8583
8584        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
8585        let info = tool
8586            .job_registry()
8587            .get_by_task_id(&task_id)
8588            .await
8589            .expect("the finished job stays in the registry");
8590        assert!(
8591            matches!(
8592                info.status,
8593                JobStatus::Killed {
8594                    cause: crate::KillCause::Timeout(_),
8595                    delivery: crate::Delivery::Pending
8596                }
8597            ),
8598            "the job should have been killed at its timeout: {completed:?}"
8599        );
8600    }
8601
8602    #[test]
8603    fn the_timeout_notice_states_both_utc_times() {
8604        let kill = TimeoutKill {
8605            timeout: Duration::from_secs(90),
8606            started: "2026-11-04T12:00:00Z".parse().expect("valid timestamp"),
8607            killed: "2026-11-04T12:01:31Z".parse().expect("valid timestamp"),
8608        };
8609        assert_eq!(
8610            TestWording.command_killed(&crate::CommandKilled::TimedOut(&kill)),
8611            "Its 90s timeout bound passed; it started at 2026-11-04 12:00:00 UTC \
8612             and was killed at 2026-11-04 12:01:31 UTC."
8613        );
8614    }
8615
8616    #[cfg(unix)]
8617    fn spinning_args(timeout: u64, background: bool) -> ShellArgs {
8618        ShellArgs {
8619            description: "spin past the timeout".to_string(),
8620            script: if background {
8621                "while :; do sleep 0.1; done"
8622            } else {
8623                // A foreground `sleep` is refused; a niced spin leaves the
8624                // other tests their CPU.
8625                "nice -n 19 sh -c 'while :; do :; done'"
8626            }
8627            .to_string(),
8628            interpreter: Interpreter::Shell,
8629            sandbox: SandboxMode::Sandboxed,
8630            location: None,
8631            resolution: MediaResolution::Auto,
8632            max_lines: Some(50),
8633            raw: false,
8634            timeout,
8635            background,
8636        }
8637    }
8638
8639    #[cfg(unix)]
8640    #[tokio::test(flavor = "multi_thread")]
8641    async fn a_background_job_killed_at_its_timeout_reports_its_utc_times() {
8642        let dir = tempfile::tempdir().expect("temp dir should be created");
8643        let tool = configured_test_terminal(
8644            dir.path(),
8645            Duration::from_secs(10),
8646            Duration::from_secs(60),
8647            Duration::from_secs(60),
8648        )
8649        .await;
8650        let background_receiver = tool.background_receiver();
8651        tool.call(spinning_args(1, true), ToolContext::new())
8652            .await
8653            .expect("the job starts");
8654        let task_id = started_task_id(&background_receiver);
8655        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
8656
8657        let kill = completed
8658            .timeout_kill
8659            .expect("a job killed at its timeout carries the times");
8660        assert_eq!(
8661            completed.info.status.kill_cause(),
8662            Some(crate::KillCause::Timeout(kill))
8663        );
8664        assert_eq!(kill.timeout, Duration::from_secs(1));
8665        assert!(
8666            kill.killed.duration_since(kill.started).as_secs_f64() >= 1.0,
8667            "{kill:?}"
8668        );
8669        assert!(
8670            kill.killed.duration_since(kill.started).as_secs() < 10,
8671            "{kill:?}"
8672        );
8673        assert!(
8674            TestWording
8675                .command_killed(&crate::CommandKilled::TimedOut(&kill))
8676                .starts_with("Its 1s timeout bound passed; it started at ")
8677        );
8678    }
8679
8680    #[cfg(unix)]
8681    #[tokio::test(flavor = "multi_thread")]
8682    async fn a_job_killed_by_hand_is_not_a_timeout_kill() {
8683        let dir = tempfile::tempdir().expect("temp dir should be created");
8684        let tool = configured_test_terminal(
8685            dir.path(),
8686            Duration::from_secs(10),
8687            Duration::from_secs(60),
8688            Duration::from_secs(60),
8689        )
8690        .await;
8691        let background_receiver = tool.background_receiver();
8692        tool.call(spinning_args(30, true), ToolContext::new())
8693            .await
8694            .expect("the job starts");
8695        let task_id = started_task_id(&background_receiver);
8696        assert!(tool.job_registry().kill_by_task_id(&task_id).await);
8697        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
8698        assert_eq!(
8699            completed.info.status.kill_cause(),
8700            Some(crate::KillCause::User)
8701        );
8702        assert_eq!(completed.timeout_kill, None);
8703    }
8704
8705    #[cfg(unix)]
8706    #[tokio::test(flavor = "multi_thread")]
8707    async fn a_foreground_command_killed_at_its_timeout_reports_its_utc_times() {
8708        let dir = tempfile::tempdir().expect("temp dir should be created");
8709        let tool = configured_test_terminal(
8710            dir.path(),
8711            Duration::from_secs(20),
8712            Duration::from_secs(60),
8713            Duration::from_secs(60),
8714        )
8715        .await;
8716        let before = jiff::Timestamp::now();
8717        let result = tool
8718            .call(spinning_args(1, false), ToolContext::new())
8719            .await
8720            .expect("a killed command still returns a result");
8721        let rendered = render_terminal_result(&result);
8722        let utc = |marker: &str| {
8723            let text = rendered
8724                .split(marker)
8725                .nth(1)
8726                .and_then(|rest| rest.split(" UTC").next())
8727                .unwrap_or_else(|| panic!("{marker:?} missing: {rendered}"));
8728            jiff::civil::DateTime::strptime("%Y-%m-%d %H:%M:%S", text)
8729                .expect("a UTC date and time")
8730                .to_zoned(jiff::tz::TimeZone::UTC)
8731                .expect("UTC has no gaps")
8732                .timestamp()
8733        };
8734        assert!(
8735            rendered.contains("Its 1s timeout bound passed; it started at "),
8736            "{rendered}"
8737        );
8738        let started = utc("it started at ");
8739        let killed = utc("was killed at ");
8740        assert!(started.as_second() >= before.as_second(), "{rendered}");
8741        assert!(killed.as_second() - started.as_second() >= 1, "{rendered}");
8742        assert!(killed.as_second() - started.as_second() < 10, "{rendered}");
8743    }
8744
8745    #[cfg(unix)]
8746    #[tokio::test(flavor = "multi_thread")]
8747    async fn background_job_past_the_alert_threshold_yields_one_alert() {
8748        let dir = tempfile::tempdir().expect("temp dir should be created");
8749        let tool = configured_test_terminal(
8750            dir.path(),
8751            Duration::from_secs(10),
8752            Duration::from_secs(60),
8753            Duration::from_millis(300),
8754        )
8755        .await;
8756        let background_receiver = tool.background_receiver();
8757
8758        let _result = tool
8759            .run_background(ShellArgs {
8760                description: "sleep in the background".to_string(),
8761                script: "sleep 30".to_string(),
8762                interpreter: Interpreter::Shell,
8763                sandbox: SandboxMode::Sandboxed,
8764                location: None,
8765                resolution: MediaResolution::Auto,
8766                max_lines: Some(50),
8767                raw: false,
8768                timeout: 30,
8769                background: true,
8770            })
8771            .await
8772            .expect("terminal should start the job");
8773        let task_id = started_task_id(&background_receiver);
8774
8775        let deadline = std::time::Instant::now() + Duration::from_secs(10);
8776        let alerts = loop {
8777            let alerts = background_receiver.take_job_alerts();
8778            if !alerts.is_empty() {
8779                break alerts;
8780            }
8781            assert!(
8782                std::time::Instant::now() < deadline,
8783                "long-running alert did not fire"
8784            );
8785            tokio::time::sleep(Duration::from_millis(50)).await;
8786        };
8787        assert_eq!(alerts.len(), 1);
8788        assert!(
8789            matches!(&alerts[0], ShellEvent::LongRunning(job) if job.task_id == task_id),
8790            "expected the long-running alert for the job: {alerts:?}"
8791        );
8792        assert!(
8793            background_receiver.take_job_alerts().is_empty(),
8794            "the same job must not alert twice"
8795        );
8796
8797        assert!(
8798            tool.job_registry().kill_by_task_id(&task_id).await,
8799            "test cleanup should kill the job"
8800        );
8801    }
8802
8803    /// A terminal tool with `priority` applied.
8804    #[cfg(unix)]
8805    async fn prioritized_terminal_tool(
8806        dir: &Path,
8807        priority: ProcessPriority,
8808    ) -> Shell<executor_core::tokio::TokioGlobal> {
8809        let sandbox = Sandbox::new(
8810            Backend::Host {
8811                heel: crate::test_heel::binary().await.expect("a test heel"),
8812            },
8813            executor_core::tokio::TokioGlobal,
8814            dir,
8815        )
8816        .with_priority(priority);
8817        Shell::new_exact_on(
8818            sandbox,
8819            executor_core::tokio::TokioGlobal,
8820            crate::limits::fixture::limits(),
8821            crate::output_policy::fixture::policy(),
8822            TestWording::any(),
8823            crate::test_wording::job_tools(),
8824        )
8825        .await
8826        .expect("terminal tool should initialize")
8827    }
8828
8829    /// A probe script made only of `sh` builtins: a strict sandbox executes
8830    /// nothing but the launched shell, the prepared tools and granted paths,
8831    /// so it reports its own `$$` into `pid` and waits for the host's `go`
8832    /// marker instead of running `nice`.
8833    #[cfg(unix)]
8834    fn pid_probe_args() -> ShellArgs {
8835        ShellArgs {
8836            description: "report the process pid and wait".to_string(),
8837            script: concat!(
8838                "printf '%s\\n' $$ > \"$PWD/pid\"; ",
8839                "while [ ! -f \"$PWD/go\" ]; do :; done"
8840            )
8841            .to_string(),
8842            interpreter: Interpreter::Shell,
8843            sandbox: SandboxMode::Sandboxed,
8844            location: None,
8845            resolution: MediaResolution::Auto,
8846            max_lines: Some(50),
8847            raw: false,
8848            timeout: 30,
8849            background: false,
8850        }
8851    }
8852
8853    /// Reads the pid the sandboxed probe wrote, retrying while the sandbox
8854    /// starts.
8855    #[cfg(unix)]
8856    async fn probe_pid(dir: &Path) -> u32 {
8857        let path = dir.join("pid");
8858        for _ in 0..150 {
8859            if let Ok(text) = std::fs::read_to_string(&path)
8860                && let Ok(pid) = text.trim().parse()
8861            {
8862                return pid;
8863            }
8864            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
8865        }
8866        panic!("the sandboxed probe did not write {}", path.display());
8867    }
8868
8869    /// The `pid`'s nice level, read from the host while the probe is alive.
8870    #[cfg(unix)]
8871    fn probe_nice(pid: u32) -> i64 {
8872        // SAFETY: queries the kernel for the named process's priority.
8873        i64::from(unsafe { libc::getpriority(libc::PRIO_PROCESS as _, pid as _) })
8874    }
8875
8876    /// Releases the sandboxed probe by creating the `go` marker it polls for.
8877    #[cfg(unix)]
8878    fn release_probe(dir: &Path) {
8879        std::fs::File::create(dir.join("go")).expect("create the probe marker");
8880    }
8881
8882    #[cfg(unix)]
8883    #[tokio::test]
8884    async fn foreground_command_runs_with_configured_nice() {
8885        let dir = tempfile::tempdir().expect("temp dir should be created");
8886        let tool = prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
8887
8888        let call = tool.call(pid_probe_args(), ToolContext::new());
8889        let probe = async {
8890            let pid = probe_pid(dir.path()).await;
8891            assert_eq!(
8892                probe_nice(pid),
8893                expected_lowered_nice(10),
8894                "foreground command should run at the configured nice level"
8895            );
8896            release_probe(dir.path());
8897        };
8898        let (result, ()) = futures::join!(call, probe);
8899        let rendered = render_terminal_result(&result.expect("terminal call should succeed"));
8900        assert!(!rendered.contains("Exit code:"), "{rendered}");
8901    }
8902
8903    #[cfg(unix)]
8904    #[tokio::test]
8905    async fn persistent_session_runs_with_configured_nice() {
8906        let dir = tempfile::tempdir().expect("temp dir should be created");
8907        let tool = prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
8908        let background_receiver = tool.background_receiver();
8909        let input_tool = input_tool(tool.jobs());
8910
8911        // `exec` keeps `$$` — the pid the probe wrote — on the interactive
8912        // shell the session then drives.
8913        let result = tool
8914            .call(
8915                ShellArgs {
8916                    description: "start a persistent shell".to_string(),
8917                    script: "printf '%s\\n' $$ > \"$PWD/pid\"; exec sh".to_string(),
8918                    interpreter: Interpreter::Shell,
8919                    sandbox: SandboxMode::Sandboxed,
8920                    location: None,
8921                    resolution: MediaResolution::Auto,
8922                    max_lines: Some(50),
8923                    raw: false,
8924                    timeout: 30,
8925                    background: true,
8926                },
8927                ToolContext::new(),
8928            )
8929            .await
8930            .expect("terminal call should succeed");
8931        let rendered = render_terminal_result(&result);
8932        assert!(
8933            rendered.contains("Started in background as task '"),
8934            "{rendered}"
8935        );
8936        let task_id = started_task_id(&tool.background_receiver());
8937
8938        let pid = probe_pid(dir.path()).await;
8939        assert_eq!(
8940            probe_nice(pid),
8941            expected_lowered_nice(10),
8942            "persistent session should run at the configured nice level"
8943        );
8944
8945        input_tool
8946            .call(
8947                JobInputArgs {
8948                    task_id: task_id.clone(),
8949                    input: "exit".to_string(),
8950                    append_newline: true,
8951                },
8952                ToolContext::new(),
8953            )
8954            .await
8955            .expect("terminal_input should succeed");
8956
8957        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
8958        let terminal_result = completed
8959            .result
8960            .expect("persistent shell should exit cleanly after input");
8961        assert_eq!(terminal_result.exit_code, 0);
8962    }
8963
8964    #[cfg(unix)]
8965    #[tokio::test]
8966    async fn background_job_runs_with_configured_nice() {
8967        let dir = tempfile::tempdir().expect("temp dir should be created");
8968        let tool = prioritized_terminal_tool(dir.path(), test_nice_priority()).await;
8969        let background_receiver = tool.background_receiver();
8970
8971        let result = tool
8972            .call(
8973                ShellArgs {
8974                    background: true,
8975                    ..pid_probe_args()
8976                },
8977                ToolContext::new(),
8978            )
8979            .await
8980            .expect("terminal call should succeed");
8981        let rendered = render_terminal_result(&result);
8982        let mut started = tool.background_receiver().take_started();
8983        assert_eq!(started.len(), 1, "expected one started-task event");
8984        let started = started.remove(0);
8985        let task_id = started.task_id;
8986        assert_eq!(
8987            rendered,
8988            format!(
8989                "Started in background as task '{task_id}'; output is being written to {} (absolute path: {}).\n",
8990                started.output_file.url, started.output_file.path
8991            )
8992        );
8993        assert_eq!(
8994            result.command().map(|command| &command.outcome),
8995            Some(&CommandOutcome::Running {
8996                task_id: task_id.clone(),
8997                output: started.output_file.clone(),
8998            })
8999        );
9000
9001        let pid = probe_pid(dir.path()).await;
9002        assert_eq!(
9003            probe_nice(pid),
9004            expected_lowered_nice(10),
9005            "background job should run at the configured nice level"
9006        );
9007        release_probe(dir.path());
9008
9009        let completed = wait_for_completed_task(&background_receiver, &task_id).await;
9010        let terminal_result = completed
9011            .result
9012            .expect("background job should complete successfully");
9013        assert_eq!(terminal_result.exit_code, 0);
9014    }
9015
9016    #[test]
9017    fn wrap_container_script_applies_configured_priority() {
9018        let priority = ProcessPriority::new(
9019            CpuPriority::Nice(NiceLevel::new(5).expect("nice level 5 is in range")),
9020            IoPriority::Background,
9021        );
9022        let tools_dir = container_tools_dir();
9023        let executable = format!("--executable {}", shell_escape(tools_dir.as_str()));
9024        let setup = crate::spawn::container_ipc::exec_setup(
9025            &ipc_commands(&["websearch"]),
9026            "host.docker.internal",
9027            9000,
9028        )
9029        .expect("ipc setup");
9030        let wrapped = wrap_container_script(
9031            "echo ok",
9032            Some(&setup),
9033            priority,
9034            &tools_dir,
9035            "/workspace",
9036            None,
9037        )
9038        .expect("wrap script");
9039        assert!(wrapped.contains(
9040            "\"$AITHER_HEEL_BIN\" run --isolation permissive --working-dir '/workspace' \
9041             --env-passthrough PATH --env-passthrough HOME"
9042        ));
9043        assert!(wrapped.contains(&executable));
9044        assert!(wrapped.contains(
9045            "--ipc-endpoint 'tcp://host.docker.internal:9000' --grant \"$AITHER_IPC_DIR=rx\" \
9046             --nice 5 --io-priority background -- sh -c 'echo ok'"
9047        ));
9048        assert!(wrapped.contains("HEEL_IPC_ENDPOINT"));
9049
9050        let bare = wrap_container_script("echo ok", None, priority, &tools_dir, "/workspace", None)
9051            .expect("wrap script");
9052        assert!(bare.contains("AITHER_HEEL_BIN=\"$(command -v heel || true)\""));
9053        assert!(bare.contains(
9054            "\"$AITHER_HEEL_BIN\" run --isolation permissive --working-dir '/workspace' \
9055             --env-passthrough PATH --env-passthrough HOME"
9056        ));
9057        assert!(bare.contains(&executable));
9058        assert!(bare.contains("--nice 5 --io-priority background -- sh -c 'echo ok'"));
9059
9060        let normal = wrap_container_script(
9061            "echo ok",
9062            None,
9063            ProcessPriority::default(),
9064            &tools_dir,
9065            "/workspace",
9066            None,
9067        )
9068        .expect("wrap script");
9069        assert_eq!(normal, "echo ok");
9070    }
9071
9072    #[test]
9073    fn wrap_container_script_prioritizes_each_half_independently() {
9074        let io_only = wrap_container_script(
9075            "echo ok",
9076            None,
9077            ProcessPriority::new(CpuPriority::Normal, IoPriority::Utility),
9078            &container_tools_dir(),
9079            "/workspace",
9080            None,
9081        )
9082        .expect("wrap script");
9083        assert!(io_only.contains(" --io-priority utility -- sh -c 'echo ok'"));
9084        assert!(!io_only.contains("--nice"));
9085
9086        let cpu_only = wrap_container_script(
9087            "echo ok",
9088            None,
9089            ProcessPriority::new(
9090                CpuPriority::Nice(NiceLevel::new(9).expect("nice level 9 is in range")),
9091                IoPriority::Normal,
9092            ),
9093            &container_tools_dir(),
9094            "/workspace",
9095            None,
9096        )
9097        .expect("wrap script");
9098        assert!(cpu_only.contains(" --nice 9 -- sh -c 'echo ok'"));
9099        assert!(!cpu_only.contains("--io-priority"));
9100    }
9101
9102    /// An IPC command that answers with the marker it was invoked with, so a
9103    /// request that actually reached the live handler is unmistakable.
9104    struct ProbeEchoCommand;
9105
9106    #[derive(Debug, Deserialize)]
9107    struct ProbeEchoArgs {
9108        marker: String,
9109    }
9110
9111    impl heel::IpcCommand for ProbeEchoCommand {
9112        fn name(&self) -> Cow<'static, str> {
9113            "probe_echo".into()
9114        }
9115
9116        type Args = ProbeEchoArgs;
9117        type Response = String;
9118
9119        fn handle(
9120            &self,
9121            args: Self::Args,
9122            _context: heel::IpcContext,
9123        ) -> impl std::future::Future<Output = Result<Self::Response, heel::IpcError>> + Send
9124        {
9125            std::future::ready(Ok(format!("marker: {}", args.marker)))
9126        }
9127    }
9128
9129    /// A container executor for runtimes whose container is never reached.
9130    struct UnreachableContainerExec;
9131
9132    impl crate::ContainerExec for UnreachableContainerExec {
9133        fn exec(
9134            &self,
9135            _container_id: &str,
9136            _script: &str,
9137            _working_dir: &str,
9138            _kill_rx: Receiver<()>,
9139            _stdin_rx: Receiver<Vec<u8>>,
9140            _lifetime: ExecLifetime,
9141        ) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
9142        {
9143            std::future::ready(Err("the container is never executed in".to_string()))
9144        }
9145
9146        fn exec_streamed(
9147            &self,
9148            _container_id: &str,
9149            _script: &str,
9150            _working_dir: &str,
9151            _kill_rx: Receiver<()>,
9152            _stdin_rx: Receiver<Vec<u8>>,
9153            _stdout: Sender<Vec<u8>>,
9154            _lifetime: ExecLifetime,
9155        ) -> impl std::future::Future<Output = Result<crate::ContainerExecOutcome, String>> + Send
9156        {
9157            std::future::ready(Err("the container is never executed in".to_string()))
9158        }
9159    }
9160
9161    /// Host side of the container IPC transport on every platform: a client
9162    /// speaking the bridge's framing over loopback TCP reaches the embedder's
9163    /// live handler and gets its answer back.
9164    #[tokio::test(flavor = "multi_thread")]
9165    async fn container_ipc_bridge_round_trips_a_command_over_tcp() {
9166        use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
9167        let router = heel::IpcRouter::new().register(ProbeEchoCommand);
9168        let loopback = std::net::IpAddr::from([127, 0, 0, 1]);
9169        let runtime = crate::ContainerShellRuntime::new(
9170            "aither-test-ipc",
9171            crate::HostRoute::new("host.docker.internal", loopback).expect("loopback is routable"),
9172            crate::AnyContainerExec::new(Arc::new(UnreachableContainerExec)),
9173        );
9174        let executor = Arc::new(executor_core::AnyExecutor::new(
9175            executor_core::tokio::TokioGlobal,
9176        ));
9177        let bridge = crate::spawn::container_ipc::ContainerIpc::serve(&executor, router, &runtime)
9178            .expect("bridge should start on loopback");
9179
9180        let mut stream = async_io::Async::<std::net::TcpStream>::connect(
9181            std::net::SocketAddr::new(loopback, bridge.port()),
9182        )
9183        .await
9184        .expect("client should connect to the bridge");
9185
9186        let params = rmp_serde::to_vec_named(&serde_json::json!({ "marker": "pong" }))
9187            .expect("params should encode");
9188        let request = heel::ipc::IpcRequest::encode("probe_echo", Path::new("/workspace"), &params)
9189            .expect("request should encode");
9190        stream
9191            .write_all(&request)
9192            .await
9193            .expect("request frame should be written");
9194
9195        let mut length_bytes = [0_u8; 4];
9196        stream
9197            .read_exact(&mut length_bytes)
9198            .await
9199            .expect("response length should be read");
9200        let mut response = vec![0_u8; u32::from_be_bytes(length_bytes) as usize];
9201        stream
9202            .read_exact(&mut response)
9203            .await
9204            .expect("response body should be read");
9205
9206        let (success, payload) = response
9207            .split_first()
9208            .expect("response carries a success flag");
9209        assert_eq!(*success, 1, "bridge should report success");
9210        let rendered: String =
9211            rmp_serde::from_slice(payload).expect("response should decode as msgpack");
9212        assert_eq!(
9213            rendered, "marker: pong",
9214            "probe_echo should answer with the CLI-rendered payload, as `heel ipc` prints it"
9215        );
9216
9217        drop(stream);
9218        bridge.stop().await;
9219    }
9220
9221    // ---- subagent authority -------------------------------------------------
9222
9223    type ConfiguredTestTool = Shell<executor_core::tokio::TokioGlobal>;
9224
9225    /// Runs `script` in `tool`'s sandbox and returns its exit code.
9226    #[cfg(unix)]
9227    async fn exit_code_of(tool: &ConfiguredTestTool, script: &str) -> i32 {
9228        let result = tool
9229            .call(terminal_args("authority probe", script), ToolContext::new())
9230            .await
9231            .expect("terminal call should succeed");
9232        match result.command().map(|command| &command.outcome) {
9233            Some(CommandOutcome::Exited { code }) => *code,
9234            other => panic!("the probe should run to completion, got {other:?}"),
9235        }
9236    }
9237
9238    #[cfg(unix)]
9239    async fn authority_terminal(dir: &Path) -> ConfiguredTestTool {
9240        configured_test_terminal(
9241            dir,
9242            Duration::from_secs(30),
9243            Duration::from_secs(60),
9244            Duration::from_secs(600),
9245        )
9246        .await
9247    }
9248
9249    /// An environment source that names the launch it is asked about.
9250    #[derive(Debug)]
9251    struct LaunchEnv;
9252
9253    impl EnvSource for LaunchEnv {
9254        fn env(&self, launch: &crate::LaunchInfo) -> Vec<(String, String)> {
9255            vec![
9256                (
9257                    "PROBE_TASK".to_string(),
9258                    launch.task_id.clone().unwrap_or_default(),
9259                ),
9260                (
9261                    "PROBE_CALL".to_string(),
9262                    launch
9263                        .call
9264                        .as_ref()
9265                        .map(|call| call.call().to_string())
9266                        .unwrap_or_default(),
9267                ),
9268                ("PROBE_MODE".to_string(), format!("{:?}", launch.mode)),
9269            ]
9270        }
9271    }
9272
9273    /// The environment source is told which job, call and mode the process
9274    /// it supplies is launched for.
9275    #[cfg(unix)]
9276    #[tokio::test(flavor = "multi_thread")]
9277    async fn the_env_source_is_told_the_launch_it_supplies() {
9278        use aither_core::llm::{AgentIdentity, ToolCallId};
9279        let dir = tempfile::tempdir().expect("temp dir should be created");
9280        let heel = crate::test_heel::binary().await.expect("a test heel");
9281        let sandbox = Sandbox::new(
9282            Backend::Host { heel },
9283            executor_core::tokio::TokioGlobal,
9284            dir.path(),
9285        )
9286        .with_env_source(LaunchEnv);
9287        let tool = Shell::new_exact_on(
9288            sandbox,
9289            executor_core::tokio::TokioGlobal,
9290            crate::limits::fixture::limits(),
9291            crate::output_policy::fixture::policy(),
9292            TestWording::any(),
9293            crate::test_wording::job_tools(),
9294        )
9295        .await
9296        .expect("terminal tool should initialize");
9297        let identity = CallIdentity::new(ToolCallId::new("call_probe"), AgentIdentity::Main);
9298
9299        let result = tool
9300            .call(
9301                terminal_args(
9302                    "print the launch",
9303                    "printenv PROBE_CALL; printenv PROBE_MODE",
9304                ),
9305                ToolContext::new().with_identity(identity),
9306            )
9307            .await
9308            .expect("terminal call should succeed");
9309        let text = render_terminal_result(&result);
9310        assert!(text.contains("call_probe\nSandboxed"), "{text}");
9311    }
9312
9313    /// A command that reports one line of progress into the job that runs it.
9314    struct ProgressCommand {
9315        jobs: crate::Jobs,
9316        task_id: String,
9317    }
9318
9319    #[derive(Debug, Deserialize)]
9320    struct NoArgs {}
9321
9322    impl heel::IpcCommand for ProgressCommand {
9323        fn name(&self) -> Cow<'static, str> {
9324            "progress".into()
9325        }
9326
9327        type Args = NoArgs;
9328        type Response = String;
9329
9330        fn handle(
9331            &self,
9332            _args: Self::Args,
9333            _context: heel::IpcContext,
9334        ) -> impl std::future::Future<Output = Result<Self::Response, heel::IpcError>> + Send
9335        {
9336            let jobs = self.jobs.clone();
9337            let task_id = self.task_id.clone();
9338            async move {
9339                let appender = jobs
9340                    .output_appender(&task_id)
9341                    .await
9342                    .expect("the job is held before its process can call");
9343                assert_eq!(
9344                    appender.append(b"working\n").await,
9345                    crate::AppendOutcome::Appended
9346                );
9347                Ok("done".to_owned())
9348            }
9349        }
9350    }
9351
9352    struct ProgressProvider(crate::Jobs);
9353
9354    impl crate::IpcProvider for ProgressProvider {
9355        fn router(&self, launch: &crate::LaunchInfo) -> Option<heel::IpcRouter> {
9356            Some(heel::IpcRouter::new().register(ProgressCommand {
9357                jobs: self.0.clone(),
9358                task_id: launch.task_id.clone().expect("a shell names its launches"),
9359            }))
9360        }
9361    }
9362
9363    /// A script that calls an embedder's command at its first instruction
9364    /// already finds its job: the appender is handed out and its line lands
9365    /// in the job's output, between the script's own.
9366    #[cfg(unix)]
9367    #[tokio::test(flavor = "multi_thread")]
9368    async fn a_command_called_at_once_appends_to_the_job_that_ran_it() {
9369        let dir = tempfile::tempdir().expect("temp dir should be created");
9370        let mut tool = fresh_terminal(dir.path()).await;
9371        tool.ipc = Some(crate::AnyIpcProvider::new(ProgressProvider(tool.jobs())));
9372
9373        let result = tool
9374            .call(
9375                terminal_args("report progress", "progress >/dev/null; echo end"),
9376                ToolContext::new(),
9377            )
9378            .await
9379            .expect("terminal call should succeed");
9380        let text = render_terminal_result(&result);
9381        assert!(text.contains("working\nend"), "{text}");
9382    }
9383
9384    /// A script the sandboxed command writes into its working directory and
9385    /// chmods executes — writable space also carries EXEC, and nothing still
9386    /// holds the file open for writing when the shell runs it.
9387    #[cfg(unix)]
9388    #[tokio::test(flavor = "multi_thread")]
9389    async fn a_script_written_into_the_working_dir_executes() {
9390        let dir = tempfile::tempdir().expect("temp dir should be created");
9391        let tool = authority_terminal(dir.path()).await;
9392        let result = tool
9393            .call(
9394                terminal_args(
9395                    "write and run a script",
9396                    "echo '#!/bin/sh\necho ok' > run.sh && chmod +x run.sh && ./run.sh",
9397                ),
9398                ToolContext::new(),
9399            )
9400            .await
9401            .expect("terminal call should succeed");
9402        let command = result.command().expect("the script runs as a command");
9403        // The shell names the errno of a failed exec on stderr: `Text file
9404        // busy` is a write descriptor still open at `execve`, `Permission
9405        // denied` the sandbox refusing EXEC.
9406        let stderr = command
9407            .stderr
9408            .as_ref()
9409            .and_then(output_text)
9410            .unwrap_or_default();
9411        assert_eq!(
9412            command.outcome,
9413            CommandOutcome::Exited { code: 0 },
9414            "a script the command writes and chmods runs; stderr: {stderr}"
9415        );
9416        assert_eq!(
9417            output_text(&command.stdout).map(str::trim),
9418            Some("ok"),
9419            "stderr: {stderr}"
9420        );
9421    }
9422
9423    /// Launches a subagent of `parent` the way its launcher does, with a
9424    /// launch history of its own.
9425    async fn launch(
9426        parent: &ConfiguredTestTool,
9427        grant: SubagentGrant,
9428    ) -> Result<ConfiguredTestTool, SubagentGrantError> {
9429        let resolved = parent
9430            .resolve_launch(&mut LaunchHistory::default(), grant)
9431            .await?;
9432        parent
9433            .launch_resolved(resolved, None, "worker".to_owned())
9434            .await
9435    }
9436
9437    /// What a [`CloneSpaces`] was asked to prepare, as `(space, launcher,
9438    /// caller)`.
9439    #[cfg(unix)]
9440    type SeenSpace = (PathBuf, PathBuf, PathBuf);
9441
9442    /// How a test's [`SubagentSpaces`] fills a space.
9443    #[cfg(unix)]
9444    #[derive(Clone, Copy)]
9445    enum Filling {
9446        /// Clones the source repository into `repo` and names it.
9447        Clone,
9448        /// Writes a file into the space, then fails.
9449        Fail,
9450        /// Names the launcher's working directory as the working copy.
9451        Outside,
9452        /// Names the launcher's working directory as `TMPDIR`.
9453        EnvOutside,
9454    }
9455
9456    #[cfg(unix)]
9457    #[derive(Debug, thiserror::Error)]
9458    #[error("the session has no clone to give")]
9459    struct NoClone;
9460
9461    /// Prepares each space from `source`, the launcher's repository, and
9462    /// records what it was asked.
9463    #[cfg(unix)]
9464    struct CloneSpaces {
9465        source: PathBuf,
9466        filling: Filling,
9467        seen: async_channel::Sender<SeenSpace>,
9468    }
9469
9470    #[cfg(unix)]
9471    impl SubagentSpaces for CloneSpaces {
9472        type Error = NoClone;
9473
9474        async fn prepare(&self, run: RunSpace<'_>) -> Result<PreparedSpace, NoClone> {
9475            self.seen
9476                .send((
9477                    run.space.to_path_buf(),
9478                    run.launcher.to_path_buf(),
9479                    run.caller.to_path_buf(),
9480                ))
9481                .await
9482                .expect("the test records each space");
9483            let clone = run.space.join("repo");
9484            match self.filling {
9485                Filling::Clone => {
9486                    let (source, target) = (self.source.clone(), clone.clone());
9487                    blocking::unblock(move || {
9488                        crate::test_git::git(
9489                            &source,
9490                            &["clone", "-q", "--local", ".", target.to_str().unwrap()],
9491                        )
9492                    })
9493                    .await;
9494                    Ok(PreparedSpace::new().with_working_copy(clone))
9495                }
9496                Filling::Fail => {
9497                    async_fs::write(run.space.join("half-done"), "x")
9498                        .await
9499                        .unwrap();
9500                    Err(NoClone)
9501                }
9502                Filling::Outside => Ok(PreparedSpace::new().with_working_copy(run.launcher)),
9503                Filling::EnvOutside => {
9504                    Ok(PreparedSpace::new().with_env_dir("TMPDIR", run.launcher))
9505                }
9506            }
9507        }
9508    }
9509
9510    /// Gives every space a temporary directory as `TMPDIR`, and the first
9511    /// space it prepares also a cache directory as `AITHER_TEST_CACHE`.
9512    #[cfg(unix)]
9513    #[derive(Default)]
9514    struct EnvSpaces {
9515        prepared: std::sync::atomic::AtomicUsize,
9516    }
9517
9518    #[cfg(unix)]
9519    impl SubagentSpaces for EnvSpaces {
9520        type Error = std::io::Error;
9521
9522        async fn prepare(&self, run: RunSpace<'_>) -> Result<PreparedSpace, std::io::Error> {
9523            let tmp = run.space.join("tmp");
9524            async_fs::create_dir(&tmp).await?;
9525            let prepared = PreparedSpace::new().with_env_dir("TMPDIR", tmp);
9526            if self
9527                .prepared
9528                .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
9529                > 0
9530            {
9531                return Ok(prepared);
9532            }
9533            let cache = run.space.join("cache");
9534            async_fs::create_dir(&cache).await?;
9535            Ok(prepared.with_env_dir("AITHER_TEST_CACHE", cache))
9536        }
9537    }
9538
9539    /// A terminal in `dir` whose subagents' spaces `filling` prepares from
9540    /// the repository `dir/repo`, with the receiver of what it is asked.
9541    #[cfg(unix)]
9542    async fn spaced_terminal(
9543        dir: &Path,
9544        filling: Filling,
9545    ) -> (ConfiguredTestTool, async_channel::Receiver<SeenSpace>) {
9546        let source = dir.join("repo");
9547        std::fs::create_dir_all(&source).unwrap();
9548        crate::test_git::git(&source, &["init", "-q", "--initial-branch=main"]);
9549        crate::test_git::git(&source, &["commit", "-q", "--allow-empty", "-m", "base"]);
9550        let (seen, seen_rx) = async_channel::unbounded();
9551        let tool = configured_test_terminal(
9552            dir,
9553            Duration::from_secs(30),
9554            Duration::from_secs(60),
9555            Duration::from_secs(600),
9556        )
9557        .await
9558        .with_subagent_spaces(CloneSpaces {
9559            source,
9560            filling,
9561            seen,
9562        });
9563        (tool, seen_rx)
9564    }
9565
9566    /// A subagent works in the clone its launcher's spaces prepared: it
9567    /// commits there, cannot push into the launcher's repository, and its
9568    /// work reaches the launcher only when the launcher fetches it. The space
9569    /// outlives the subagent's terminal for that, and the launcher can
9570    /// remove it; a subagent's own launches are prepared by the same spaces.
9571    #[cfg(unix)]
9572    #[tokio::test(flavor = "multi_thread")]
9573    async fn a_subagent_works_in_the_clone_its_launchers_spaces_prepared() {
9574        let dir = tempfile::tempdir().expect("temp dir should be created");
9575        let root = dunce::canonicalize(dir.path()).unwrap();
9576        let (parent, seen) = spaced_terminal(dir.path(), Filling::Clone).await;
9577        let caller = dir.path().join("repo");
9578        let child = parent
9579            .subagent(SubagentGrant::new(), Some(&caller), "worker")
9580            .await
9581            .expect("the space is prepared");
9582
9583        let (space, launcher, asked_from) = seen.try_recv().expect("the spaces were asked");
9584        assert_eq!(&space, child.working_dir(), "the run works in the space");
9585        assert!(space.starts_with(root.join(SUBAGENT_SPACES_DIR)));
9586        assert_eq!(launcher, root, "the launcher is the main agent's terminal");
9587        assert_eq!(asked_from, caller, "the caller's directory is passed on");
9588        let clone = space.join("repo");
9589        assert_eq!(
9590            child.prepared_space().unwrap().working_copies(),
9591            std::slice::from_ref(&clone)
9592        );
9593        assert!(parent.prepared_space().is_none());
9594
9595        let git = "git -c user.name=t -c user.email=t@t -c commit.gpgSign=false";
9596        assert_eq!(
9597            exit_code_of(
9598                &child,
9599                &format!(
9600                    "cd '{}' && echo work > file && {git} add file && {git} commit -q -m work",
9601                    clone.display()
9602                ),
9603            )
9604            .await,
9605            0,
9606            "the subagent commits in its clone"
9607        );
9608        assert_ne!(
9609            exit_code_of(
9610                &child,
9611                &format!(
9612                    "cd '{}' && {git} push -q origin HEAD:refs/heads/pushed",
9613                    clone.display()
9614                ),
9615            )
9616            .await,
9617            0,
9618            "the launcher's repository is read-only to the subagent"
9619        );
9620        assert!(!crate::test_git::succeeds(
9621            &caller,
9622            &["rev-parse", "--verify", "-q", "refs/heads/pushed"]
9623        ));
9624
9625        let nested = child
9626            .subagent(SubagentGrant::new(), None, "worker")
9627            .await
9628            .expect("a nested space is prepared");
9629        let (nested_space, nested_launcher, nested_caller) = seen.try_recv().unwrap();
9630        assert_eq!(&nested_space, nested.working_dir());
9631        assert_eq!(nested_launcher, space, "a subagent launches from its space");
9632        assert_eq!(nested_caller, space, "the caller defaults to the launcher");
9633        drop((nested, child));
9634
9635        assert!(clone.join(".git").is_dir(), "the space outlives the run");
9636        assert_eq!(
9637            exit_code_of(
9638                &parent,
9639                &format!(
9640                    "cd repo && {git} fetch -q '{}' HEAD && {git} merge -q --ff-only FETCH_HEAD",
9641                    clone.display()
9642                ),
9643            )
9644            .await,
9645            0,
9646            "the launcher merges the run's work"
9647        );
9648        assert_eq!(
9649            crate::test_git::git(&caller, &["log", "-1", "--format=%s"]),
9650            "work"
9651        );
9652        assert_eq!(
9653            exit_code_of(&parent, &format!("rm -rf '{}'", space.display())).await,
9654            0,
9655            "the launcher owns the space"
9656        );
9657        assert!(!space.exists());
9658    }
9659
9660    /// A space the launcher's spaces cannot prepare fails the launch with
9661    /// their error, and is removed with what they left in it.
9662    #[cfg(unix)]
9663    #[tokio::test(flavor = "multi_thread")]
9664    async fn a_space_that_cannot_be_prepared_fails_the_launch_and_is_removed() {
9665        let dir = tempfile::tempdir().expect("temp dir should be created");
9666        let (parent, seen) = spaced_terminal(dir.path(), Filling::Fail).await;
9667        let error = launch(&parent, SubagentGrant::new())
9668            .await
9669            .expect_err("the launch fails");
9670        let (asked, _, _) = seen.try_recv().unwrap();
9671        let SubagentGrantError::Preparation { space, source } = &error else {
9672            panic!("the launch fails with the preparation error: {error}");
9673        };
9674        assert_eq!(space, &asked);
9675        assert!(source.downcast_ref::<NoClone>().is_some(), "{error}");
9676        assert!(
9677            error
9678                .to_string()
9679                .contains("the session has no clone to give")
9680        );
9681        assert!(!space.exists(), "the failed space is removed");
9682    }
9683
9684    /// A working copy named outside the space fails the launch, and the space
9685    /// is removed.
9686    #[cfg(unix)]
9687    #[tokio::test(flavor = "multi_thread")]
9688    async fn a_working_copy_outside_the_space_fails_the_launch() {
9689        let dir = tempfile::tempdir().expect("temp dir should be created");
9690        let (parent, seen) = spaced_terminal(dir.path(), Filling::Outside).await;
9691        let error = launch(&parent, SubagentGrant::new())
9692            .await
9693            .expect_err("the launch fails");
9694        let (asked, launcher, _) = seen.try_recv().unwrap();
9695        let SubagentGrantError::PreparedOutsideSpace { path, space } = &error else {
9696            panic!("the launch fails on the working copy: {error}");
9697        };
9698        assert_eq!((path, space), (&launcher, &asked));
9699        assert!(!asked.exists(), "the refused space is removed");
9700    }
9701
9702    /// An environment directory named outside the space fails the launch,
9703    /// and the space is removed.
9704    #[cfg(unix)]
9705    #[tokio::test(flavor = "multi_thread")]
9706    async fn an_environment_directory_outside_the_space_fails_the_launch() {
9707        let dir = tempfile::tempdir().expect("temp dir should be created");
9708        let (parent, seen) = spaced_terminal(dir.path(), Filling::EnvOutside).await;
9709        let error = launch(&parent, SubagentGrant::new())
9710            .await
9711            .expect_err("the launch fails");
9712        let (asked, launcher, _) = seen.try_recv().unwrap();
9713        let SubagentGrantError::PreparedOutsideSpace { path, space } = &error else {
9714            panic!("the launch fails on the environment directory: {error}");
9715        };
9716        assert_eq!((path, space), (&launcher, &asked));
9717        assert!(!asked.exists(), "the refused space is removed");
9718    }
9719
9720    /// A subagent's commands see the directories its space was prepared with
9721    /// over the launcher's environment, and write them; a subagent it
9722    /// launches sees its own space's alone.
9723    #[cfg(unix)]
9724    #[tokio::test(flavor = "multi_thread")]
9725    async fn a_subagent_sees_the_environment_directories_of_its_own_space() {
9726        let dir = tempfile::tempdir().expect("temp dir should be created");
9727        let parent = authority_terminal(dir.path())
9728            .await
9729            .with_subagent_spaces(EnvSpaces::default());
9730        let child = launch(&parent, SubagentGrant::new())
9731            .await
9732            .expect("the space is prepared");
9733        let space = child.working_dir().to_path_buf();
9734        let (tmp, cache) = (space.join("tmp"), space.join("cache"));
9735        assert_eq!(
9736            child.prepared_space().unwrap().env_dirs().to_vec(),
9737            vec![
9738                ("TMPDIR".to_owned(), tmp.clone()),
9739                ("AITHER_TEST_CACHE".to_owned(), cache.clone()),
9740            ]
9741        );
9742        assert_eq!(
9743            stdout_of(&child, "echo \"$TMPDIR|$AITHER_TEST_CACHE\"").await,
9744            format!("{}|{}", tmp.display(), cache.display())
9745        );
9746        assert_eq!(
9747            exit_code_of(
9748                &child,
9749                "touch \"$TMPDIR/written\" \"$AITHER_TEST_CACHE/written\""
9750            )
9751            .await,
9752            0,
9753            "the subagent writes the directories its environment names"
9754        );
9755        assert!(tmp.join("written").exists() && cache.join("written").exists());
9756        assert_ne!(
9757            stdout_of(&parent, "echo \"$TMPDIR\"").await,
9758            tmp.display().to_string(),
9759            "the launcher keeps its own environment"
9760        );
9761
9762        let nested = launch(&child, SubagentGrant::new())
9763            .await
9764            .expect("a nested space is prepared");
9765        assert_eq!(
9766            stdout_of(&nested, "echo \"$TMPDIR|${AITHER_TEST_CACHE-unset}\"").await,
9767            format!("{}|unset", nested.working_dir().join("tmp").display()),
9768            "a nested subagent carries its own space's variables alone"
9769        );
9770    }
9771
9772    /// In a container, a subagent's commands export the directories its
9773    /// space was prepared with as the container spells them, and a subagent
9774    /// it launches exports its own space's alone.
9775    #[cfg(unix)]
9776    #[tokio::test(flavor = "multi_thread")]
9777    async fn a_container_subagent_exports_its_spaces_environment_through_the_mount() {
9778        let dir = tempfile::tempdir().expect("temp dir should be created");
9779        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
9780        let parent = parent.with_subagent_spaces(EnvSpaces::default());
9781        let child = launch(&parent, SubagentGrant::new())
9782            .await
9783            .expect("a space inside the workspace can be prepared");
9784        let nested = launch(&child, SubagentGrant::new())
9785            .await
9786            .expect("a nested space is prepared");
9787        assert_eq!(exit_code_of(&child, "echo child-env-probe").await, 0);
9788        assert_eq!(exit_code_of(&nested, "echo nested-env-probe").await, 0);
9789
9790        let root = dunce::canonicalize(dir.path()).unwrap();
9791        let in_container = |path: &Path| {
9792            format!(
9793                "/workspace/{}",
9794                path.strip_prefix(&root).unwrap().to_str().unwrap()
9795            )
9796        };
9797        let scripts = scripts.lock().unwrap().clone();
9798        let script_of = |probe: &str| {
9799            scripts
9800                .iter()
9801                .find(|script| script.contains(probe))
9802                .unwrap_or_else(|| panic!("the {probe} command ran"))
9803                .clone()
9804        };
9805        let child_script = script_of("child-env-probe");
9806        let space = child.working_dir();
9807        for (name, path) in [
9808            ("TMPDIR", space.join("tmp")),
9809            ("AITHER_TEST_CACHE", space.join("cache")),
9810        ] {
9811            assert!(
9812                child_script.contains(&format!("export {name}="))
9813                    && child_script.contains(&in_container(&path)),
9814                "{name} is exported as the container spells it: {child_script}"
9815            );
9816            assert!(
9817                !child_script.contains(&path.display().to_string()),
9818                "the container sees no host spelling: {child_script}"
9819            );
9820        }
9821        let nested_script = script_of("nested-env-probe");
9822        assert!(
9823            nested_script.contains(&in_container(&nested.working_dir().join("tmp"))),
9824            "{nested_script}"
9825        );
9826        assert!(
9827            !nested_script.contains("AITHER_TEST_CACHE")
9828                && !nested_script.contains(&in_container(&space.join("tmp"))),
9829            "a nested subagent exports its own space's variables alone: {nested_script}"
9830        );
9831    }
9832
9833    #[cfg(unix)]
9834    #[tokio::test(flavor = "multi_thread")]
9835    async fn subagent_cannot_write_the_session_root_but_writes_its_space_and_granted_worktrees() {
9836        let dir = tempfile::tempdir().expect("temp dir should be created");
9837        let parent = authority_terminal(dir.path()).await;
9838        let granted = dir.path().join("granted");
9839        let ungranted = dir.path().join("ungranted");
9840        std::fs::create_dir_all(&granted).unwrap();
9841        std::fs::create_dir_all(&ungranted).unwrap();
9842        let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
9843            .await
9844            .expect("a writable directory can be granted");
9845
9846        let touch = |path: &Path| format!("touch '{}'", path.display());
9847        let root_file = dir.path().join("root.txt");
9848        assert_eq!(
9849            exit_code_of(&parent, &touch(&root_file)).await,
9850            0,
9851            "the main agent writes its own space"
9852        );
9853        std::fs::remove_file(&root_file).unwrap();
9854
9855        assert_ne!(
9856            exit_code_of(&child, &touch(&root_file)).await,
9857            0,
9858            "the session root is read-only to a subagent"
9859        );
9860        assert!(!root_file.exists());
9861        assert_ne!(
9862            exit_code_of(&child, &touch(&ungranted.join("x"))).await,
9863            0,
9864            "what the parent can write but did not grant is read-only"
9865        );
9866        assert_eq!(
9867            exit_code_of(&child, &touch(&child.working_dir().join("own.txt"))).await,
9868            0,
9869            "a subagent writes its own space"
9870        );
9871        assert!(
9872            child
9873                .working_dir()
9874                .starts_with(dunce::canonicalize(dir.path()).unwrap())
9875        );
9876        assert_ne!(child.working_dir(), parent.working_dir());
9877        assert_eq!(
9878            exit_code_of(&child, &touch(&granted.join("g.txt"))).await,
9879            0,
9880            "a subagent writes the worktrees it was granted"
9881        );
9882    }
9883
9884    /// Runs `script` in `tool` and returns its trimmed standard output.
9885    #[cfg(unix)]
9886    async fn stdout_of(tool: &ConfiguredTestTool, script: &str) -> String {
9887        let result = tool
9888            .call(terminal_args("carry probe", script), ToolContext::new())
9889            .await
9890            .expect("terminal call should succeed");
9891        render_terminal_result(&result).trim().to_string()
9892    }
9893
9894    /// The directory `pwd` prints for the next command.
9895    #[cfg(unix)]
9896    async fn pwd_of(tool: &ConfiguredTestTool) -> PathBuf {
9897        PathBuf::from(stdout_of(tool, "pwd").await)
9898    }
9899
9900    #[cfg(unix)]
9901    #[tokio::test(flavor = "multi_thread")]
9902    async fn a_successful_cd_carries_to_the_next_foreground_command() {
9903        let dir = tempfile::tempdir().expect("temp dir should be created");
9904        let tool = authority_terminal(dir.path()).await;
9905        let root = dunce::canonicalize(dir.path()).unwrap();
9906        assert_eq!(pwd_of(&tool).await, root);
9907
9908        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
9909        assert_eq!(pwd_of(&tool).await, root.join("sub"));
9910        // Relative to the carried directory, and a later `cd` carries on.
9911        assert_eq!(exit_code_of(&tool, "mkdir -p a/b && cd a/b").await, 0);
9912        assert_eq!(pwd_of(&tool).await, root.join("sub/a/b"));
9913        // A direct command starts in the carried directory too.
9914        assert_eq!(
9915            PathBuf::from(stdout_of(&tool, "/bin/pwd").await),
9916            root.join("sub/a/b")
9917        );
9918    }
9919
9920    #[cfg(unix)]
9921    #[tokio::test(flavor = "multi_thread")]
9922    async fn a_failure_an_outside_cd_and_a_background_cd_leave_the_directory() {
9923        let dir = tempfile::tempdir().expect("temp dir should be created");
9924        let tool = authority_terminal(dir.path()).await;
9925        let root = dunce::canonicalize(dir.path()).unwrap();
9926        stdout_of(&tool, "mkdir sub other && cd sub").await;
9927        let sub = root.join("sub");
9928        assert_eq!(pwd_of(&tool).await, sub);
9929
9930        assert_eq!(
9931            exit_code_of(&tool, "cd ../other; exit 3").await,
9932            3,
9933            "the command fails"
9934        );
9935        assert_eq!(pwd_of(&tool).await, sub, "a failed command carries nothing");
9936
9937        // Readable to the sandbox, yet in none of the terminal's grants.
9938        assert_eq!(
9939            exit_code_of(&tool, "cd /usr").await,
9940            0,
9941            "the cd itself succeeds"
9942        );
9943        assert_eq!(
9944            pwd_of(&tool).await,
9945            sub,
9946            "a directory outside the readable paths carries nothing"
9947        );
9948
9949        start_background_job(&tool, "cd ../other && pwd").await;
9950        for _ in 0..500 {
9951            if tool.running_tasks.load(Ordering::Acquire) == 0 {
9952                break;
9953            }
9954            async_io::Timer::after(Duration::from_millis(20)).await;
9955        }
9956        assert_eq!(tool.running_tasks.load(Ordering::Acquire), 0);
9957        assert_eq!(pwd_of(&tool).await, sub, "a background cd carries nothing");
9958    }
9959
9960    #[cfg(unix)]
9961    #[tokio::test(flavor = "multi_thread")]
9962    async fn an_exported_variable_does_not_reach_the_next_command() {
9963        let dir = tempfile::tempdir().expect("temp dir should be created");
9964        let tool = authority_terminal(dir.path()).await;
9965        assert_eq!(
9966            stdout_of(
9967                &tool,
9968                "export CARRY_PROBE=set; mkdir sub; cd sub; echo $CARRY_PROBE"
9969            )
9970            .await,
9971            "set"
9972        );
9973        assert_eq!(
9974            stdout_of(&tool, "printenv CARRY_PROBE; echo rc=$?").await,
9975            "rc=1"
9976        );
9977        assert_eq!(
9978            pwd_of(&tool).await,
9979            dunce::canonicalize(dir.path()).unwrap().join("sub")
9980        );
9981    }
9982
9983    #[cfg(unix)]
9984    #[tokio::test(flavor = "multi_thread")]
9985    async fn a_symlinked_working_directory_is_resolved_for_the_report() {
9986        let dir = tempfile::tempdir().expect("temp dir should be created");
9987        let real = dunce::canonicalize(dir.path()).unwrap().join("real");
9988        std::fs::create_dir(&real).unwrap();
9989        let link = dir.path().join("link");
9990        std::os::unix::fs::symlink(&real, &link).unwrap();
9991
9992        let tool = authority_terminal(&link).await;
9993        assert_eq!(tool.working_dir(), &real);
9994        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
9995        assert_eq!(pwd_of(&tool).await, real.join("sub"));
9996    }
9997
9998    #[cfg(unix)]
9999    #[tokio::test(flavor = "multi_thread")]
10000    async fn a_subagents_cd_does_not_carry_over() {
10001        let dir = tempfile::tempdir().expect("temp dir should be created");
10002        let parent = authority_terminal(dir.path()).await;
10003        let child = launch(&parent, SubagentGrant::new())
10004            .await
10005            .expect("a subagent without grants launches");
10006        let space = child.working_dir().clone();
10007
10008        assert_eq!(exit_code_of(&child, "mkdir sub && cd sub").await, 0);
10009        assert_eq!(
10010            pwd_of(&child).await,
10011            space,
10012            "the subagent starts in its space"
10013        );
10014        // Nor does it disturb the main agent's directory.
10015        assert_eq!(
10016            pwd_of(&parent).await,
10017            dunce::canonicalize(dir.path()).unwrap()
10018        );
10019    }
10020
10021    #[cfg(unix)]
10022    #[test]
10023    fn container_directory_report_is_written_by_the_rendered_script() {
10024        let dir = tempfile::tempdir().expect("temp dir should be created");
10025        let report = dir.path().join("it's report");
10026        let script = carry_cwd_script("mkdir sub && cd sub", &report.to_string_lossy())
10027            .expect("the trailer should render");
10028        let status = std::process::Command::new("sh")
10029            .args(["-c", &script])
10030            .current_dir(dir.path())
10031            .status()
10032            .expect("sh should run");
10033        assert!(status.success());
10034        let written = std::fs::read_to_string(&report).expect("the trailer writes the report");
10035        assert_eq!(
10036            PathBuf::from(written.trim_end()),
10037            dunce::canonicalize(dir.path().join("sub")).unwrap()
10038        );
10039        // The script's own exit status survives the trailer, whether the
10040        // script ends through `exit` or its last command fails.
10041        for (script, code) in [("exit 7", 7), ("cd sub; (exit 5)", 5)] {
10042            let status = std::process::Command::new("sh")
10043                .args([
10044                    "-c",
10045                    &carry_cwd_script(script, &report.to_string_lossy()).unwrap(),
10046                ])
10047                .current_dir(dir.path())
10048                .status()
10049                .expect("sh should run");
10050            assert_eq!(status.code(), Some(code), "{script}");
10051        }
10052        // The script's own syntax cannot swallow the trailer: an unterminated
10053        // here-document holding a quote still ends before the report.
10054        std::fs::remove_file(&report).expect("the report exists");
10055        let output = std::process::Command::new("sh")
10056            .args([
10057                "-c",
10058                &carry_cwd_script("cd sub; cat <<EOF\nit's", &report.to_string_lossy()).unwrap(),
10059            ])
10060            .current_dir(dir.path())
10061            .output()
10062            .expect("sh should run");
10063        assert!(output.status.success());
10064        // bash ends the unterminated body with a newline, dash does not.
10065        assert_eq!(String::from_utf8_lossy(&output.stdout).trim_end(), "it's");
10066        let written = std::fs::read_to_string(&report).expect("the trailer writes the report");
10067        assert_eq!(
10068            PathBuf::from(written.trim_end()),
10069            dunce::canonicalize(dir.path().join("sub")).unwrap()
10070        );
10071    }
10072
10073    /// Reports how each script ended, to a channel the test holds.
10074    struct RecordCarries(async_channel::Sender<(ScriptDir, Carry)>);
10075
10076    impl crate::ScriptPolicy for RecordCarries {
10077        type State = ();
10078
10079        fn check(
10080            &self,
10081            _script: &crate::ScriptCheck<'_>,
10082            (): &(),
10083        ) -> impl Future<Output = ScriptDecision> + Send {
10084            std::future::ready(ScriptDecision::Pass)
10085        }
10086
10087        async fn ended(&self, end: &crate::ScriptEnd<'_>, (): &()) {
10088            self.0
10089                .send((end.end.clone(), end.carry))
10090                .await
10091                .expect("the test holds the receiver");
10092        }
10093    }
10094
10095    /// The main agent's terminal of [`authority_terminal`], with the end of
10096    /// every script reported on the returned channel.
10097    #[cfg(unix)]
10098    async fn carry_terminal(
10099        dir: &Path,
10100    ) -> (
10101        ConfiguredTestTool,
10102        async_channel::Receiver<(ScriptDir, Carry)>,
10103    ) {
10104        let (ends_tx, ends) = async_channel::unbounded();
10105        let tool = configured_test_terminal(
10106            dir,
10107            Duration::from_secs(30),
10108            Duration::from_secs(60),
10109            Duration::from_secs(600),
10110        )
10111        .await
10112        .with_test_policies(vec![crate::AnyScriptPolicy::new(RecordCarries(ends_tx))]);
10113        (tool, ends)
10114    }
10115
10116    /// The ends reported since the last call.
10117    #[cfg(unix)]
10118    fn carries(ends: &async_channel::Receiver<(ScriptDir, Carry)>) -> Vec<(ScriptDir, Carry)> {
10119        std::iter::from_fn(|| ends.try_recv().ok()).collect()
10120    }
10121
10122    #[cfg(unix)]
10123    #[tokio::test(flavor = "multi_thread")]
10124    async fn a_carried_directory_is_moved_or_unchanged() {
10125        let dir = tempfile::tempdir().expect("temp dir should be created");
10126        let (tool, ends) = carry_terminal(dir.path()).await;
10127        let sub = ScriptDir::Host(dunce::canonicalize(dir.path()).unwrap().join("sub"));
10128
10129        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
10130        assert_eq!(exit_code_of(&tool, "true").await, 0);
10131        assert_eq!(exit_code_of(&tool, "pwd").await, 0);
10132        // A failure that stayed in its directory, and a direct command.
10133        assert_ne!(exit_code_of(&tool, "false").await, 0);
10134        assert_ne!(exit_code_of(&tool, "ls /nonexistent-directory").await, 0);
10135        assert_eq!(
10136            carries(&ends),
10137            [
10138                (sub.clone(), Carry::Moved),
10139                (sub.clone(), Carry::Unchanged),
10140                (sub.clone(), Carry::Unchanged),
10141                (sub.clone(), Carry::Unchanged),
10142                (sub, Carry::Unchanged),
10143            ]
10144        );
10145    }
10146
10147    #[cfg(unix)]
10148    #[tokio::test(flavor = "multi_thread")]
10149    async fn a_failed_command_resets_to_the_directory_commands_run_in() {
10150        let dir = tempfile::tempdir().expect("temp dir should be created");
10151        let (tool, ends) = carry_terminal(dir.path()).await;
10152        let root = dunce::canonicalize(dir.path()).unwrap();
10153
10154        assert_ne!(exit_code_of(&tool, "mkdir sub && cd sub && false").await, 0);
10155        assert_eq!(
10156            carries(&ends),
10157            [(
10158                ScriptDir::Host(root.clone()),
10159                Carry::Reset(DirectoryResetReason::Failed)
10160            )]
10161        );
10162        assert_eq!(pwd_of(&tool).await, root);
10163    }
10164
10165    #[cfg(unix)]
10166    #[tokio::test(flavor = "multi_thread")]
10167    async fn exit_without_a_report_resets() {
10168        let dir = tempfile::tempdir().expect("temp dir should be created");
10169        let (tool, ends) = carry_terminal(dir.path()).await;
10170        let root = dunce::canonicalize(dir.path()).unwrap();
10171        let sub = ScriptDir::Host(root.join("sub"));
10172
10173        assert_eq!(exit_code_of(&tool, "mkdir sub && cd sub").await, 0);
10174        assert_eq!(exit_code_of(&tool, "cd ..; exit 0").await, 0);
10175        assert_eq!(
10176            carries(&ends),
10177            [
10178                (sub.clone(), Carry::Moved),
10179                (sub, Carry::Reset(DirectoryResetReason::Unreported)),
10180            ]
10181        );
10182        assert_eq!(pwd_of(&tool).await, root.join("sub"));
10183    }
10184
10185    #[cfg(unix)]
10186    #[tokio::test(flavor = "multi_thread")]
10187    async fn a_directory_outside_the_readable_paths_resets() {
10188        let dir = tempfile::tempdir().expect("temp dir should be created");
10189        let (tool, ends) = carry_terminal(dir.path()).await;
10190        let root = dunce::canonicalize(dir.path()).unwrap();
10191
10192        // Readable to the sandbox, yet in none of the terminal's grants.
10193        assert_eq!(exit_code_of(&tool, "cd /usr").await, 0);
10194        assert_eq!(
10195            carries(&ends),
10196            [(
10197                ScriptDir::Host(root.clone()),
10198                Carry::Reset(DirectoryResetReason::OutsideReadable)
10199            )]
10200        );
10201        assert_eq!(pwd_of(&tool).await, root);
10202    }
10203
10204    #[cfg(unix)]
10205    #[tokio::test(flavor = "multi_thread")]
10206    async fn a_removed_carried_directory_resets() {
10207        let dir = tempfile::tempdir().expect("temp dir should be created");
10208        let (tool, ends) = carry_terminal(dir.path()).await;
10209        let root = dunce::canonicalize(dir.path()).unwrap();
10210
10211        assert_eq!(exit_code_of(&tool, "mkdir gone && cd gone").await, 0);
10212        assert_eq!(
10213            carries(&ends),
10214            [(ScriptDir::Host(root.join("gone")), Carry::Moved)]
10215        );
10216        std::fs::remove_dir(root.join("gone")).unwrap();
10217        assert_eq!(pwd_of(&tool).await, root);
10218        assert_eq!(
10219            carries(&ends),
10220            [(
10221                ScriptDir::Host(root.clone()),
10222                Carry::Reset(DirectoryResetReason::Removed)
10223            )]
10224        );
10225        assert_eq!(pwd_of(&tool).await, root);
10226        assert_eq!(carries(&ends), [(ScriptDir::Host(root), Carry::Unchanged)]);
10227    }
10228
10229    #[cfg(unix)]
10230    #[tokio::test(flavor = "multi_thread")]
10231    async fn a_container_directory_report_maps_through_the_workspace_mount() {
10232        let dir = tempfile::tempdir().expect("temp dir should be created");
10233        let tool = authority_terminal(dir.path()).await;
10234        let mount = MountRoot::new(
10235            tool.working_dir(),
10236            ContainerPath::new("/workspace").expect("absolute"),
10237        );
10238        let report = tool.working_dir().join(".cwd-container");
10239        let carry = CwdCarry {
10240            start: None,
10241            report: Some(report.clone()),
10242            container: Some(ContainerCarry {
10243                mount: mount.clone(),
10244                report: Some(
10245                    mount
10246                        .container_path(&report)
10247                        .expect("report is in the mount"),
10248                ),
10249                start: ContainerPath::new("/workspace").unwrap(),
10250            }),
10251            shell: true,
10252            removed: false,
10253        };
10254        assert_eq!(
10255            carry
10256                .container
10257                .as_ref()
10258                .unwrap()
10259                .report
10260                .as_ref()
10261                .unwrap()
10262                .as_str(),
10263            format!(
10264                "/workspace/{}",
10265                report.file_name().unwrap().to_string_lossy()
10266            )
10267        );
10268        let carried = tool.carried_dir.as_ref().unwrap();
10269
10270        // A directory inside the mount, spelled as the container sees it.
10271        std::fs::write(&report, "/workspace/sub/dir\n").unwrap();
10272        let settled = tool.record_carried_dir(&carry, true).await;
10273        assert_eq!(carried.get(), Some(tool.working_dir().join("sub/dir")));
10274        assert!(!report.exists(), "the report is consumed");
10275        assert_eq!(settled.carry, Carry::Moved);
10276        assert_eq!(settled.carried, carried.get());
10277
10278        // Outside the mount, after a failure and an empty report: unchanged,
10279        // and each says why the next command starts where the last did.
10280        std::fs::write(&report, "/etc\n").unwrap();
10281        let settled = tool.record_carried_dir(&carry, true).await;
10282        assert_eq!(carried.get(), Some(tool.working_dir().join("sub/dir")));
10283        assert_eq!(
10284            settled.carry,
10285            Carry::Reset(DirectoryResetReason::OutsideWorkspace)
10286        );
10287        std::fs::write(&report, "/workspace/other\n").unwrap();
10288        let settled = tool.record_carried_dir(&carry, false).await;
10289        assert_eq!(carried.get(), Some(tool.working_dir().join("sub/dir")));
10290        assert_eq!(settled.carry, Carry::Reset(DirectoryResetReason::Failed));
10291        let settled = tool.record_carried_dir(&carry, true).await;
10292        assert_eq!(
10293            settled.carry,
10294            Carry::Reset(DirectoryResetReason::Unreported)
10295        );
10296        // A failure that stayed where it started changes nothing.
10297        std::fs::write(&report, "/workspace\n").unwrap();
10298        let settled = tool.record_carried_dir(&carry, false).await;
10299        assert_eq!(settled.carry, Carry::Unchanged);
10300
10301        // The mapping back to the container for the next start.
10302        assert_eq!(
10303            mount
10304                .container_path(&tool.working_dir().join("sub/dir"))
10305                .unwrap()
10306                .as_str(),
10307            "/workspace/sub/dir"
10308        );
10309    }
10310
10311    #[cfg(unix)]
10312    #[tokio::test]
10313    async fn a_grant_outside_the_launchers_authority_is_refused() {
10314        let dir = tempfile::tempdir().expect("temp dir should be created");
10315        let outside = tempfile::tempdir().expect("temp dir should be created");
10316        let parent = authority_terminal(dir.path()).await;
10317        let error = launch(&parent, SubagentGrant::new().with_worktree(outside.path()))
10318            .await
10319            .expect_err("a launcher cannot hand on what it cannot write");
10320        assert!(
10321            matches!(error, SubagentGrantError::OutsideAuthority(_)),
10322            "{error}"
10323        );
10324    }
10325
10326    #[cfg(unix)]
10327    fn commit_script(worktree: &Path, subject: &str) -> String {
10328        format!(
10329            "git -c user.name=agent -c user.email=agent@example.com -c commit.gpgSign=false -C '{}' commit --allow-empty -m '{subject}'",
10330            worktree.display()
10331        )
10332    }
10333
10334    /// A repository with a worktree one can commit in, and the paths the
10335    /// commit grant is about, all canonical.
10336    #[cfg(unix)]
10337    struct CommitSetup {
10338        dir: tempfile::TempDir,
10339        worktree: PathBuf,
10340        /// The main repository's git directory.
10341        common: PathBuf,
10342        /// The worktree's entry in it.
10343        entry: PathBuf,
10344        /// The subagent's repository.
10345        subagent: PathBuf,
10346        parent: ConfiguredTestTool,
10347    }
10348
10349    #[cfg(unix)]
10350    impl CommitSetup {
10351        async fn new(namespace: &str) -> Self {
10352            let dir = tempfile::tempdir().expect("temp dir should be created");
10353            let worktree =
10354                crate::subagent::tests::repository_with_linked_worktree(dir.path(), namespace);
10355            let parent = authority_terminal(dir.path()).await;
10356            let common = dunce::canonicalize(dir.path().join("repository/.git")).unwrap();
10357            let entry = common.join("worktrees").join(namespace);
10358            Self {
10359                worktree: dunce::canonicalize(worktree).unwrap(),
10360                subagent: entry.join("subagent"),
10361                common,
10362                entry,
10363                parent,
10364                dir,
10365            }
10366        }
10367
10368        async fn committing_child(&self, launcher: &ConfiguredTestTool) -> ConfiguredTestTool {
10369            launch(
10370                launcher,
10371                SubagentGrant::new().with_committing_worktree(&self.worktree),
10372            )
10373            .await
10374            .expect("the worktree can be granted with commit")
10375        }
10376
10377        fn main_has(&self, id: &str) -> bool {
10378            crate::test_git::command()
10379                .args(["cat-file", "-e", id])
10380                .current_dir(&self.common)
10381                .output()
10382                .unwrap()
10383                .status
10384                .success()
10385        }
10386
10387        fn main(&self, args: &[&str]) -> String {
10388            crate::subagent::tests::git_in(&self.common, args)
10389        }
10390    }
10391
10392    #[cfg(unix)]
10393    #[tokio::test(flavor = "multi_thread")]
10394    async fn a_sandboxed_commit_lands_in_the_subagents_repository_and_the_main_one_is_read_only() {
10395        let setup = CommitSetup::new("one").await;
10396        let child = setup.committing_child(&setup.parent).await;
10397        let ledger = child.commit_ledger().expect("a commit grant has a ledger");
10398        let mark = ledger.mark().await.expect("the namespace can be read");
10399        let before = setup.main(&["rev-parse", "refs/heads/subagent/one/work"]);
10400
10401        assert_eq!(
10402            exit_code_of(&child, &commit_script(&setup.worktree, "authorized")).await,
10403            0,
10404            "a commit grant lets the subagent commit"
10405        );
10406        assert_eq!(
10407            setup.main(&["rev-parse", "refs/heads/subagent/one/work"]),
10408            before,
10409            "the commit is not in the main repository yet"
10410        );
10411
10412        let commits = ledger.since(&mark).await.expect("commits can be listed");
10413        assert_eq!(commits.len(), 1, "{commits:?}");
10414        assert_eq!(commits[0].subject, "authorized");
10415        assert_eq!(commits[0].worktree, setup.worktree);
10416        assert!(setup.main_has(&commits[0].commit));
10417        assert_eq!(
10418            setup.main(&["rev-parse", "refs/heads/subagent/one/work"]),
10419            commits[0].commit
10420        );
10421        setup.main(&["fsck", "--strict", "--no-dangling"]);
10422    }
10423
10424    /// Nothing of the main repository's git directory is writable to a
10425    /// committing subagent: each attempt on the main repository fails, and the
10426    /// same command shape on the subagent's own repository, its positive
10427    /// control, succeeds.
10428    #[cfg(unix)]
10429    #[tokio::test(flavor = "multi_thread")]
10430    #[allow(clippy::too_many_lines)]
10431    async fn a_committing_subagent_can_change_nothing_the_main_repository_reads() {
10432        let setup = CommitSetup::new("two").await;
10433        let child = setup.committing_child(&setup.parent).await;
10434
10435        // A fan-out directory known to be absent, and a loose object known to
10436        // exist, in the main object store.
10437        let absent = setup.common.join("objects/ff");
10438        let _ = std::fs::remove_dir(&absent);
10439        assert!(!absent.exists());
10440        let loose_dir = std::fs::read_dir(setup.common.join("objects"))
10441            .unwrap()
10442            .map(|entry| entry.unwrap().path())
10443            .find(|path| {
10444                path.file_name()
10445                    .and_then(|name| name.to_str())
10446                    .is_some_and(|name| name.len() == 2 && name != "ff")
10447            })
10448            .expect("the initial commit left loose objects");
10449        let loose = std::fs::read_dir(&loose_dir)
10450            .unwrap()
10451            .next()
10452            .unwrap()
10453            .unwrap()
10454            .path();
10455        let loose_name = loose.file_name().unwrap().to_str().unwrap().to_string();
10456        let loose_dir_name = loose_dir.file_name().unwrap().to_str().unwrap().to_string();
10457        let loose_bytes = std::fs::read(&loose).unwrap();
10458
10459        // The subagent's own repository, for the controls.
10460        let own = &setup.subagent;
10461        std::fs::create_dir_all(own.join("objects").join(&loose_dir_name)).unwrap();
10462        std::fs::write(
10463            own.join("objects").join(&loose_dir_name).join(&loose_name),
10464            b"own",
10465        )
10466        .unwrap();
10467
10468        let main_objects = setup.common.join("objects");
10469        let own_objects = own.join("objects");
10470        let attempts: Vec<(&str, String, String)> = vec![
10471            (
10472                "create a fan-out directory",
10473                format!("mkdir '{}'", main_objects.join("ff").display()),
10474                format!("mkdir '{}'", own_objects.join("ff").display()),
10475            ),
10476            (
10477                "create an object in an existing fan-out directory",
10478                format!(
10479                    "touch '{}'",
10480                    main_objects.join(&loose_dir_name).join("new").display()
10481                ),
10482                format!(
10483                    "touch '{}'",
10484                    own_objects.join(&loose_dir_name).join("new").display()
10485                ),
10486            ),
10487            (
10488                "overwrite an existing loose object",
10489                format!("echo evil > '{}'", loose.display()),
10490                format!(
10491                    "echo evil > '{}'",
10492                    own_objects
10493                        .join(&loose_dir_name)
10494                        .join(&loose_name)
10495                        .display()
10496                ),
10497            ),
10498            (
10499                "replace an existing loose object by renaming over it",
10500                format!(
10501                    "echo evil > '{}/stage' && mv -f '{}/stage' '{}'",
10502                    own_objects.display(),
10503                    own_objects.display(),
10504                    loose.display()
10505                ),
10506                format!(
10507                    "echo evil > '{}/stage' && mv -f '{}/stage' '{}'",
10508                    own_objects.display(),
10509                    own_objects.display(),
10510                    own_objects
10511                        .join(&loose_dir_name)
10512                        .join(&loose_name)
10513                        .display()
10514                ),
10515            ),
10516            (
10517                "remove an existing loose object",
10518                format!("rm -f '{}'", loose.display()),
10519                format!(
10520                    "rm -f '{}'",
10521                    own_objects
10522                        .join(&loose_dir_name)
10523                        .join(&loose_name)
10524                        .display()
10525                ),
10526            ),
10527            (
10528                "create a pack",
10529                format!(
10530                    "touch '{}'",
10531                    main_objects.join("pack/pack-x.pack").display()
10532                ),
10533                format!("touch '{}'", own_objects.join("pack/pack-x.pack").display()),
10534            ),
10535            (
10536                "write an alternates file",
10537                format!(
10538                    "echo /tmp > '{}'",
10539                    main_objects.join("info/alternates").display()
10540                ),
10541                format!(
10542                    "echo /tmp > '{}'",
10543                    own_objects.join("info/scratch").display()
10544                ),
10545            ),
10546            (
10547                "move the worktree's branch",
10548                format!(
10549                    "echo {} > '{}'",
10550                    "a".repeat(40),
10551                    setup.common.join("refs/heads/subagent/two/work").display()
10552                ),
10553                format!(
10554                    "echo {} > '{}'",
10555                    "a".repeat(40),
10556                    own.join("refs/heads/subagent/two/scratch").display()
10557                ),
10558            ),
10559            (
10560                "rewrite the entry's HEAD",
10561                format!("echo evil >> '{}'", setup.entry.join("HEAD").display()),
10562                format!("echo evil >> '{}'", own.join("scratch-head").display()),
10563            ),
10564            (
10565                "rewrite the entry's index",
10566                format!("echo evil >> '{}'", setup.entry.join("index").display()),
10567                format!("echo evil >> '{}'", own.join("scratch-index").display()),
10568            ),
10569            (
10570                "rewrite the repository's configuration",
10571                format!("echo evil >> '{}'", setup.common.join("config").display()),
10572                format!("echo evil >> '{}'", own.join("scratch-config").display()),
10573            ),
10574        ];
10575        for (what, denied, control) in attempts {
10576            assert_ne!(
10577                exit_code_of(&child, &denied).await,
10578                0,
10579                "must not {what} in the main repository"
10580            );
10581            assert_eq!(
10582                exit_code_of(&child, &control).await,
10583                0,
10584                "the same command succeeds in the subagent's own repository: {what}"
10585            );
10586        }
10587        assert!(!absent.exists(), "no fan-out directory appeared");
10588        assert_eq!(
10589            std::fs::read(&loose).unwrap(),
10590            loose_bytes,
10591            "the object is as it was"
10592        );
10593        assert!(
10594            !std::fs::read_to_string(setup.common.join("config"))
10595                .unwrap()
10596                .contains("evil")
10597        );
10598        setup.main(&["fsck", "--strict", "--no-dangling"]);
10599    }
10600
10601    /// Git in a repository the sandbox can read keeps working next to the
10602    /// redirected worktree: nothing is set process-wide.
10603    #[cfg(unix)]
10604    #[tokio::test(flavor = "multi_thread")]
10605    async fn git_in_another_repository_works_inside_a_committing_subagents_sandbox() {
10606        let setup = CommitSetup::new("three").await;
10607        let other = setup.dir.path().join("other");
10608        std::fs::create_dir_all(&other).unwrap();
10609        crate::subagent::tests::git_in(&other, &["init", "--initial-branch=main"]);
10610        crate::subagent::tests::git_in(&other, &["commit", "--allow-empty", "-m", "elsewhere"]);
10611        let child = setup.committing_child(&setup.parent).await;
10612
10613        assert!(
10614            stdout_of(
10615                &child,
10616                &format!("git -C '{}' log --oneline", other.display())
10617            )
10618            .await
10619            .contains("elsewhere")
10620        );
10621        let clone = child.working_dir().join("clone");
10622        assert_eq!(
10623            exit_code_of(
10624                &child,
10625                &format!("git clone '{}' '{}'", other.display(), clone.display())
10626            )
10627            .await,
10628            0
10629        );
10630        assert!(clone.join(".git").exists());
10631    }
10632
10633    /// A subagent a committing subagent launches with the commit grant it
10634    /// holds works in the same repository: it sees its parent's commits and
10635    /// the parent's ledger reports both.
10636    #[cfg(unix)]
10637    #[tokio::test(flavor = "multi_thread")]
10638    async fn a_committing_child_shares_its_parents_repository() {
10639        let setup = CommitSetup::new("four").await;
10640        let parent_subagent = setup.committing_child(&setup.parent).await;
10641        let parent_ledger = parent_subagent.commit_ledger().unwrap();
10642        let parent_mark = parent_ledger.mark().await.unwrap();
10643        assert_eq!(
10644            exit_code_of(
10645                &parent_subagent,
10646                &commit_script(&setup.worktree, "parent work")
10647            )
10648            .await,
10649            0
10650        );
10651
10652        let child = setup.committing_child(&parent_subagent).await;
10653        let child_ledger = child.commit_ledger().unwrap();
10654        let child_mark = child_ledger.mark().await.unwrap();
10655        assert!(
10656            stdout_of(
10657                &child,
10658                &format!("git -C '{}' log --oneline", setup.worktree.display())
10659            )
10660            .await
10661            .contains("parent work"),
10662            "the child sees its parent's commit"
10663        );
10664        assert_eq!(
10665            exit_code_of(&child, &commit_script(&setup.worktree, "child work")).await,
10666            0
10667        );
10668
10669        let child_commits = child_ledger.since(&child_mark).await.unwrap();
10670        assert_eq!(
10671            child_commits
10672                .iter()
10673                .map(|commit| commit.subject.as_str())
10674                .collect::<Vec<_>>(),
10675            ["child work"]
10676        );
10677        let parent_commits = parent_ledger.since(&parent_mark).await.unwrap();
10678        assert_eq!(
10679            parent_commits
10680                .iter()
10681                .map(|commit| commit.subject.as_str())
10682                .collect::<Vec<_>>(),
10683            ["parent work", "child work"]
10684        );
10685        for commit in &parent_commits {
10686            assert!(setup.main_has(&commit.commit));
10687        }
10688        setup.main(&["fsck", "--strict", "--no-dangling"]);
10689    }
10690
10691    /// The import asks a sandbox that cannot read another repository for that
10692    /// repository's objects: they cannot reach the main one.
10693    #[cfg(unix)]
10694    #[tokio::test(flavor = "multi_thread")]
10695    async fn objects_the_subagent_cannot_read_never_reach_the_main_repository() {
10696        let setup = CommitSetup::new("five").await;
10697        let child = setup.committing_child(&setup.parent).await;
10698        let outside = tempfile::tempdir().expect("temp dir should be created");
10699        std::fs::write(outside.path().join("secret.txt"), "secret").unwrap();
10700        crate::subagent::tests::git_in(outside.path(), &["init", "--initial-branch=main"]);
10701        crate::subagent::tests::git_in(outside.path(), &["add", "secret.txt"]);
10702        crate::subagent::tests::git_in(outside.path(), &["commit", "-m", "secret commit"]);
10703        let secret = crate::subagent::tests::git_in(outside.path(), &["rev-parse", "HEAD"]);
10704        // Reads are open except the denylist, so the other repository is
10705        // unreadable to the subagent only by an embedder denial.
10706        child
10707            .grants()
10708            .deny_read(std::fs::canonicalize(outside.path()).unwrap());
10709        assert_ne!(
10710            exit_code_of(
10711                &child,
10712                &format!("cat '{}'", outside.path().join("secret.txt").display())
10713            )
10714            .await,
10715            0,
10716            "the control: the sandbox cannot read the other repository"
10717        );
10718
10719        let ledger = child.commit_ledger().unwrap();
10720        let mark = ledger.mark().await.unwrap();
10721        // The subagent's repository names a commit only the other one has,
10722        // and reaches its objects through symlinks, as its own: a process
10723        // that could read the other repository would pack them (the pack
10724        // leaves out only objects borrowed from an alternate).
10725        for entry in std::fs::read_dir(outside.path().join(".git/objects")).unwrap() {
10726            let entry = entry.unwrap();
10727            let name = entry.file_name();
10728            if name.len() == 2 {
10729                std::os::unix::fs::symlink(entry.path(), setup.subagent.join("objects").join(name))
10730                    .unwrap();
10731            }
10732        }
10733        std::fs::write(
10734            setup.subagent.join("refs/heads/subagent/five/stolen"),
10735            format!("{secret}\n"),
10736        )
10737        .unwrap();
10738        assert_eq!(
10739            crate::subagent::tests::git_in(
10740                &setup.subagent,
10741                &["--git-dir", ".", "cat-file", "-t", &secret]
10742            ),
10743            "commit",
10744            "the control: a git that could read the other repository packs its commit"
10745        );
10746        let error = ledger
10747            .since(&mark)
10748            .await
10749            .expect_err("the sandbox cannot read the objects it is asked to pack");
10750        assert!(
10751            matches!(error, crate::CommitLedgerError::Export { .. }),
10752            "the sandboxed git is what refuses: {error}"
10753        );
10754        assert!(!setup.main_has(&secret), "the secret commit never arrives");
10755        assert!(
10756            !setup
10757                .common
10758                .join("refs/heads/subagent/five/stolen")
10759                .exists(),
10760            "and no ref names it"
10761        );
10762    }
10763
10764    /// The import budget is the terminal's operator setting: 1 GiB unless set,
10765    /// and a change through its handle reaches the subagents already running.
10766    #[cfg(unix)]
10767    #[tokio::test(flavor = "multi_thread")]
10768    async fn the_import_budget_is_a_setting_adjustable_while_subagents_run() {
10769        let setup = CommitSetup::new("budget").await;
10770        let budget = setup.parent.subagent_import_budget();
10771        assert_eq!(budget.get(), 1024 * 1024 * 1024);
10772        let child = setup.committing_child(&setup.parent).await;
10773        let ledger = child.commit_ledger().unwrap();
10774        let mark = ledger.mark().await.unwrap();
10775        assert_eq!(
10776            exit_code_of(
10777                &child,
10778                &commit_script(&setup.worktree, "heavier than 1 byte")
10779            )
10780            .await,
10781            0
10782        );
10783
10784        budget.set(1);
10785        let error = ledger
10786            .since(&mark)
10787            .await
10788            .expect_err("the setting changed after the subagent launched applies to it");
10789        assert!(
10790            matches!(
10791                error,
10792                crate::CommitLedgerError::Export { .. } | crate::CommitLedgerError::Rejected { .. }
10793            ),
10794            "{error}"
10795        );
10796        budget.set(0);
10797        let listed = ledger.since(&mark).await.expect("zero bounds nothing");
10798        assert_eq!(listed.len(), 1);
10799    }
10800
10801    /// A commit the main agent makes between runs is visible to the next run,
10802    /// and what the subagent had not yet shared survives the refresh.
10803    #[cfg(unix)]
10804    #[tokio::test(flavor = "multi_thread")]
10805    async fn the_run_start_refresh_shows_new_main_commits_and_keeps_unimported_work() {
10806        let setup = CommitSetup::new("six").await;
10807        let child = setup.committing_child(&setup.parent).await;
10808        let ledger = child.commit_ledger().unwrap();
10809        ledger.mark().await.unwrap();
10810        assert_eq!(
10811            exit_code_of(&child, &commit_script(&setup.worktree, "unimported")).await,
10812            0
10813        );
10814
10815        crate::subagent::tests::git_in(
10816            &dunce::canonicalize(setup.dir.path().join("repository")).unwrap(),
10817            &["commit", "--allow-empty", "-m", "main moved on"],
10818        );
10819        let log = |branch: &str| {
10820            format!(
10821                "git -C '{}' log --format=%s {branch}",
10822                setup.worktree.display()
10823            )
10824        };
10825        assert!(
10826            !stdout_of(&child, &log("main"))
10827                .await
10828                .contains("main moved on"),
10829            "the snapshot is the one from before"
10830        );
10831
10832        ledger.mark().await.unwrap();
10833        assert!(
10834            stdout_of(&child, &log("main"))
10835                .await
10836                .contains("main moved on"),
10837            "the next run starts with the main agent's new commit"
10838        );
10839        assert!(
10840            stdout_of(&child, &log("subagent/six/work"))
10841                .await
10842                .contains("unimported"),
10843            "the subagent's own work survives the refresh"
10844        );
10845    }
10846
10847    /// A container backend spells the repository's remote and runs the
10848    /// refresh, as the subagent, through the confined streamed exec.
10849    #[cfg(unix)]
10850    #[tokio::test(flavor = "multi_thread")]
10851    async fn a_container_commit_grant_refreshes_through_the_confined_streamed_exec() {
10852        let dir = tempfile::tempdir().expect("temp dir should be created");
10853        let worktree = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "seven");
10854        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
10855        let child = launch(
10856            &parent,
10857            SubagentGrant::new().with_committing_worktree(&worktree),
10858        )
10859        .await
10860        .expect("a worktree inside the workspace can be granted commit");
10861
10862        let subagent = dunce::canonicalize(dir.path())
10863            .unwrap()
10864            .join("repository/.git/worktrees/seven/subagent");
10865        let config = std::fs::read_to_string(subagent.join("config")).unwrap();
10866        assert!(
10867            config.contains("url = \"/workspace/repository/.git\""),
10868            "the remote is spelled as the container sees it: {config}"
10869        );
10870        assert!(
10871            config.contains("hooksPath = \"../repository/.git/hooks\""),
10872            "{config}"
10873        );
10874
10875        // The recording exec prints nothing, so the import that follows the
10876        // refresh finds no report; only the refresh is of interest here.
10877        let _ = child.commit_ledger().unwrap().mark().await;
10878        let scripts = scripts.lock().unwrap().clone();
10879        let refresh = scripts
10880            .iter()
10881            .find(|script| script.contains("fetch"))
10882            .expect("the refresh ran in the container");
10883        assert!(refresh.contains("run --working-dir"), "{refresh}");
10884        assert!(
10885            refresh.contains("--grant '/workspace/repository/.git/worktrees/seven/subagent=rw'"),
10886            "{refresh}"
10887        );
10888        assert!(
10889            refresh.contains("git --git-dir /workspace/repository/.git/worktrees/seven/subagent"),
10890            "{refresh}"
10891        );
10892        assert!(refresh.contains("main-repository"), "{refresh}");
10893    }
10894
10895    #[cfg(unix)]
10896    #[tokio::test]
10897    async fn a_commit_grant_needs_a_linked_worktree_whose_repository_the_launcher_can_write() {
10898        let dir = tempfile::tempdir().expect("temp dir should be created");
10899        let repository = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "two")
10900            .parent()
10901            .unwrap()
10902            .join("repository");
10903        let plain = dir.path().join("plain");
10904        std::fs::create_dir_all(&plain).unwrap();
10905        let parent = authority_terminal(dir.path()).await;
10906
10907        let checkout = launch(
10908            &parent,
10909            SubagentGrant::new().with_committing_worktree(&repository),
10910        )
10911        .await
10912        .expect_err("a checkout holds its git data inside the grant");
10913        assert!(
10914            matches!(checkout, SubagentGrantError::RepositoryCheckout(_)),
10915            "{checkout}"
10916        );
10917        let not_git = launch(
10918            &parent,
10919            SubagentGrant::new().with_committing_worktree(&plain),
10920        )
10921        .await
10922        .expect_err("a plain directory has nothing to commit in");
10923        assert!(
10924            matches!(not_git, SubagentGrantError::NotAWorktree(_)),
10925            "{not_git}"
10926        );
10927
10928        // A worktree inside the launcher's space whose repository is not.
10929        let elsewhere = tempfile::tempdir().expect("temp dir should be created");
10930        let foreign =
10931            crate::subagent::tests::repository_with_linked_worktree(elsewhere.path(), "three");
10932        let inside = dir.path().join("three");
10933        std::fs::rename(&foreign, &inside).unwrap();
10934        crate::subagent::tests::git_in(
10935            &elsewhere.path().join("repository"),
10936            &["worktree", "repair", inside.to_str().unwrap()],
10937        );
10938        let outside = launch(
10939            &parent,
10940            SubagentGrant::new().with_committing_worktree(&inside),
10941        )
10942        .await
10943        .expect_err("the launcher cannot hand on git data it cannot write");
10944        assert!(
10945            matches!(outside, SubagentGrantError::OutsideAuthority(_)),
10946            "{outside}"
10947        );
10948    }
10949
10950    /// A subagent hands on only what it holds: commit where it was granted
10951    /// commit, and paths inside its own authority.
10952    #[cfg(unix)]
10953    #[tokio::test]
10954    async fn a_nested_launch_never_exceeds_its_launcher() {
10955        let dir = tempfile::tempdir().expect("temp dir should be created");
10956        let worktree = crate::subagent::tests::repository_with_linked_worktree(dir.path(), "four");
10957        let sibling = dir.path().join("sibling");
10958        std::fs::create_dir_all(&sibling).unwrap();
10959        let parent = authority_terminal(dir.path()).await;
10960
10961        let writer = launch(&parent, SubagentGrant::new().with_worktree(&worktree))
10962            .await
10963            .unwrap();
10964        let escalated = launch(
10965            &writer,
10966            SubagentGrant::new().with_committing_worktree(&worktree),
10967        )
10968        .await
10969        .expect_err("a subagent without commit cannot grant it");
10970        assert!(
10971            matches!(escalated, SubagentGrantError::CommitOutsideAuthority(_)),
10972            "{escalated}"
10973        );
10974        let sideways = launch(&writer, SubagentGrant::new().with_worktree(&sibling))
10975            .await
10976            .expect_err("a subagent cannot grant what it cannot write");
10977        assert!(
10978            matches!(sideways, SubagentGrantError::OutsideAuthority(_)),
10979            "{sideways}"
10980        );
10981
10982        let committer = launch(
10983            &parent,
10984            SubagentGrant::new().with_committing_worktree(&worktree),
10985        )
10986        .await
10987        .unwrap();
10988        let handed_on = launch(
10989            &committer,
10990            SubagentGrant::new().with_committing_worktree(&worktree),
10991        )
10992        .await
10993        .expect("a subagent hands on the commit grant it holds");
10994        assert_eq!(
10995            handed_on.grants().snapshot().writable,
10996            committer.grants().snapshot().writable
10997        );
10998        assert!(handed_on.working_dir().starts_with(committer.working_dir()));
10999    }
11000
11001    /// A terminal that approves unsafe scripts.
11002    #[cfg(unix)]
11003    async fn unsafe_terminal(dir: &Path) -> Shell<executor_core::tokio::TokioGlobal> {
11004        fresh_terminal(dir).await.with_approver(ApproveAll)
11005    }
11006
11007    /// Runs an approved unsafe `script` to its end and renders the result.
11008    #[cfg(unix)]
11009    async fn run_unsafe(tool: &Shell<executor_core::tokio::TokioGlobal>, script: &str) -> String {
11010        let result = tool
11011            .call(
11012                ShellArgs {
11013                    sandbox: SandboxMode::Unsandboxed,
11014                    ..terminal_args("unsafe probe", script)
11015                },
11016                ToolContext::new(),
11017            )
11018            .await
11019            .expect("the unsafe call succeeds");
11020        render_terminal_result(&result)
11021    }
11022
11023    /// An approved unsafe script reads a file its sandboxed sibling cannot:
11024    /// host access grants the invoking user's whole filesystem, not a grant
11025    /// list.
11026    #[cfg(unix)]
11027    #[tokio::test]
11028    async fn an_unsafe_script_reads_a_file_outside_every_grant() {
11029        let session = tempfile::tempdir().expect("temp dir should be created");
11030        let home = tempfile::Builder::new()
11031            .prefix("aither-unsafe-home-")
11032            .tempdir_in(std::env::var_os("HOME").expect("HOME is set"))
11033            .expect("a temp dir under the real home");
11034        let secret = home.path().join("secret.txt");
11035        std::fs::write(&secret, "token-value").expect("secret written");
11036        let tool = unsafe_terminal(session.path()).await;
11037
11038        let result = run_unsafe(&tool, &format!("cat {}", secret.display())).await;
11039
11040        assert!(
11041            result.contains("token-value"),
11042            "the unsafe run read the file: {result}"
11043        );
11044    }
11045
11046    /// Host access also writes wherever the invoking user may write.
11047    #[cfg(unix)]
11048    #[tokio::test]
11049    async fn an_unsafe_script_writes_a_file_outside_every_grant() {
11050        let session = tempfile::tempdir().expect("temp dir should be created");
11051        let outside = tempfile::tempdir().expect("temp dir should be created");
11052        let probe = outside.path().join("written.txt");
11053        let tool = unsafe_terminal(session.path()).await;
11054
11055        let result = run_unsafe(&tool, &format!("printf %s written > {}", probe.display())).await;
11056
11057        assert!(
11058            !result.contains("Exit code"),
11059            "the unsafe run failed: {result}"
11060        );
11061        assert_eq!(
11062            std::fs::read_to_string(&probe).expect("written file reads back"),
11063            "written"
11064        );
11065    }
11066
11067    /// Confined profiles deny exec in the shared temp directories; host access
11068    /// runs what a user put there.
11069    #[cfg(unix)]
11070    #[tokio::test]
11071    async fn an_unsafe_script_executes_a_program_written_to_the_temp_directory() {
11072        let session = tempfile::tempdir().expect("temp dir should be created");
11073        let outside = tempfile::tempdir().expect("temp dir should be created");
11074        let probe = outside.path().join("probe.sh");
11075        std::fs::write(&probe, "#!/bin/sh\necho executed\n").expect("probe written");
11076        let tool = unsafe_terminal(session.path()).await;
11077
11078        let result = run_unsafe(&tool, &format!("chmod +x {0} && {0}", probe.display())).await;
11079
11080        assert!(
11081            result.contains("executed"),
11082            "the unsafe run ran the probe: {result}"
11083        );
11084    }
11085
11086    /// No proxy stands between an unsafe script and the network: a loopback
11087    /// listener the test binds accepts its connection directly.
11088    #[cfg(unix)]
11089    #[tokio::test]
11090    async fn an_unsafe_script_connects_to_loopback_without_a_proxy() {
11091        let session = tempfile::tempdir().expect("temp dir should be created");
11092        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
11093        let port = listener.local_addr().expect("local addr").port();
11094        let (accepted, got) = std::sync::mpsc::channel();
11095        std::thread::spawn(move || {
11096            let _ = accepted.send(listener.accept());
11097        });
11098        let tool = unsafe_terminal(session.path()).await;
11099
11100        let result = run_unsafe(
11101            &tool,
11102            &format!("/bin/bash -c 'exec 3<>/dev/tcp/127.0.0.1/{port}'"),
11103        )
11104        .await;
11105
11106        assert!(
11107            !result.contains("Exit code"),
11108            "the unsafe run failed: {result}"
11109        );
11110        got.recv_timeout(Duration::from_secs(10))
11111            .expect("the listener accepted the connection")
11112            .expect("accept succeeded");
11113    }
11114
11115    #[tokio::test]
11116    async fn a_subagent_of_a_subagent_works_inside_its_launchers_space() {
11117        let dir = tempfile::tempdir().expect("temp dir should be created");
11118        let parent = fresh_terminal(dir.path()).await;
11119        let child = launch(&parent, SubagentGrant::new()).await.unwrap();
11120        let grandchild = launch(&child, SubagentGrant::new()).await.unwrap();
11121        assert!(grandchild.working_dir().starts_with(child.working_dir()));
11122    }
11123
11124    // ---- terminal runner ----------------------------------------------------
11125
11126    /// Runs a script on `terminal` and answers with how the script ended and
11127    /// what it printed.
11128    #[cfg(unix)]
11129    async fn run_check_probe(
11130        terminal: &ConfiguredTestTool,
11131        dir: &Path,
11132        script: &str,
11133        timeout: u64,
11134    ) -> String {
11135        let result = terminal
11136            .run(Script::new(script, dir, Duration::from_secs(timeout)))
11137            .await
11138            .expect("the run ends");
11139        match (&result.outcome, &result.stdout) {
11140            (crate::RunOutcome::Exited { code }, CommandStream::Inline { text }) => {
11141                format!("exit={code} stdout={text}")
11142            }
11143            (crate::RunOutcome::Killed(_), _) => "killed".to_string(),
11144            other => panic!("a run ends exited with inline output or killed: {other:?}"),
11145        }
11146    }
11147
11148    /// A run executes a script on the shell, under its policy as it stands at
11149    /// the run: a grant made after the registry was bound included.
11150    #[cfg(unix)]
11151    #[tokio::test(flavor = "multi_thread")]
11152    async fn a_run_executes_a_script_under_the_shells_policy() {
11153        let dir = tempfile::tempdir().expect("temp dir should be created");
11154        let clone = tempfile::tempdir().expect("clone dir should be created");
11155        let read_only = tempfile::tempdir().expect("read-only dir should be created");
11156        let terminal = fresh_terminal(dir.path()).await;
11157        terminal.grants().add_readable(read_only.path());
11158        terminal.grants().add_writable(clone.path());
11159
11160        let clone_dir = std::fs::canonicalize(clone.path()).unwrap();
11161        let answer = run_check_probe(&terminal, &clone_dir, "pwd && touch checked", 30).await;
11162        assert!(answer.starts_with("exit=0 "), "{answer}");
11163        assert!(
11164            answer.contains(clone_dir.to_str().unwrap()),
11165            "the run starts in the directory it names: {answer}"
11166        );
11167        assert!(clone_dir.join("checked").exists());
11168
11169        let read_only_dir = std::fs::canonicalize(read_only.path()).unwrap();
11170        let answer = run_check_probe(&terminal, &read_only_dir, "touch denied", 30).await;
11171        assert!(
11172            !answer.starts_with("exit=0 "),
11173            "a read-only grant stays read-only: {answer}"
11174        );
11175        assert!(!read_only_dir.join("denied").exists());
11176
11177        let answer = run_check_probe(&terminal, &clone_dir, "sleep 30", 1).await;
11178        assert_eq!(answer, "killed", "the timeout kills the run");
11179
11180        let unsafe_run = terminal
11181            .run(
11182                Script::new("true", &clone_dir, Duration::from_secs(30))
11183                    .with_sandbox(SandboxMode::Unsandboxed),
11184            )
11185            .await;
11186        assert!(
11187            matches!(
11188                unsafe_run,
11189                Err(ShellRunError::Terminal(TerminalError::NoApprover(_)))
11190            ),
11191            "an unsafe run is put to an approver, and this terminal has none: {unsafe_run:?}"
11192        );
11193    }
11194
11195    /// Records the script every container exec runs.
11196    #[cfg(unix)]
11197    struct RecordingExec {
11198        scripts: Arc<std::sync::Mutex<Vec<String>>>,
11199    }
11200
11201    #[cfg(unix)]
11202    impl crate::ContainerExec for RecordingExec {
11203        fn exec(
11204            &self,
11205            _container_id: &str,
11206            script: &str,
11207            _working_dir: &str,
11208            _kill_rx: Receiver<()>,
11209            _stdin_rx: Receiver<Vec<u8>>,
11210            _lifetime: ExecLifetime,
11211        ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
11212        {
11213            self.scripts.lock().unwrap().push(script.to_string());
11214            std::future::ready(Ok(ContainerExecOutcome::Completed {
11215                output: std::process::Output {
11216                    status: std::os::unix::process::ExitStatusExt::from_raw(0),
11217                    stdout: Vec::new(),
11218                    stderr: Vec::new(),
11219                },
11220                killed: Vec::new(),
11221            }))
11222        }
11223
11224        fn exec_streamed(
11225            &self,
11226            _container_id: &str,
11227            script: &str,
11228            _working_dir: &str,
11229            _kill_rx: Receiver<()>,
11230            _stdin_rx: Receiver<Vec<u8>>,
11231            _stdout: Sender<Vec<u8>>,
11232            _lifetime: ExecLifetime,
11233        ) -> impl std::future::Future<Output = Result<ContainerExecOutcome, String>> + Send
11234        {
11235            self.scripts.lock().unwrap().push(script.to_string());
11236            std::future::ready(Ok(ContainerExecOutcome::Completed {
11237                output: std::process::Output {
11238                    status: std::os::unix::process::ExitStatusExt::from_raw(0),
11239                    stdout: Vec::new(),
11240                    stderr: Vec::new(),
11241                },
11242                killed: Vec::new(),
11243            }))
11244        }
11245    }
11246
11247    /// A terminal whose home backend is a recording container, which mounts
11248    /// `workspace` as `/workspace` when one is given.
11249    #[cfg(unix)]
11250    async fn recording_container_terminal(
11251        dir: &Path,
11252        workspace: Option<&Path>,
11253    ) -> (Arc<std::sync::Mutex<Vec<String>>>, ConfiguredTestTool) {
11254        let scripts = Arc::new(std::sync::Mutex::new(Vec::new()));
11255        let runtime = ContainerShellRuntime::new(
11256            "aither-test-confinement",
11257            crate::HostRoute::new(
11258                "host.docker.internal",
11259                std::net::IpAddr::from([127, 0, 0, 1]),
11260            )
11261            .expect("loopback is routable"),
11262            crate::AnyContainerExec::new(Arc::new(RecordingExec {
11263                scripts: scripts.clone(),
11264            })),
11265        );
11266        let runtime = match workspace {
11267            Some(workspace) => runtime.with_workspace_mount(MountRoot::new(
11268                workspace,
11269                ContainerPath::new(CONTAINER_EXEC_WORKING_DIR).expect("the workspace is absolute"),
11270            )),
11271            None => runtime,
11272        };
11273        let sandbox = container_sandbox(&runtime, dir);
11274        let parent = Shell::new_exact_on(
11275            sandbox,
11276            executor_core::tokio::TokioGlobal,
11277            crate::limits::fixture::limits(),
11278            crate::output_policy::fixture::policy(),
11279            TestWording::any(),
11280            crate::test_wording::job_tools(),
11281        )
11282        .await
11283        .expect("terminal tool should initialize");
11284        (scripts, parent)
11285    }
11286
11287    /// A container terminal's jobs are the container's: they carry the
11288    /// marker its memory reader finds them by, are registered as running
11289    /// there, and the terminal judges the container's memory too.
11290    #[cfg(unix)]
11291    #[tokio::test(flavor = "multi_thread")]
11292    async fn container_jobs_are_marked_and_placed_in_the_container() {
11293        let dir = tempfile::tempdir().expect("temp dir should be created");
11294        let (scripts, parent) = recording_container_terminal(dir.path(), None).await;
11295        assert!(parent.container_probe().is_some());
11296        assert!(parent.job_memory().has_container());
11297
11298        // A background job, whose completion is held so the registry still
11299        // keeps it to be read.
11300        let receiver = parent.background_receiver();
11301        parent
11302            .run_background(background_args("mark", "echo marked-command"))
11303            .await
11304            .expect("terminal call should succeed");
11305        let task_id = started_task_id(&receiver);
11306        let _completed = wait_for_completed_task(&receiver, &task_id).await;
11307
11308        let scripts = scripts.lock().unwrap().clone();
11309        let script = scripts
11310            .iter()
11311            .find(|script| script.contains("marked-command"))
11312            .expect("the command ran");
11313        let jobs = parent.job_registry().list().await;
11314        let job = jobs
11315            .iter()
11316            .find(|job| job.script == "echo marked-command")
11317            .expect("the job is registered");
11318        assert_eq!(job.place, crate::JobPlace::Container);
11319        // The sandbox exports it ahead of the command, which the managed
11320        // shell's command line quotes.
11321        assert!(
11322            script.contains(&format!("export {}=", crate::memory::JOB_MARKER_ENV))
11323                && script.contains(job.task_id.as_str()),
11324            "{script}"
11325        );
11326    }
11327
11328    #[cfg(unix)]
11329    #[tokio::test(flavor = "multi_thread")]
11330    async fn a_local_terminal_judges_no_container() {
11331        let dir = tempfile::tempdir().expect("temp dir should be created");
11332        let tool = configured_test_terminal(
11333            dir.path(),
11334            Duration::from_secs(10),
11335            Duration::from_secs(60),
11336            Duration::from_secs(600),
11337        )
11338        .await;
11339        assert!(tool.container_probe().is_none());
11340        assert!(!tool.job_memory().has_container());
11341    }
11342
11343    #[cfg(unix)]
11344    #[tokio::test(flavor = "multi_thread")]
11345    async fn container_session_runs_the_main_agent_unconfined_and_a_subagent_confined() {
11346        let dir = tempfile::tempdir().expect("temp dir should be created");
11347        let granted = dir.path().join("granted");
11348        std::fs::create_dir_all(&granted).unwrap();
11349        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
11350        let child = launch(&parent, SubagentGrant::new().with_worktree(&granted))
11351            .await
11352            .expect("a directory inside the workspace can be granted");
11353
11354        assert_eq!(exit_code_of(&parent, "echo main-command").await, 0);
11355        assert_eq!(exit_code_of(&child, "echo subagent-command").await, 0);
11356
11357        let scripts = scripts.lock().unwrap().clone();
11358        let main = scripts
11359            .iter()
11360            .find(|script| script.contains("main-command"))
11361            .expect("the main agent's command ran");
11362        let sub = scripts
11363            .iter()
11364            .find(|script| script.contains("subagent-command"))
11365            .expect("the subagent's command ran");
11366        assert!(
11367            !main.contains(" run --"),
11368            "the container is the main agent's boundary: {main}"
11369        );
11370        assert!(
11371            sub.contains("\"$AITHER_HEEL_BIN\" run --working-dir"),
11372            "{sub}"
11373        );
11374        assert!(!sub.contains("--isolation permissive"), "{sub}");
11375        let root = dunce::canonicalize(dir.path()).unwrap();
11376        let space = child
11377            .working_dir()
11378            .strip_prefix(&root)
11379            .unwrap()
11380            .to_str()
11381            .unwrap();
11382        assert!(
11383            sub.contains(&format!("--working-dir '/workspace/{space}'")),
11384            "{sub}"
11385        );
11386        let granted_name = granted.file_name().unwrap().to_str().unwrap();
11387        assert!(
11388            sub.contains(&format!("--grant '/workspace/{granted_name}=rw'")),
11389            "{sub}"
11390        );
11391    }
11392
11393    /// The shim inside a container compares its working directory against
11394    /// the worktree map: the map must spell the paths the mount resolves —
11395    /// host spellings would leave the worktree unprotected, the `git` shim
11396    /// unable to hit it.
11397    #[cfg(unix)]
11398    #[tokio::test(flavor = "multi_thread")]
11399    async fn a_containers_git_map_spells_the_worktree_and_gitdir_the_container_way() {
11400        let dir = tempfile::tempdir().expect("temp dir should be created");
11401        let worktree =
11402            crate::subagent::tests::repository_with_linked_worktree(dir.path(), "mapped");
11403        let (scripts, parent) = recording_container_terminal(dir.path(), Some(dir.path())).await;
11404        let _child = launch(
11405            &parent,
11406            SubagentGrant::new().with_committing_worktree(&worktree),
11407        )
11408        .await
11409        .expect("the worktree can be granted with commit");
11410
11411        assert_eq!(exit_code_of(&parent, "echo mapped-worktree").await, 0);
11412
11413        let script = scripts
11414            .lock()
11415            .unwrap()
11416            .iter()
11417            .find(|script| script.contains("mapped-worktree"))
11418            .expect("the main agent's command ran")
11419            .clone();
11420        assert!(
11421            script.contains("export AITHER_GIT_WORKTREE_PATH_0=/workspace/mapped"),
11422            "{script}"
11423        );
11424        assert!(
11425            script.contains(
11426                "export AITHER_GIT_WORKTREE_GITDIR_0=/workspace/repository/.git/worktrees/mapped"
11427            ),
11428            "{script}"
11429        );
11430        let host = dunce::canonicalize(&worktree)
11431            .unwrap()
11432            .display()
11433            .to_string();
11434        assert!(
11435            !script.contains(&host),
11436            "the shim sees no host spelling: {script}"
11437        );
11438    }
11439
11440    /// A subagent whose paths the container cannot express is refused when
11441    /// it is launched, not when it first runs a command.
11442    #[cfg(unix)]
11443    #[tokio::test(flavor = "multi_thread")]
11444    async fn a_container_subagent_outside_the_workspace_mount_is_refused_at_launch() {
11445        let dir = tempfile::tempdir().expect("temp dir should be created");
11446        let mounted = dir.path().join("mounted");
11447        let granted = dir.path().join("granted");
11448        std::fs::create_dir_all(&mounted).unwrap();
11449        std::fs::create_dir_all(&granted).unwrap();
11450
11451        let (_scripts, parent) = recording_container_terminal(dir.path(), Some(&mounted)).await;
11452        let error = launch(&parent, SubagentGrant::new().with_worktree(&granted))
11453            .await
11454            .expect_err("the subagent's paths are not inside the mount");
11455        assert!(
11456            matches!(error, SubagentGrantError::OutsideContainerMount { .. }),
11457            "{error}"
11458        );
11459
11460        let (_scripts, unmounted) = recording_container_terminal(dir.path(), None).await;
11461        let error = launch(&unmounted, SubagentGrant::new())
11462            .await
11463            .expect_err("a container without a declared mount cannot confine a subagent");
11464        assert!(
11465            matches!(error, SubagentGrantError::NoContainerMount),
11466            "{error}"
11467        );
11468    }
11469
11470    /// A local terminal in `dir` under `policies`, for the script policy
11471    /// tests.
11472    #[cfg(unix)]
11473    async fn policy_tool(
11474        dir: &Path,
11475        policies: Vec<crate::AnyScriptPolicy>,
11476    ) -> Shell<executor_core::tokio::TokioGlobal> {
11477        fresh_terminal(dir).await.with_test_policies(policies)
11478    }
11479
11480    /// Refuses every shell script that runs `program`, and reports how each
11481    /// script it was asked about ended.
11482    struct RefuseProgram {
11483        program: &'static str,
11484        ends: async_channel::Sender<crate::ScriptOutcome>,
11485    }
11486
11487    impl RefuseProgram {
11488        fn refusal(&self) -> String {
11489            format!(
11490                "`{}` does not run here; kill the PID you started.",
11491                self.program
11492            )
11493        }
11494    }
11495
11496    impl crate::ScriptPolicy for RefuseProgram {
11497        type State = ();
11498
11499        fn check(
11500            &self,
11501            script: &crate::ScriptCheck<'_>,
11502            _state: &(),
11503        ) -> impl Future<Output = ScriptDecision> + Send {
11504            let runs = matches!(
11505                script.shell,
11506                Some(Ok(shell)) if shell.commands().iter().any(|command| command.program() == self.program)
11507            );
11508            std::future::ready(if runs {
11509                ScriptDecision::Refuse(ScriptRefusal::new(self.refusal()))
11510            } else {
11511                ScriptDecision::Pass
11512            })
11513        }
11514
11515        async fn ended(&self, end: &crate::ScriptEnd<'_>, _state: &()) {
11516            self.ends
11517                .send(end.outcome)
11518                .await
11519                .expect("the test holds the receiver");
11520        }
11521    }
11522
11523    /// Refuses a script identical to the agent's last one that exited 0;
11524    /// a script that failed is not remembered.
11525    struct RefuseRepeat;
11526
11527    #[derive(Default)]
11528    struct Repeats {
11529        /// Task id → script, for the scripts allowed and not yet ended.
11530        pending: std::sync::Mutex<std::collections::HashMap<String, String>>,
11531        last_success: std::sync::Mutex<Option<String>>,
11532    }
11533
11534    impl crate::ScriptPolicy for RefuseRepeat {
11535        type State = Repeats;
11536
11537        fn check(
11538            &self,
11539            script: &crate::ScriptCheck<'_>,
11540            state: &Repeats,
11541        ) -> impl Future<Output = ScriptDecision> + Send {
11542            let decision = if state.last_success.lock().unwrap().as_deref() == Some(script.script) {
11543                ScriptDecision::Refuse(ScriptRefusal::new(
11544                    "It would print what it printed last time.",
11545                ))
11546            } else {
11547                state
11548                    .pending
11549                    .lock()
11550                    .unwrap()
11551                    .insert(script.task_id.to_string(), script.script.to_string());
11552                ScriptDecision::Pass
11553            };
11554            std::future::ready(decision)
11555        }
11556
11557        fn ended(
11558            &self,
11559            end: &crate::ScriptEnd<'_>,
11560            state: &Repeats,
11561        ) -> impl Future<Output = ()> + Send {
11562            let script = state.pending.lock().unwrap().remove(end.task_id);
11563            if end.outcome == (crate::ScriptOutcome::Exited { code: 0 }) {
11564                *state.last_success.lock().unwrap() = script;
11565            }
11566            std::future::ready(())
11567        }
11568    }
11569
11570    /// A policy's refusal is what the caller reads, before any part of the
11571    /// script runs, in the foreground and the background alike; the policy
11572    /// is told the script never ran.
11573    #[cfg(unix)]
11574    #[tokio::test]
11575    async fn a_policy_refusal_reaches_the_caller_before_the_script_runs() {
11576        let dir = tempfile::tempdir().expect("temp dir should be created");
11577        let (ends, ended) = async_channel::unbounded();
11578        let policy = RefuseProgram {
11579            program: "pkill",
11580            ends,
11581        };
11582        let text = policy.refusal();
11583        let tool = policy_tool(dir.path(), vec![crate::AnyScriptPolicy::new(policy)]).await;
11584        let marker = dir.path().join("ran");
11585        let script = format!("touch {}; sudo env pkill anything", marker.display());
11586
11587        let error = tool
11588            .call(
11589                terminal_args("name-based kill", &script),
11590                ToolContext::new(),
11591            )
11592            .await
11593            .expect_err("the policy refuses the script");
11594        assert_eq!(error.to_string(), text);
11595        let refusal = error
11596            .downcast_ref::<ScriptRefusal>()
11597            .expect("the refusal stays typed for the agent loop");
11598        assert_eq!(refusal.text(), text);
11599        let error = tool
11600            .run_background(terminal_args("name-based kill", &script))
11601            .await
11602            .expect_err("the policy refuses the background script");
11603        assert_eq!(error.to_string(), text);
11604        assert!(!marker.exists(), "no part of a refused script runs");
11605        assert_eq!(ended.try_recv(), Ok(crate::ScriptOutcome::NotRun));
11606        assert_eq!(ended.try_recv(), Ok(crate::ScriptOutcome::NotRun));
11607
11608        let result = tool
11609            .call(
11610                terminal_args("mention a killer", "echo pkill; exit 3"),
11611                ToolContext::new(),
11612            )
11613            .await
11614            .expect("a script that only names the program runs");
11615        assert!(render_terminal_result(&result).contains("pkill"));
11616        assert_eq!(
11617            ended.try_recv(),
11618            Ok(crate::ScriptOutcome::Exited { code: 3 }),
11619            "the policy learns how the script ended before its result returns"
11620        );
11621    }
11622
11623    /// Records the directory each script started in and the one it ended in.
11624    struct RecordDirs {
11625        starts: async_channel::Sender<ScriptDir>,
11626        ends: async_channel::Sender<(ScriptDir, Carry)>,
11627    }
11628
11629    impl crate::ScriptPolicy for RecordDirs {
11630        type State = ();
11631
11632        async fn check(&self, script: &crate::ScriptCheck<'_>, (): &()) -> ScriptDecision {
11633            self.starts
11634                .send(script.start.clone())
11635                .await
11636                .expect("the test holds the receiver");
11637            ScriptDecision::Pass
11638        }
11639
11640        async fn ended(&self, end: &crate::ScriptEnd<'_>, (): &()) {
11641            self.ends
11642                .send((end.end.clone(), end.carry))
11643                .await
11644                .expect("the test holds the receiver");
11645        }
11646    }
11647
11648    /// A policy sees where each script starts: after a script that ran `cd`,
11649    /// the next starts in that directory, and the end directory of a script
11650    /// is the start directory of the next.
11651    #[cfg(unix)]
11652    #[tokio::test]
11653    async fn a_policy_sees_the_directory_a_script_starts_and_ends_in() {
11654        let dir = tempfile::tempdir().expect("temp dir should be created");
11655        let (starts_tx, starts) = async_channel::unbounded();
11656        let (ends_tx, ends) = async_channel::unbounded();
11657        let policy = RecordDirs {
11658            starts: starts_tx,
11659            ends: ends_tx,
11660        };
11661        let tool = policy_tool(dir.path(), vec![crate::AnyScriptPolicy::new(policy)]).await;
11662        let root = dunce::canonicalize(dir.path()).unwrap();
11663
11664        for (description, script) in [
11665            ("enter a directory", "mkdir sub && cd sub"),
11666            ("stay there", "true"),
11667            ("leave it", "cd .."),
11668            ("stay at the root", "true"),
11669        ] {
11670            tool.call(terminal_args(description, script), ToolContext::new())
11671                .await
11672                .expect("the script runs");
11673        }
11674
11675        let starts: Vec<_> = std::iter::from_fn(|| starts.try_recv().ok()).collect();
11676        let ends: Vec<_> = std::iter::from_fn(|| ends.try_recv().ok()).collect();
11677        let sub = root.join("sub");
11678        let host = |dir: &Path| ScriptDir::Host(dir.to_path_buf());
11679        assert_eq!(starts, [host(&root), host(&sub), host(&sub), host(&root)]);
11680        assert_eq!(
11681            ends,
11682            [
11683                (host(&sub), Carry::Moved),
11684                (host(&sub), Carry::Unchanged),
11685                (host(&root), Carry::Moved),
11686                (host(&root), Carry::Unchanged),
11687            ]
11688        );
11689        for ((end, _), next) in ends.iter().zip(&starts[1..]) {
11690            assert_eq!(end, next, "a script starts where the last ended");
11691        }
11692    }
11693
11694    /// `Carry` reports each of its cases: a script that moved the shell, left
11695    /// it where it started, failed after moving it, exited without a report,
11696    /// and one that runs in the background.
11697    #[cfg(unix)]
11698    #[tokio::test]
11699    async fn a_policy_is_told_what_each_script_did_to_the_carried_directory() {
11700        let dir = tempfile::tempdir().expect("temp dir should be created");
11701        let (starts_tx, _starts) = async_channel::unbounded();
11702        let (ends_tx, ends) = async_channel::unbounded();
11703        let policy = RecordDirs {
11704            starts: starts_tx,
11705            ends: ends_tx,
11706        };
11707        let tool = policy_tool(dir.path(), vec![crate::AnyScriptPolicy::new(policy)]).await;
11708        let root = dunce::canonicalize(dir.path()).unwrap();
11709        let sub = ScriptDir::Host(root.join("sub"));
11710
11711        for script in ["mkdir sub && cd sub", "true", "cd ..; false", "exit 0"] {
11712            tool.call(terminal_args("carry", script), ToolContext::new())
11713                .await
11714                .expect("the script runs");
11715        }
11716        // The call returns before a background script ends.
11717        tool.run_background(terminal_args("detach", "sleep 1"))
11718            .await
11719            .expect("the background script starts");
11720        assert!(
11721            ends.len() == 4,
11722            "a background script's end is told after its call returned"
11723        );
11724        let carries: Vec<_> = std::iter::from_fn(|| ends.try_recv().ok()).collect();
11725        assert_eq!(
11726            carries,
11727            [
11728                (sub.clone(), Carry::Moved),
11729                (sub.clone(), Carry::Unchanged),
11730                (sub.clone(), Carry::Reset(DirectoryResetReason::Failed)),
11731                (sub.clone(), Carry::Reset(DirectoryResetReason::Unreported)),
11732            ]
11733        );
11734        let background = tokio::time::timeout(Duration::from_secs(20), ends.recv())
11735            .await
11736            .expect("the background script ends")
11737            .expect("the test holds the sender");
11738        assert_eq!(background, (sub, Carry::NotCarried));
11739    }
11740
11741    /// Scripts started together start in the directory that was carried when
11742    /// each was admitted, and each reports an end directory that is a
11743    /// directory some script of the group settled, which the next script
11744    /// then starts in.
11745    #[cfg(unix)]
11746    #[tokio::test]
11747    async fn parallel_scripts_start_alike_and_the_next_starts_where_a_last_ended() {
11748        let dir = tempfile::tempdir().expect("temp dir should be created");
11749        let (starts_tx, starts) = async_channel::unbounded();
11750        let (ends_tx, ends) = async_channel::unbounded();
11751        let policy = RecordDirs {
11752            starts: starts_tx,
11753            ends: ends_tx,
11754        };
11755        let tool = policy_tool(dir.path(), vec![crate::AnyScriptPolicy::new(policy)]).await;
11756        let root = dunce::canonicalize(dir.path()).unwrap();
11757
11758        let calls = ["a", "b", "c", "d"].map(|name| {
11759            let tool = &tool;
11760            async move {
11761                tool.call(
11762                    terminal_args("enter", &format!("mkdir -p {name} && cd {name}")),
11763                    ToolContext::new(),
11764                )
11765                .await
11766                .expect("the script runs");
11767            }
11768        });
11769        futures::future::join_all(calls).await;
11770        let starts: Vec<_> = std::iter::from_fn(|| starts.try_recv().ok()).collect();
11771        assert_eq!(starts, vec![ScriptDir::Host(root.clone()); 4]);
11772        let ends: Vec<_> = std::iter::from_fn(|| ends.try_recv().ok()).collect();
11773        assert_eq!(ends.len(), 4);
11774        let settled = ["a", "b", "c", "d"].map(|name| ScriptDir::Host(root.join(name)));
11775        for (end, carry) in &ends {
11776            assert!(settled.contains(end), "{end:?}");
11777            assert_eq!(*carry, Carry::Moved);
11778        }
11779
11780        tool.call(terminal_args("next", "true"), ToolContext::new())
11781            .await
11782            .expect("the script runs");
11783        let next = starts_after(&tool).await;
11784        assert!(ends.iter().any(|(end, _)| *end == next));
11785    }
11786
11787    /// The directory the terminal's next foreground script starts in.
11788    #[cfg(unix)]
11789    async fn starts_after(tool: &Shell<executor_core::tokio::TokioGlobal>) -> ScriptDir {
11790        carried_start(tool.carried_dir.as_ref()).await.map_or_else(
11791            || ScriptDir::Host(tool.working_dir.clone()),
11792            ScriptDir::Host,
11793        )
11794    }
11795
11796    /// Two policies that disagree resolve to the strictest decision: a
11797    /// refusal outranks an approval, wherever they stand in the registry.
11798    #[cfg(unix)]
11799    #[tokio::test]
11800    async fn policies_that_disagree_resolve_to_the_strictest_decision() {
11801        let dir = tempfile::tempdir().expect("temp dir should be created");
11802        let tool = approval_tool(
11803            dir.path(),
11804            [
11805                ScriptDecision::Refuse(ScriptRefusal::new("refused by the second")),
11806                ScriptDecision::Allow,
11807            ],
11808            None,
11809        )
11810        .await;
11811        let error = tool
11812            .call(terminal_args("disagree", "true"), ToolContext::new())
11813            .await
11814            .expect_err("the refusal outranks the approval");
11815        assert_eq!(error.to_string(), "refused by the second");
11816    }
11817
11818    /// With no policy the sandbox refuses nothing: `grep` and a foreground
11819    /// `sleep` run.
11820    #[cfg(unix)]
11821    #[tokio::test]
11822    async fn with_no_policy_grep_and_a_foreground_sleep_run() {
11823        let dir = tempfile::tempdir().expect("temp dir should be created");
11824        let tool = policy_tool(dir.path(), Vec::new()).await;
11825        let result = tool
11826            .call(
11827                terminal_args(
11828                    "grep and sleep",
11829                    "printf 'needle\\n' | grep needle; sleep 1; echo slept",
11830                ),
11831                ToolContext::new(),
11832            )
11833            .await
11834            .expect("nothing is refused");
11835        let rendered = render_terminal_result(&result);
11836        assert!(rendered.contains("needle"), "{rendered}");
11837        assert!(rendered.contains("slept"), "{rendered}");
11838    }
11839
11840    /// A policy keeps state for its agent across calls, and learns of each
11841    /// end before the call returns: a repeat of a script that succeeded is
11842    /// refused, a failed one runs again.
11843    #[cfg(unix)]
11844    #[tokio::test]
11845    async fn a_policy_state_follows_each_script_to_its_end() {
11846        let dir = tempfile::tempdir().expect("temp dir should be created");
11847        let tool = policy_tool(dir.path(), vec![crate::AnyScriptPolicy::new(RefuseRepeat)]).await;
11848        assert_eq!(exit_code_of(&tool, "exit 3").await, 3);
11849        assert_eq!(
11850            exit_code_of(&tool, "exit 3").await,
11851            3,
11852            "a failed script is not remembered, so it runs again"
11853        );
11854        assert_eq!(exit_code_of(&tool, "echo once").await, 0);
11855        let error = tool
11856            .call(terminal_args("again", "echo once"), ToolContext::new())
11857            .await
11858            .expect_err("a repeat of a successful script is refused");
11859        assert!(error.downcast_ref::<ScriptRefusal>().is_some(), "{error}");
11860        assert_eq!(exit_code_of(&tool, "echo twice").await, 0);
11861    }
11862
11863    use crate::monitor::{MonitorArgs, MonitorEnd, MonitorSource, MonitorTool};
11864
11865    /// Job alerts the monitor produces until `ended` or `duration` passes.
11866    async fn monitor_alerts(receiver: &ShellEvents, duration: Duration) -> Vec<ShellEvent> {
11867        let deadline = std::time::Instant::now() + duration;
11868        let mut alerts = Vec::new();
11869        while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
11870            let Some(alert) = receiver.recv_timeout(remaining).await else {
11871                break;
11872            };
11873            if matches!(alert, ShellEvent::JobEnded(_) | ShellEvent::JobStarted(_)) {
11874                continue;
11875            }
11876            let ended = matches!(alert, ShellEvent::MonitorEnded(_));
11877            alerts.push(alert);
11878            if ended {
11879                break;
11880            }
11881        }
11882        alerts
11883    }
11884
11885    fn monitor_command(command: &str, timeout_secs: u64) -> MonitorArgs {
11886        MonitorArgs {
11887            source: MonitorSource::Command {
11888                command: command.to_string(),
11889                interpreter: Interpreter::Shell,
11890            },
11891            interval_secs: Some(1),
11892            filter: None,
11893            stop_on: None,
11894            kill_on_stop: false,
11895            stall_secs: None,
11896            timeout_secs,
11897        }
11898    }
11899
11900    #[cfg(unix)]
11901    #[tokio::test(flavor = "multi_thread")]
11902    async fn monitored_command_delivers_increments_and_its_exit() {
11903        let dir = tempfile::tempdir().unwrap();
11904        let tool = configured_test_terminal(
11905            dir.path(),
11906            Duration::from_secs(10),
11907            Duration::from_secs(7200),
11908            Duration::from_secs(600),
11909        )
11910        .await;
11911        let monitor = MonitorTool::new(tool.clone(), crate::monitor::fixture_settings());
11912        monitor
11913            .call(
11914                monitor_command("echo a; sleep 2; echo b", 30),
11915                ToolContext::new(),
11916            )
11917            .await
11918            .expect("monitor starts");
11919
11920        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(20)).await;
11921        let increments: Vec<&[String]> = alerts
11922            .iter()
11923            .filter_map(|alert| match alert {
11924                ShellEvent::MonitorIncrement(increment) => Some(increment.lines.as_slice()),
11925                _ => None,
11926            })
11927            .collect();
11928        assert!(
11929            increments.iter().any(|inc| *inc == ["a".to_string()]),
11930            "the first line is delivered as it arrives: {alerts:?}"
11931        );
11932        assert!(
11933            increments.iter().any(|inc| *inc == ["b".to_string()]),
11934            "the later line is delivered in a following increment: {alerts:?}"
11935        );
11936        assert!(
11937            alerts.iter().any(|alert| matches!(
11938                alert,
11939                ShellEvent::MonitorEnded(ended)
11940                    if matches!(ended.end, MonitorEnd::Exited { exit_code: 0 })
11941            )),
11942            "the monitor reports the command's exit: {alerts:?}"
11943        );
11944    }
11945
11946    #[cfg(unix)]
11947    #[tokio::test(flavor = "multi_thread")]
11948    async fn monitor_filter_keeps_matching_lines_and_stop_on_ends() {
11949        let dir = tempfile::tempdir().unwrap();
11950        let tool = configured_test_terminal(
11951            dir.path(),
11952            Duration::from_secs(10),
11953            Duration::from_secs(7200),
11954            Duration::from_secs(600),
11955        )
11956        .await;
11957        let monitor = MonitorTool::new(tool.clone(), crate::monitor::fixture_settings());
11958        let mut args = monitor_command(
11959            "printf 'keep one\\ndrop\\nkeep two\\nlast\\n'; sleep 60",
11960            30,
11961        );
11962        args.filter = Some("^keep".to_string());
11963        args.stop_on = Some("two".to_string());
11964        monitor
11965            .call(args, ToolContext::new())
11966            .await
11967            .expect("monitor starts");
11968
11969        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(20)).await;
11970        let lines: Vec<&String> = alerts
11971            .iter()
11972            .filter_map(|alert| match alert {
11973                ShellEvent::MonitorIncrement(increment) => Some(&increment.lines),
11974                _ => None,
11975            })
11976            .flatten()
11977            .collect();
11978        assert!(
11979            lines.iter().all(|line| line.starts_with("keep")),
11980            "filter drops non-matching lines: {lines:?}"
11981        );
11982        assert!(
11983            !lines.iter().any(|line| *line == "last"),
11984            "lines after the stop match are not delivered: {lines:?}"
11985        );
11986        assert!(
11987            alerts.iter().any(|alert| matches!(
11988                alert,
11989                ShellEvent::MonitorEnded(ended)
11990                    if matches!(&ended.end, MonitorEnd::StopMatched { line } if line == "keep two")
11991            )),
11992            "the first stop_on match ends the monitor: {alerts:?}"
11993        );
11994        tool.job_registry().kill_running().await;
11995    }
11996
11997    #[cfg(unix)]
11998    #[tokio::test(flavor = "multi_thread")]
11999    async fn monitor_rejects_a_timeout_over_the_cap_and_times_out_at_the_deadline() {
12000        let dir = tempfile::tempdir().unwrap();
12001        let tool = configured_test_terminal(
12002            dir.path(),
12003            Duration::from_secs(10),
12004            Duration::from_secs(7200),
12005            Duration::from_secs(600),
12006        )
12007        .await;
12008        let monitor = MonitorTool::new(tool.clone(), crate::monitor::fixture_settings());
12009        let refused = monitor
12010            .call(monitor_command("sleep 60", 7201), ToolContext::new())
12011            .await;
12012        assert!(refused.is_err(), "timeout_secs over the cap is refused");
12013
12014        monitor
12015            .call(monitor_command("sleep 60", 2), ToolContext::new())
12016            .await
12017            .expect("monitor starts");
12018        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
12019        assert!(
12020            alerts.iter().any(|alert| matches!(
12021                alert,
12022                ShellEvent::MonitorEnded(ended) if matches!(ended.end, MonitorEnd::TimedOut)
12023            )),
12024            "the deadline kills the run and reports a timeout: {alerts:?}"
12025        );
12026    }
12027
12028    /// The watched job's bound stays a margin past the monitor's deadline, so
12029    /// the largest monitor is the shell's cap less that margin, and one past
12030    /// it is refused up front instead of failing to start the job.
12031    #[cfg(unix)]
12032    #[tokio::test(flavor = "multi_thread")]
12033    async fn the_largest_monitor_leaves_the_jobs_margin_inside_the_shells_cap() {
12034        let dir = tempfile::tempdir().unwrap();
12035        let tool = configured_test_terminal(
12036            dir.path(),
12037            Duration::from_secs(10),
12038            Duration::from_secs(7200),
12039            Duration::from_secs(600),
12040        )
12041        .await;
12042        let monitor = MonitorTool::new(tool.clone(), crate::monitor::fixture_settings());
12043        monitor
12044            .call(monitor_command("sleep 60", 7140), ToolContext::new())
12045            .await
12046            .expect("a monitor whose job bound fits the cap starts");
12047        let refused = monitor
12048            .call(monitor_command("sleep 60", 7141), ToolContext::new())
12049            .await;
12050        assert!(refused.is_err(), "its job's bound would pass the cap");
12051        tool.jobs().kill_all().await;
12052    }
12053
12054    #[cfg(unix)]
12055    #[tokio::test(flavor = "multi_thread")]
12056    async fn monitor_reports_a_stall_once() {
12057        let dir = tempfile::tempdir().unwrap();
12058        let tool = configured_test_terminal(
12059            dir.path(),
12060            Duration::from_secs(10),
12061            Duration::from_secs(7200),
12062            Duration::from_secs(600),
12063        )
12064        .await;
12065        let monitor = MonitorTool::new(tool.clone(), crate::monitor::fixture_settings());
12066        let mut args = monitor_command("sleep 4; echo done", 30);
12067        args.stall_secs = Some(1);
12068        monitor
12069            .call(args, ToolContext::new())
12070            .await
12071            .expect("monitor starts");
12072
12073        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
12074        let stalls = alerts
12075            .iter()
12076            .filter(|alert| matches!(alert, ShellEvent::MonitorStalled(_)))
12077            .count();
12078        assert_eq!(stalls, 1, "a stall is reported once: {alerts:?}");
12079    }
12080
12081    #[cfg(unix)]
12082    #[tokio::test(flavor = "multi_thread")]
12083    async fn monitored_file_delivers_appends_and_refuses_an_unreadable_file() {
12084        let dir = tempfile::tempdir().unwrap();
12085        let tool = configured_test_terminal(
12086            dir.path(),
12087            Duration::from_secs(10),
12088            Duration::from_secs(7200),
12089            Duration::from_secs(600),
12090        )
12091        .await;
12092        let monitor = MonitorTool::new(tool.clone(), crate::monitor::fixture_settings());
12093        let unreadable = monitor
12094            .call(
12095                MonitorArgs {
12096                    source: MonitorSource::File {
12097                        file: "/etc/sudoers".to_string(),
12098                    },
12099                    ..monitor_command("true", 30)
12100                },
12101                ToolContext::new(),
12102            )
12103            .await;
12104        assert!(
12105            unreadable.is_err(),
12106            "a file the sandbox may not read is refused"
12107        );
12108
12109        let path = tool.working_dir().join("followed.log");
12110        std::fs::write(&path, "existing\n").unwrap();
12111        monitor
12112            .call(
12113                MonitorArgs {
12114                    source: MonitorSource::File {
12115                        file: "followed.log".to_string(),
12116                    },
12117                    ..monitor_command("true", 30)
12118                },
12119                ToolContext::new(),
12120            )
12121            .await
12122            .expect("monitor starts");
12123        async_io::Timer::after(Duration::from_millis(1500)).await;
12124        let mut file = std::fs::OpenOptions::new()
12125            .append(true)
12126            .open(&path)
12127            .unwrap();
12128        std::io::Write::write_all(&mut file, b"appended\n").unwrap();
12129        std::fs::rename(&path, tool.working_dir().join("followed.log.1")).unwrap();
12130        std::fs::write(&path, "rotated\n").unwrap();
12131        async_io::Timer::after(Duration::from_millis(500)).await;
12132        let mut file = std::fs::OpenOptions::new()
12133            .append(true)
12134            .open(&path)
12135            .unwrap();
12136        std::io::Write::write_all(&mut file, b"after\n").unwrap();
12137
12138        let alerts = monitor_alerts(&tool.background_receiver(), Duration::from_secs(15)).await;
12139        let lines: Vec<&String> = alerts
12140            .iter()
12141            .filter_map(|alert| match alert {
12142                ShellEvent::MonitorIncrement(increment) => Some(&increment.lines),
12143                _ => None,
12144            })
12145            .flatten()
12146            .collect();
12147        assert!(
12148            !lines.iter().any(|line| *line == "existing"),
12149            "content written before the monitor started is not delivered: {lines:?}"
12150        );
12151        for expected in ["appended", "rotated", "after"] {
12152            assert!(
12153                lines.iter().any(|line| *line == expected),
12154                "appended line {expected:?} is delivered, across rotation: {lines:?}"
12155            );
12156        }
12157        tool.job_registry().kill_running().await;
12158    }
12159
12160    // ---- runtime grants -----------------------------------------------------
12161
12162    /// The done-when case: a writable grant added at runtime reaches every
12163    /// command launched afterwards, while a command already running keeps
12164    /// the grants it launched with.
12165    #[cfg(unix)]
12166    #[tokio::test(flavor = "multi_thread")]
12167    async fn a_runtime_writable_grant_reaches_new_commands_not_running_ones() {
12168        let dir = tempfile::tempdir().expect("temp dir should be created");
12169        let tool = authority_terminal(dir.path()).await;
12170        let outside = tempfile::tempdir().expect("outside dir should be created");
12171        let late_target = outside.path().join("late.txt");
12172        // Launched before the grant; its write happens after the grant is
12173        // added but its grant snapshot was taken at launch.
12174        let task_id = start_background_job(
12175            &tool,
12176            &format!("sleep 2; echo x > '{}'", late_target.display()),
12177        )
12178        .await;
12179        let receiver = tool.background_receiver();
12180
12181        assert_ne!(
12182            exit_code_of(
12183                &tool,
12184                &format!("echo x > '{}'", outside.path().join("denied.txt").display())
12185            )
12186            .await,
12187            0,
12188            "a write outside the sandbox is denied before the grant"
12189        );
12190        tool.grants().add_writable(outside.path());
12191        assert_eq!(
12192            exit_code_of(
12193                &tool,
12194                &format!(
12195                    "echo x > '{}'",
12196                    outside.path().join("granted.txt").display()
12197                )
12198            )
12199            .await,
12200            0,
12201            "the command after the grant writes the approved dir"
12202        );
12203
12204        let completed = wait_for_completed_task(&receiver, &task_id).await;
12205        let _ = completed.result;
12206        assert!(
12207            !late_target.exists(),
12208            "a command launched before the grant keeps its launch grants"
12209        );
12210    }
12211
12212    /// A grant taken back no longer reaches the next command: the write the
12213    /// grant allowed is denied again.
12214    #[cfg(unix)]
12215    #[tokio::test(flavor = "multi_thread")]
12216    async fn a_removed_grant_is_gone_from_the_next_command() {
12217        let dir = tempfile::tempdir().expect("temp dir should be created");
12218        let tool = authority_terminal(dir.path()).await;
12219        let outside = tempfile::tempdir().expect("outside dir should be created");
12220        tool.grants().add_writable(outside.path());
12221        assert_eq!(
12222            exit_code_of(
12223                &tool,
12224                &format!("touch '{}'", outside.path().join("granted.txt").display())
12225            )
12226            .await,
12227            0,
12228            "the granted dir is writable"
12229        );
12230        tool.grants().revoke(outside.path());
12231        assert_ne!(
12232            exit_code_of(
12233                &tool,
12234                &format!("touch '{}'", outside.path().join("revoked.txt").display())
12235            )
12236            .await,
12237            0,
12238            "the command after the removal is denied the write"
12239        );
12240    }
12241
12242    /// A writable grant deleted mid-session no longer fails admission, and
12243    /// the alert fires when it was the directory the shell had carried.
12244    #[cfg(unix)]
12245    #[tokio::test(flavor = "multi_thread")]
12246    async fn a_deleted_writable_grant_does_not_block_the_next_command() {
12247        let dir = tempfile::tempdir().expect("temp dir should be created");
12248        let (tool, ends) = carry_terminal(dir.path()).await;
12249        let root = dunce::canonicalize(dir.path()).unwrap();
12250        let outside = tempfile::tempdir().expect("outside dir should be created");
12251        let granted = dunce::canonicalize(outside.path()).unwrap();
12252        tool.grants().add_writable(&granted);
12253        assert_eq!(
12254            exit_code_of(&tool, &format!("cd '{}'", granted.display())).await,
12255            0
12256        );
12257        assert_eq!(
12258            carries(&ends),
12259            [(ScriptDir::Host(granted.clone()), Carry::Moved)]
12260        );
12261
12262        std::fs::remove_dir_all(&granted).unwrap();
12263        assert_eq!(exit_code_of(&tool, "echo test").await, 0);
12264        assert_eq!(
12265            carries(&ends),
12266            [(
12267                ScriptDir::Host(root.clone()),
12268                Carry::Reset(DirectoryResetReason::Removed)
12269            )]
12270        );
12271        assert_eq!(pwd_of(&tool).await, root);
12272    }
12273
12274    /// A read-only grant deleted mid-session grants nothing and no longer
12275    /// fails the sandbox setup of the next command.
12276    #[cfg(unix)]
12277    #[tokio::test(flavor = "multi_thread")]
12278    async fn a_deleted_readable_grant_does_not_block_the_next_command() {
12279        let dir = tempfile::tempdir().expect("temp dir should be created");
12280        let tool = authority_terminal(dir.path()).await;
12281        let outside = tempfile::tempdir().expect("outside dir should be created");
12282        let granted = dunce::canonicalize(outside.path()).unwrap();
12283        tool.grants().add_readable(&granted);
12284        assert_eq!(exit_code_of(&tool, "echo test").await, 0);
12285
12286        std::fs::remove_dir_all(&granted).unwrap();
12287        assert_eq!(exit_code_of(&tool, "echo test").await, 0);
12288    }
12289
12290    /// Cloned terminals share one grant store: a grant added through the
12291    /// original's handle reaches the clone's next command.
12292    #[cfg(unix)]
12293    #[tokio::test(flavor = "multi_thread")]
12294    async fn a_cloned_terminal_sees_runtime_grants() {
12295        let dir = tempfile::tempdir().expect("temp dir should be created");
12296        let tool = authority_terminal(dir.path()).await;
12297        let clone = tool.clone();
12298        let outside = tempfile::tempdir().expect("outside dir should be created");
12299        tool.grants().add_writable(outside.path());
12300        assert_eq!(
12301            exit_code_of(
12302                &clone,
12303                &format!("touch '{}'", outside.path().join("shared.txt").display())
12304            )
12305            .await,
12306            0,
12307            "the clone's commands carry grants added through the original"
12308        );
12309    }
12310
12311    /// A subagent's derived grants follow its parent's readable list live:
12312    /// a readable grant added to the parent after the subagent launches is
12313    /// readable inside it; a writable grant on the parent never becomes
12314    /// writable in the subagent (it lands on the subagent's readable side).
12315    #[cfg(unix)]
12316    #[tokio::test(flavor = "multi_thread")]
12317    async fn a_subagent_sees_runtime_readable_but_never_writable_parent_grants() {
12318        let dir = tempfile::tempdir().expect("temp dir should be created");
12319        let parent = authority_terminal(dir.path()).await;
12320        let readable_dir = tempfile::tempdir().expect("readable dir");
12321        let writable_dir = tempfile::tempdir().expect("writable dir");
12322        std::fs::write(readable_dir.path().join("r.txt"), "data").unwrap();
12323        std::fs::write(writable_dir.path().join("w.txt"), "data").unwrap();
12324
12325        let child = launch(&parent, SubagentGrant::new())
12326            .await
12327            .expect("subagent launches");
12328        parent.grants().add_readable(readable_dir.path());
12329        parent.grants().add_writable(writable_dir.path());
12330
12331        assert_eq!(
12332            exit_code_of(
12333                &child,
12334                &format!("cat '{}'", readable_dir.path().join("r.txt").display())
12335            )
12336            .await,
12337            0,
12338            "a runtime readable grant on the parent reaches the subagent"
12339        );
12340        let denied_dir = tempfile::tempdir().expect("denied dir");
12341        std::fs::write(denied_dir.path().join("d.txt"), "data").unwrap();
12342        parent
12343            .grants()
12344            .deny_read(std::fs::canonicalize(denied_dir.path()).unwrap());
12345        assert_ne!(
12346            exit_code_of(
12347                &child,
12348                &format!("cat '{}'", denied_dir.path().join("d.txt").display())
12349            )
12350            .await,
12351            0,
12352            "a read denial added to the parent after launch reaches the subagent"
12353        );
12354        assert_ne!(
12355            exit_code_of(
12356                &child,
12357                &format!("touch '{}'", writable_dir.path().join("x.txt").display())
12358            )
12359            .await,
12360            0,
12361            "a parent writable grant is never writable inside the subagent"
12362        );
12363    }
12364
12365    /// A shell launched before the grant keeps the grants it started
12366    /// with — its sandbox was fixed when it spawned — while every new
12367    /// command picks the grant up (`add_writable` documents this).
12368    #[cfg(unix)]
12369    #[tokio::test(flavor = "multi_thread")]
12370    async fn a_running_shell_keeps_the_grants_it_started_with() {
12371        let dir = tempfile::tempdir().expect("temp dir should be created");
12372        let tool = authority_terminal(dir.path()).await;
12373        let outside = tempfile::tempdir().expect("outside dir should be created");
12374        let shell_target = outside.path().join("from_shell.txt");
12375
12376        // A shell session launched before the grant: its write lands after
12377        // the grant was added, but inside its launch-time sandbox.
12378        let task_id = start_background_job(
12379            &tool,
12380            &format!("sleep 2; touch '{}'", shell_target.display()),
12381        )
12382        .await;
12383        let receiver = tool.background_receiver();
12384        tool.grants().add_writable(outside.path());
12385        let fresh_target = outside.path().join("fresh.txt");
12386        assert_eq!(
12387            exit_code_of(&tool, &format!("touch '{}'", fresh_target.display())).await,
12388            0,
12389            "a fresh command picks up the grant"
12390        );
12391        let _ = wait_for_completed_task(&receiver, &task_id).await;
12392        assert!(
12393            !shell_target.exists(),
12394            "the shell launched before the grant is still sandboxed without it"
12395        );
12396    }
12397}