> ## Documentation Index
> Fetch the complete documentation index at: https://axe-engine.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Embed the engine in Rust

> Link the axe crate into your own agent: supervise processes, replay their output, and confine file access without running axed.

The `axe` crate is the engine `axed` runs, with no network code and no daemon.

> [!WARNING]
>
> `axe` builds on Linux only. On any other target the crate stops with `compile_error!("axe targets Linux")`. On macOS, build and run inside a Linux container, as described in [Develop on macOS](#develop-on-macos).

## Add the dependency

The crate is not published to crates.io. Add it as a git dependency. The package name is `axe`.

```toml Cargo.toml theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
[dependencies]
axe = { git = "https://github.com/vincent0426/axe" }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
libc = "0.2"   # only for signal numbers such as libc::SIGTERM
```

The engine runs on Tokio. `axe` enables the Tokio features it needs itself (`rt`, `net`, `io-util`, `sync`, `time`, `macros`). Your program needs a runtime to call it from. `rt-multi-thread` and `macros` give you `#[tokio::main]`. Creating the `Supervisor` needs no runtime, but call `Supervisor::spawn` from inside one, because the runtime drives every process it starts.

Pin a commit with `rev = "..."` if you want reproducible builds. The crate's minimum Rust version is 1.88 and it uses edition 2024.

## The engine owns `wait`

The engine reaps every child of your program from one thread with `wait4(-1)`. It also marks your program as a child subreaper, so orphaned grandchildren come back to it.

> [!WARNING]
>
> Never wait for children yourself. `std::process::Child::wait`, `waitpid` and `tokio::process` race with the engine's reaper. Either side can collect an exit the other is waiting for. Start every process through `Supervisor::spawn`.

## Core types

| Type | Module | What it is |
| - | - | - |
| `Supervisor` | `axe` | The registry of processes. Spawns, looks up, removes, freezes, and shuts down. Created with `Supervisor::new(Config, Option<Cgroups>)`, which returns `Result<Arc<Supervisor>>`. |
| `Config` | `axe` | Retention, budgets and table sizes. `Config::default()` matches `axed`'s defaults, except that `axed` sets `child_oom_score_adj` to 500. |
| `Command` | `axe` | What to run: `argv`, `env`, `cwd`, `stdio`, `limits`, `user`, `leftovers`. Build it with `Command::new(argv, cwd)` and set fields directly. |
| `WorkDir` | `axe` | A working directory inside a `Root`, from `root.dir(path)`. Only a `Root` can make one, so a `Command` always starts inside the workspace. |
| `SpawnOptions` | `axe` | How the supervisor tracks a spawn: `retain_bytes`, `keep`, `attach`, `name`, `request_id`, `labels`. |
| `Process`, `ProcessId` | `axe` | One supervised process, shared as `Arc<Process>`, and its identity: 128 random bits, printed as 32 hex digits. Read its state, open readers, write stdin, signal, resize, wait. |
| `Owned` | `axe` | A process tied to its caller: dropping it kills the tree if the process is still running, and the exit reports `ExitReason::OwnerGone`. |
| `Events`, `Event`, `Replay` | `axe` | A process's output followed by its exit, from `process.events(reader, replay)`. |
| `Captured`, `CaptureLimits` | `axe` | A run to completion with its output kept, from `supervisor.capture(command, limits)`, or `supervisor.capture_once(..)` to make it safe to retry. |
| `Exit`, `ExitStatus`, `ExitReason`, `Usage` | `axe` | How a process ended: status, why (`ExitReason`), CPU and memory totals, time. |
| `LiveUsage`, `UsageScope` | `axe` | What a running process uses now, from `process.usage()`, and whether that covers the tree or the leader. |
| `Reader`, `Item`, `Chunk`, `Delivery` | `axe::output` | A cursor into a process's output log. `Item::Chunk` carries bytes with their offset and stream; `Item::Gap` reports bytes evicted before you read them. `Delivery::Lossless` or `Delivery::Lossy` picks whether a reader may hold the process back. |
| `Root` | `axe::fs` | A directory every path is confined to. Opens, lists, creates, moves and removes files without letting a path or symlink leave it. |
| `PendingWrite` | `axe::fs` | A file being written that appears at its path only when you call `commit()`. |
| `Watcher` | `axe::watch` | Change notifications for a directory under a `Root`, over inotify. |
| `Lifecycle` | `axe::lifecycle` | Instance id, resume detection and running-time clock. Reach it with `supervisor.lifecycle()`. |
| `Cgroups` | `axe::cgroup` | A delegated cgroup v2 subtree, from `Cgroups::setup`. Gives whole-tree kill, memory, CPU and task limits, OOM detection and freezing. |
| `Error`, `Result` | `axe` | Fallible calls return `axe::Result<T>`, except `Watcher::next_batch`, which returns `std::io::Result`. `Error` is `#[non_exhaustive]`, so a `match` needs a fallback arm. See [Errors](https://axe-engine.mintlify.site/reference/errors.md). |

### How they fit

1. Open a `Root` for the workspace. Resolve working directories with `root.dir(path)`, which is the only way to get the `WorkDir` a `Command` needs.
2. Create one `Supervisor`, with or without `Cgroups`.
3. Build a `Command` and call `supervisor.spawn(command, options)`. It returns `(Arc<Process>, Option<Reader>)` once the process is running. Or call `supervisor.capture(command, limits).await` to run it to completion and keep its output.
4. Read output through a `Reader`, from the spawn or later from `process.reader(from, delivery)?`, or through `process.events(reader, replay)` to get the exit at the end.
5. Call `process.wait().await` for the `Exit`.
6. Call `supervisor.shutdown(grace).await` before your program exits.

### `SpawnOptions`

| Field | Type | Meaning |
| - | - | - |
| `retain_bytes` | `usize` | Output kept for replay. `0` selects `Config::default_retain_bytes`. Values above `Config::max_retain_bytes` fail with `Error::LimitExceeded`. Values below `Config::chunk_size` are raised to it. |
| `keep` | `bool` | Keep the record after exit, so you can look it up, reattach and read the exit. Records that are not kept vanish when the process finishes, and anything left in its process group is killed, unless the command's `leftovers` is `Leftovers::Leave`. |
| `attach` | `Option<Delivery>` | `Some(Delivery::Lossless)` returns a lossless reader at offset 0: the process blocks when you stop reading and its retention is full, like a terminal. `Some(Delivery::Lossy)` returns a lossy reader that never slows the process and gets `Item::Gap` for evicted bytes. `None` returns no reader. |
| `name` | `Option<String>` | Unique among running processes. Spawning a second running process with the same name fails with `Error::NameInUse`. The name frees when the process exits, and still finds the most recent kept process with it. |
| `request_id` | `Option<String>` | Idempotency key. Spawning again with the same key and the same command and options returns the process the first spawn created. A different command or options under the key fails with `Error::RequestIdConflict`. Once the supervisor evicts that process, the key fails with `Error::RequestExpired` (for the last 4096 evicted keys). `remove` frees the key. |
| `labels` | `BTreeMap<String, String>` | Free-form labels, read back with `process.labels()`. |

### `Config`

| Field | Default | Meaning |
| - | - | - |
| `default_retain_bytes` | 1 MiB | Output retained per process when the spawn passes `0`. |
| `max_retain_bytes` | 64 MiB | Most a spawn may ask to retain. |
| `max_finished` | 256 | Finished, kept processes remembered before the oldest is forgotten. |
| `output_budget_bytes` | 256 MiB | Ceiling on retention reserved by all tracked processes. A spawn evicts the oldest finished records to fit, and fails with `Error::BudgetExhausted` when running processes fill it. |
| `max_processes` | 1024 | Most processes tracked at once, running or finished. A spawn evicts finished records to make room, and fails with `Error::BudgetExhausted` when running processes fill every slot. |
| `chunk_size` | 64 KiB | Largest single read from a process's output. |
| `drain_grace` | 5 s | How long to wait for output pipes that descendants keep open after the leader exits. Only time spent waiting for output counts: while a lossless reader holds the output back, the exit waits for it instead of dropping output. |
| `capture_budget_bytes` | 256 MiB | Ceiling on output all concurrent `capture` calls keep at once. Separate from `output_budget_bytes`. |
| `child_oom_score_adj` | `None` | `oom_score_adj` each child sets for itself before it execs, from -1000 to 1000, so the kernel's OOM killer picks children before your program. Raising it needs no privilege. `None` leaves children with your program's value. axed sets 500. |

`Supervisor::new` fails with `Error::InvalidArgument` when `chunk_size` or `max_processes` is 0, when `default_retain_bytes` exceeds `max_retain_bytes`, or when `child_oom_score_adj` is outside -1000 to 1000. Otherwise it raises `default_retain_bytes` to at least `chunk_size`, `max_retain_bytes` to at least that, and `output_budget_bytes` to at least the raised `max_retain_bytes`.

### `Command`

| Field | Type | Meaning |
| - | - | - |
| `argv` | `Vec<String>` | Program and arguments. Empty fails with `Error::InvalidArgument`. |
| `env` | `Vec<(String, String)>` | Added on top of your program's environment. |
| `cwd` | `WorkDir` | Working directory, from `root.dir(path)`. |
| `stdio` | `Stdio` | `Stdio::Pipes { stdin }` (the default, with `stdin: false`, which gives `/dev/null`) or `Stdio::Pty(Option<WinSize>)`. A PTY reports all output as stdout, and gets `TERM=xterm-256color` when neither your environment nor `env` sets `TERM`. |
| `limits` | `Limits` | `memory_bytes`, `cpu_millis`, `max_tasks`, `open_files`, `open_files_soft`, `timeout`. See below. |
| `user` | `Option<User>` | Run as `User { uid, gid }` instead of your program's user. `User::resolve(spec)` builds one from a name, a uid or `uid:gid` as axed does, reading `/etc/passwd`; it refuses anything but a regular file of at most 1 MiB, and blocks, so call it off the async runtime. |
| `leftovers` | `Leftovers` | What happens to the rest of the tree when the leader exits on its own. `Leftovers::Kill` (the default) kills it unless the process is kept. `Leftovers::Leave` leaves it running, as a shell leaves a background job; with a cgroup, the cgroup stays until it empties, and `shutdown` kills what is left in it. Kills, timeouts and a dropped `Owned` end the whole tree either way. |

`Limits` fields:

| Field | With cgroups | Without cgroups |
| - | - | - |
| `memory_bytes` | `memory.max` for the tree, with `memory.oom.group` and no swap | `RLIMIT_AS` per process |
| `cpu_millis` | `cpu.max` (1000 = one CPU) | Refused with `Error::FailedPrecondition` |
| `max_tasks` | `pids.max` | `RLIMIT_NPROC` |
| `open_files` | `RLIMIT_NOFILE`, soft and hard | Same |
| `open_files_soft` | Soft `RLIMIT_NOFILE` only, keeping the inherited hard limit. For a program that raised its own soft limit and wants children to start with the original, as Go's `os/exec` does. Ignored when `open_files` is set. | Same |
| `timeout` | Kills the tree after this much running time. Time the sandbox spends suspended does not count. The exit reports `ExitReason::TimedOut`. | Same |

A `WorkDir` holds the directory's host path as `Root` resolved it, and the kernel resolves that path again when the process starts. Resolution cannot leave the root, but a path component swapped for a symlink between the two lookups can still redirect the starting directory. The race grants the process nothing it could not do itself with `chdir`.

## Stream output as it arrives

This program runs a command, prints each chunk with its stream and offset, and reports the exit.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use std::io::Write;
use std::time::Duration;

use axe::fs::Root;
use axe::output::{Delivery, Item, Stream};
use axe::{Command, Config, Event, Limits, Replay, SpawnOptions, Supervisor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;
    let supervisor = Supervisor::new(Config::default(), None)?;

    let script = "for i in 1 2 3; do echo line $i; sleep 1; done; echo done >&2; exit 3";
    let mut command = Command::new(["sh", "-c", script], root.dir(".")?);
    command.env.push(("GREETING".into(), "hello".into()));
    command.limits = Limits { timeout: Some(Duration::from_secs(30)), ..Limits::default() };

    // A lossless reader from offset 0, created before any output exists.
    let options = SpawnOptions { attach: Some(Delivery::Lossless), keep: true, ..SpawnOptions::default() };
    let (process, reader) = supervisor.spawn(command, options)?;
    let mut events = process.events(reader.expect("attach returns a reader"), Replay::Follow);

    while let Some(event) = events.next().await {
        match event {
            Event::Output(Item::Chunk(chunk)) => {
                let name = if chunk.stream == Stream::Stdout { "stdout" } else { "stderr" };
                print!("[{name} @{}] {}", chunk.offset, String::from_utf8_lossy(&chunk.data));
                std::io::stdout().flush()?;
            }
            Event::Output(Item::Gap { from, to }) => eprintln!("bytes {from}..{to} were evicted"),
            Event::Exited(exit) => println!("exit code {}, reason {:?}", exit.status.code(), exit.reason),
        }
    }

    supervisor.shutdown(Duration::from_secs(5)).await;
    Ok(())
}
```

It prints:

```text theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
[stdout @0] line 1
[stdout @7] line 2
[stdout @14] line 3
[stderr @21] done
exit code 3, reason Exited
```

Offsets count bytes in one log that combines stdout and stderr, so the interleaving survives replay. The chunk's `stream_offset` field gives the position within the chunk's own stream, for protocols that address the two separately.

`process.events(reader, replay)` turns any reader into output followed by the exit. `Replay::Follow` waits for output until the log ends, then yields `Event::Exited`. `Replay::Snapshot` yields only what is retained now, and ends with `Event::Exited` only if the process has already exited. Gaps appear if the reader is lossy, or once at the start if it was opened at an offset already evicted. `events.next()` is cancel-safe, so it can sit in a `tokio::select!`.

## Run a command to completion

`supervisor.capture(command, limits).await` runs a command, keeps a prefix of each stream, and returns `Captured { exit, stdout, stderr, elapsed }`. Each stream is a `Capture { data, truncated }`.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use axe::fs::Root;
use axe::{CaptureLimits, Command, Config, Supervisor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;
    let supervisor = Supervisor::new(Config::default(), None)?;

    let command = Command::new(["sh", "-c", "seq 1 100000; echo oops >&2"], root.dir(".")?);
    let limits = CaptureLimits { stdout_bytes: 1024, stderr_bytes: 0 };
    let run = supervisor.capture(command, limits).await?;

    println!("exit {} after {:?}", run.exit.status.code(), run.elapsed);
    println!("stdout: {} bytes, truncated {}", run.stdout.data.len(), run.stdout.truncated);
    println!("stderr: {:?}", String::from_utf8_lossy(&run.stderr.data));
    Ok(())
}
```

* A limit of `0`, or anything above `axe::MAX_CAPTURE_BYTES` (256 MiB), keeps up to 256 MiB of that stream.
* Kept bytes count against `Config::capture_budget_bytes`, shared by every capture, until you drop `data` (and every clone of it). A capture never waits for memory: output past its limit or past what the budget has left is dropped and reported as `truncated`, and the kept bytes are always a prefix of the stream.
* The process belongs to the future. Dropping it before the process exits kills the tree. The record is not kept after exit.

### Retry a capture safely

`supervisor.capture_once(command, limits, request_id, retain_bytes).await` is a capture you can repeat, for a caller that may lose the first answer, as a client does across a snapshot. The process is kept like a spawn with `keep`, retaining `retain_bytes` of output (`0` for the default), and it runs to the end even if the future is dropped. Repeating the call with the same request id, command (its `Limits` included) and `retain_bytes` collects the first run's process instead of starting another, reading its output back from the retained log, so the command runs once. Once that output or the record is evicted, the repeat fails with `Error::RequestExpired`.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use axe::fs::Root;
use axe::{CaptureLimits, Command, Config, Supervisor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;
    let supervisor = Supervisor::new(Config::default(), None)?;

    let command = Command::new(["sh", "-c", "echo ran >> runs.log; cat runs.log"], root.dir(".")?);
    let first = supervisor.capture_once(command.clone(), CaptureLimits::default(), "job-7".into(), 0).await?;
    let again = supervisor.capture_once(command, CaptureLimits::default(), "job-7".into(), 0).await?;
    assert_eq!(first.stdout.data, again.stdout.data, "the second call returned the first run's output");
    Ok(())
}
```

## Tie a process to its caller

`Owned::new(process)` wraps an `Arc<Process>`. When the `Owned` is dropped while the process is still running, it kills the tree with `kill_tree`. Use it to give a process the lifetime of a request or a connection: hold the `Owned` in the task serving the client, and the process dies when the client goes away. `Owned` dereferences to `Process`, and `owned.process()` gives the `Arc` back.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use std::sync::Arc;
use std::time::Duration;

use axe::fs::Root;
use axe::{Command, Config, ExitReason, ExitStatus, Owned, SpawnOptions, Supervisor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;
    let supervisor = Supervisor::new(Config::default(), None)?;

    let command = Command::new(["sleep", "600"], root.dir(".")?);
    let (process, _) = supervisor.spawn(command, SpawnOptions { keep: true, ..SpawnOptions::default() })?;

    // The task serving a client holds the owner. Here the client "goes away"
    // after 100 ms: the timeout cancels the task, which drops the owner.
    let owner = Owned::new(Arc::clone(&process));
    let serve = async move {
        let exit = owner.wait().await; // stream output to the client here
        println!("finished with {}", exit.status.code());
    };
    let _ = tokio::time::timeout(Duration::from_millis(100), serve).await;

    let exit = process.wait().await;
    assert_eq!((exit.status, exit.reason), (ExitStatus::Signaled(libc::SIGKILL), ExitReason::OwnerGone));
    supervisor.shutdown(Duration::from_secs(5)).await;
    Ok(())
}
```

## Run a detached process and reattach

A detached process has no reader at spawn. Its output goes to a bounded log that you can read later from any retained offset.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use std::time::Duration;

use axe::fs::Root;
use axe::output::{Delivery, Item};
use axe::{Command, Config, IfRunning, ProcessId, SignalTarget, SpawnOptions, Supervisor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;
    let supervisor = Supervisor::new(Config::default(), None)?;

    let command = Command::new(
        ["sh", "-c", "trap 'echo got TERM; exit 0' TERM; while true; do date; sleep 1; done"],
        root.dir(".")?,
    );

    // attach: None starts the process without a reader. keep: true keeps
    // the record, its output and its exit after the process finishes.
    let options = SpawnOptions { keep: true, name: Some("ticker".into()), ..SpawnOptions::default() };
    let (process, _) = supervisor.spawn(command, options)?;
    let id: String = process.id().to_string();
    println!("started {id} (pid {})", process.pid());

    tokio::time::sleep(Duration::from_secs(3)).await;

    // Later, possibly from another task: look the process up again, by
    // name or by the id string a client sent back.
    let process = supervisor.get_by_name("ticker").expect("still tracked");
    assert!(supervisor.get(id.parse::<ProcessId>()?).is_some());

    // Replay everything retained from offset 0. A lossy reader never slows
    // the process; try_next returns None once it has caught up.
    let mut reader = process.reader(Some(0), Delivery::Lossy)?;
    let mut next = 0;
    while let Some(item) = reader.try_next() {
        match item {
            Item::Chunk(chunk) => {
                next = chunk.offset + chunk.data.len() as u64;
                print!("{}", String::from_utf8_lossy(&chunk.data));
            }
            Item::Gap { from, to } => {
                next = to;
                println!("[{} bytes evicted]", to - from);
            }
        }
    }
    println!("caught up at offset {next}");

    // SIGTERM to the whole process group.
    process.signal(libc::SIGTERM, SignalTarget::Group)?;
    let exit = process.wait().await;

    println!("code      {}", exit.status.code());
    println!("signal    {:?}", exit.status.signal());
    println!("reason    {:?}", exit.reason);
    println!("user cpu  {:?}", exit.usage.user_cpu);
    println!("exited at {:?}", exit.at);

    // Output stays readable after exit, until the record is removed.
    let window = process.output().window();
    println!("retained output {}..{}", window.start, window.end);
    supervisor.remove(process.id(), IfRunning::Fail).await?;

    supervisor.shutdown(Duration::from_secs(5)).await;
    Ok(())
}
```

Things to know about readers:

* `process.reader(Some(offset), delivery)` starts at `offset`, clamped to the end of the log. `process.reader(None, delivery)` starts at the oldest retained byte. It returns `axe::Result<Reader>`. A process allows at most 64 lossless readers at once (`axe::output::MAX_LOSSLESS_READERS`), and one more fails with `Error::ResourceExhausted`. Lossy readers are not limited.
* If `offset` was already evicted, the reader first returns `Item::Gap { from, to }` and continues at the oldest retained byte. A lossy reader also gets a gap whenever it falls behind the retained window later.
* `reader.try_next()` returns what is available now and `None` when caught up. `reader.next().await` waits for more and returns `None` after the process exits and the log is drained.
* To resume later without replaying, keep the offset after the last byte you read: `chunk.offset + chunk.data.len()` for a chunk, or `to` for a gap. Pass it as `Some(offset)` to a new reader.
* A lossless reader holds the process back once retention is full. Drop it when you stop reading.

To find a process again, use `supervisor.get(id)`, `supervisor.get_by_name(name)` (the running process with that name, or else the most recently finished kept one), or `supervisor.list()` (oldest first). A `ProcessId` prints as 32 lowercase hex digits and parses back from exactly that with `str::parse`; anything else fails with `Error::InvalidArgument`.

The output log behind `process.output()` is read-only to you. Only the engine writes to it or ends it. Use it for `window()` and `is_closed()`, and open readers through `process.reader`.

### `Exit` fields

| Field | Type | Meaning |
| - | - | - |
| `status` | `ExitStatus` | `Exited(code)` or `Signaled(signal)`, or `Unknown` in the rare case the process was reaped but its status was lost (`code()` is then -1). `status.code()` gives the shell convention: the exit code, or 128 plus the signal number. `status.signal()` gives `Some(signal)` for a signal. |
| `usage` | `Usage` | `user_cpu`, `system_cpu` and `peak_memory_bytes`. From the cgroup when there is one, otherwise from `wait4`'s rusage. |
| `at` | `SystemTime` | When the exit was recorded. |
| `reason` | `ExitReason` | Why it ended, below. |

`ExitReason` is `#[non_exhaustive]`:

| Variant | Meaning |
| - | - |
| `Exited` | The leader exited on its own. |
| `Signaled` | A signal ended the leader, sent by anything but the engine, `process.signal` included. |
| `TimedOut` | `Limits::timeout` ran out. |
| `OomKilled` | The kernel killed the tree for exceeding its cgroup memory limit. Only with cgroups. |
| `Killed` | `process.kill_tree()`, or `supervisor.remove(id, IfRunning::Kill)` of a running process. |
| `OwnerGone` | An `Owned` handle was dropped while the process ran, including a dropped `capture` future. |
| `Shutdown` | `supervisor.shutdown` stopped it. |
| `Unknown` | The leader was reaped but its status was lost; `status` is `ExitStatus::Unknown`. |

When the engine kills a tree, the first cause it acted on wins, whatever status that left. A process that had already exited on its own when the engine acted keeps `Exited` or `Signaled`.

If the program in the example exits through its trap, `status` is `Exited(0)`, `signal()` is `None` and `reason` is `Exited`. A process killed by `SIGTERM` reports code 143, `Some(15)` and `Signaled`.

### Usage while running

`process.usage()` returns a `LiveUsage` for a running process: `user_cpu`, `system_cpu`, `memory_bytes`, `peak_memory_bytes` (`Option`) and `tasks`, and a `scope`. With a cgroup the figures cover the whole tree (`UsageScope::Tree`), read from `cpu.stat`, `memory.current`, `memory.peak` and `pids.current`. Without one they cover only the leader (`UsageScope::Leader`), from `/proc/<pid>/stat`, and `peak_memory_bytes` is `None`. Each call reads a few small files; nothing samples in the background. It returns `None` once the process has exited, when `Exit::usage` has the totals. `process.has_cgroup()` tells which applies.

## Stop a process

Pick the call by what you want to happen.

| Call | Sends | Reaches | Waits | Forgets the record |
| - | - | - | - | - |
| `process.signal(sig, SignalTarget::Group)` | Any signal | The process group, or the leader alone if the group is gone | No | No |
| `process.signal(sig, SignalTarget::Leader)` | Any signal | The leader only, through its pidfd when available | No | No |
| `process.kill_tree()` | `SIGKILL` | The whole cgroup with `cgroup.kill`, or without cgroups the process group plus every descendant reachable through `/proc`. Once the leader has exited, only what is left in its process group. The exit reports `Killed`. | No | No |
| `supervisor.remove(id, IfRunning::Fail).await` | Nothing | Nothing | No | Yes, if finished. A running process fails with `Error::FailedPrecondition`. |
| `supervisor.remove(id, IfRunning::Kill).await` | `SIGKILL` through `kill_tree` | The whole tree | Yes, until exit | Yes, and removes its cgroup |
| Dropping an `Owned` | `SIGKILL` through `kill_tree`, if still running. The exit reports `OwnerGone`. | The whole tree | No | No |
| `supervisor.shutdown(grace).await` | `SIGTERM` to every running process group, then `kill_tree` after `grace`. Exits report `Shutdown`. | Every process | Yes | No. It also stops new spawns. |

Use `signal` with `SIGTERM` or `SIGINT` to ask a process to stop and let it clean up, then `wait`. Use `kill_tree` when you need the process and everything it started gone now; follow it with `wait` if you need the exit. Use `remove` to free a finished record's retention and table slot, with `IfRunning::Kill` to stop and forget in one step.

`signal` is a no-op once the leader has exited, even while its output is still draining, so a signal never reaches a process that has since reused its pid. It returns `Error::InvalidArgument` for an invalid signal number and `Error::PermissionDenied` when the kernel refuses.

> [!NOTE]
>
> Processes in a pipeline or a shell often ignore `SIGTERM` sent only to the leader. `SignalTarget::Group` signals the whole group, which is what a terminal does.

## Work with files

`Root` resolves every path one component at a time against directory descriptors it holds, so neither `..` nor a symlink, even one swapped in mid-request, can lead outside it. Absolute paths under the root have the root stripped. Other absolute paths fail with `Error::PermissionDenied`.

`root.lenient()?` returns a second handle on the same directory that takes an absolute path outside the root as relative to it, so `/etc/passwd` names `etc/passwd` inside the root. That is the Kubernetes Agent Sandbox convention, and axed uses it for that protocol only. Confinement is the same in both modes. `..` and symlinks still cannot leave the root.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use std::io::{Read, Write};
use std::time::Duration;

use axe::fs::{Opened, Root, WriteMode};
use axe::watch::{Event, Watcher};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;
    root.mkdir("notes", 0o755, true)?;

    // Watch before writing, so the commit shows up as an event.
    let mut watcher = Watcher::new(&root, "notes", true)?;

    // The file appears at its path only on commit. Dropping `upload`
    // without committing leaves nothing behind.
    let mut upload = root.create("notes/hello.txt", 0o644, WriteMode::Replace)?;
    upload.file().write_all(b"hello\n")?;
    upload.commit()?;

    if let Opened::File(mut file, entry) = root.open("notes/hello.txt")? {
        let mut text = String::new();
        file.read_to_string(&mut text)?;
        println!("{} bytes, mode {:o}: {text:?}", entry.size, entry.mode);
    }

    for e in watcher.next_batch(Duration::from_millis(100)).await? {
        match e {
            Event::Change { kind, path } => println!("{kind:?} {path}"),
            Event::Error { message, terminal } => println!("error {message} (terminal: {terminal})"),
        }
    }

    // `..` above the root, and absolute paths outside it, are refused.
    assert!(matches!(root.open("../etc/passwd"), Err(axe::Error::PermissionDenied(_))));
    assert!(matches!(root.open("/etc/passwd"), Err(axe::Error::PermissionDenied(_))));
    // A lenient handle reads /etc/passwd as etc/passwd under the root.
    assert!(matches!(root.lenient()?.open("/etc/passwd"), Err(axe::Error::NotFound(_))));
    Ok(())
}
```

`Root` methods are blocking. In an async program, call them from `tokio::task::spawn_blocking` when they may take a while (large listings, copies, archive extraction).

| Method | Does |
| - | - |
| `Root::new(path)` | Opens the root, creating it if missing. The root is strict. |
| `lenient()` | The same directory, taking absolute paths outside it as relative to it. |
| `stat(path)` | Metadata, following symlinks. Returns an `Entry` (`name`, `kind`, `size`, `modified`, `mode`). |
| `open(path)` | `Opened::File(File, Entry)` for a regular file, `Opened::Directory(Entry)` for a directory. Other file types fail with `Error::InvalidArgument`. |
| `list(path, max_depth, ListLimits)` | Entries in lexical order, each directory before its contents. `max_depth` `Some(1)` lists direct children, `None` is unlimited. Listings of any depth fail with `Error::InvalidArgument` past `max_entries` names read, or past `max_name_bytes` of returned names. Names are paths from the listed directory, so a deep tree costs more name bytes than its entry count suggests. Symlinks report their target, resolved from their own directory, and are never descended into. |
| `dir(path)` | A `WorkDir` for `Command::cwd`. Fails with `Error::InvalidArgument` if the path is not a directory. |
| `create(path, mode, write_mode)` | A `PendingWrite`. Write through `file()`, then `commit()`. `WriteMode::Replace` replaces atomically; `WriteMode::CreateOnly` fails with `Error::FailedPrecondition` if the path exists at commit. Missing parents are created. The mode is applied exactly, ignoring the umask, except that setuid and setgid are dropped, as they are from every mode a `Root` sets. |
| `append(path, mode)` | A `File` opened for appending, created with `mode` if absent. Not atomic. |
| `open_write(path, mode)` | A `File` for writing in place, created if absent. Existing content is kept. |
| `mkdir(path, mode, parents)` | Creates a directory. Succeeds if a directory already exists. |
| `remove(path, recursive)` | Removes a file, symlink (never its target) or directory. Removing the root with `recursive` empties it. |
| `transfer(src, dst, Transfer::Move \| Transfer::Copy, overwrite)` | Moves or copies. `overwrite` replaces a file with a file, never a directory. Copies drop setuid and setgid bits. |
| `extract_tar(path, mode, reader, ExtractLimits)` | Unpacks a tar or gzipped tar into a directory, refusing entries that escape it. Setuid and setgid bits are dropped. Past `max_entries` entries, `max_bytes` of entry data, or 32 KiB of header and long-name, long-link or PAX records for one entry, it fails with `Error::ResourceExhausted`. |

`Watcher::new(&root, path, recursive)` arms an inotify watch on a directory. `next_batch(window).await` waits for at least one event, keeps collecting for `window`, and returns the events in order. A batch stops early at about 4,096 events; the rest wait in the kernel's queue, which reports an overflow if it fills. An empty batch means the watch ended. Paths in events are relative to the root. A rename is reported on the old path, and the new path arrives as a `Create` when it lands inside the watched tree. Uploads in progress through `create` are not reported until they commit.

## Cgroups and the lifecycle

Pass `Some(Cgroups)` to `Supervisor::new` to place each process in its own cgroup, named `p` plus its process id. `Cgroups::setup(Path::new("/sys/fs/cgroup"), leaf)` takes over the cgroup your program runs in: it moves your program into a child cgroup named `leaf` (axed passes `axed`), removes per-process cgroups left by an earlier run (killing anything still in them), and enables the `cpu`, `memory` and `pids` controllers for per-process children. It fails with `Error::FailedPrecondition` when cgroup v2 is not mounted in unified mode, or when other processes share the cgroup and your program is not PID 1.

```rust src/main.rs theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
use std::path::Path;
use std::time::Duration;

use axe::cgroup::Cgroups;
use axe::fs::Root;
use axe::{Command, Config, ExitReason, Limits, SpawnOptions, Supervisor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Root::new("/tmp/agent-workspace")?;

    // Take over the cgroup this program runs in, or run without one.
    let cgroups = match Cgroups::setup(Path::new("/sys/fs/cgroup"), "agent") {
        Ok(cg) => Some(cg),
        Err(e) => {
            eprintln!("cgroups unavailable: {e}");
            None
        }
    };
    let config = Config { default_retain_bytes: 4 << 20, max_processes: 64, ..Config::default() };
    let supervisor = Supervisor::new(config, cgroups)?;

    let life = supervisor.lifecycle();
    println!("instance {} generation {}", life.instance(), life.generation());

    let mut command = Command::new(["sh", "-c", "echo limited"], root.dir(".")?);
    command.limits = Limits { memory_bytes: Some(256 << 20), max_tasks: Some(64), ..Limits::default() };
    let (process, _) = supervisor.spawn(command, SpawnOptions { keep: true, ..SpawnOptions::default() })?;
    let exit = process.wait().await;
    println!("exit {} oom-killed {}", exit.status.code(), exit.reason == ExitReason::OomKilled);

    supervisor.shutdown(Duration::from_secs(5)).await;
    Ok(())
}
```

Without cgroups, processes run in their own process groups under rlimits, `cpu_millis` is refused, and `supervisor.set_frozen(frozen, timeout).await` fails with `Error::FailedPrecondition`. With cgroups, `set_frozen` freezes or thaws every process tree, including what finished processes left running with `Leftovers::Leave`, and returns how many trees changed state before the timeout and how many there were. From a freeze until the thaw, `spawn` and `capture` fail with `Error::Frozen`, so nothing starts while the rest are stopped; `supervisor.is_frozen()` tells whether that is the case.

`cgroups.reserve_memory(bytes)` sets `memory.min` on the leaf your program moved into, so reclaim takes the supervised trees' memory first. It fails without the memory controller. axed reserves 16 MiB.

`supervisor.lifecycle()` returns the `Lifecycle`:

| Method | Does |
| - | - |
| `instance()` | A random 128-bit id, in hex, for this in-memory process table. It survives memory restores and changes on a cold boot. |
| `generation()` | Resumes detected so far. |
| `resumes()` | The most recent resumes, oldest first, each with `at` and an estimated `gap`. |
| `resumed()` | Records a resume the platform reported, for runtimes whose clocks do not reveal it. |
| `set_wall_clock(to, tolerance)` | Steps `CLOCK_REALTIME` when it is off by more than `tolerance`. Needs `CAP_SYS_TIME`. |

`axe::lifecycle::add_entropy(bytes)` credits bytes to the kernel entropy pool after a restore. It needs `CAP_SYS_ADMIN`. [Snapshots](https://axe-engine.mintlify.site/snapshots.md) explains when to call these.

## Develop on macOS

The repository's `scripts/dev` runs any command in a Linux container with a Rust toolchain:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
git clone https://github.com/vincent0426/axe && cd axe
scripts/dev cargo run -p axe --example embed
```

[`examples/embed.rs`](https://github.com/vincent0426/axe/blob/main/crates/axe/examples/embed.rs) is a complete program in the repository. For your own crate, run Cargo in any Linux container or VM with your project mounted.

## Read the API documentation

The crate documents every public type, starting with a quickstart. On Linux, from your project or the AXE repository:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
cargo doc -p axe --open
```

On macOS, `scripts/dev` keeps build output in a Docker volume, so the HTML stays inside it. Point `CARGO_TARGET_DIR` at a directory in your checkout to get it on the host:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
AXE_DEV_DOCKER_ARGS="-e CARGO_TARGET_DIR=/src/target-doc" scripts/dev cargo doc -p axe --no-deps
open target-doc/doc/axe/index.html
```

## Next steps

* [Architecture](https://axe-engine.mintlify.site/architecture.md) shows how the engine, the daemon and the adapters fit together.
* [Output and replay](https://axe-engine.mintlify.site/processes/output.md) covers offsets and retention in depth.
* [File confinement](https://axe-engine.mintlify.site/files/confinement.md) explains path resolution.
* [Errors](https://axe-engine.mintlify.site/reference/errors.md) lists every `axe::Error` variant.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.