Whole-sandbox resource limits for ai-jail 3.7.0: --memory, --max-tasks and
--cpu-quota (a systemd user scope, verified to enforce before launch). After
the run, the supervisor reads the scope's cgroup and adds what the exit code
cannot say to upstream's exit line: an OOM kill at the memory limit (with the
peak), forks refused at the task limit, and under --memory that a SIGKILL was
not the sandbox's limit. --memory also makes the sandbox the preferred OOM
victim. The launch's audit record gains `limits` and `cgroup`.

--cpus and --rlimit NAME=VALUE are upstream's since v3.6.0 (PRs #253, #254);
these limits consume upstream's --cpus and define no second one. Config keys
memory_max, max_tasks and cpu_quota; a project may add or lower a limit,
never raise it.

From the zeo-workspace/ai-jail fork, branch zeo/ebuild-370: feat/resource-
limits rebased onto upstream v3.7.0, plus the guide entries v3.7.0's own
controls need under the guide-coverage test. Not upstream yet; it goes there
as its own PR after local testing (Zeo next proposal §6.54).

diff --git a/CLAUDE.md b/CLAUDE.md
index 519017f..679439d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -32,6 +32,7 @@ src/
   bootstrap.rs    -- AI tool config generation (Claude, Codex, OpenCode)
   command.rs      -- harness/ai-memory wrapper detection, effective command names
   fsutil.rs       -- atomic file writes (0600), symlink-safe target checks
+  limits.rs       -- whole-sandbox limits (systemd user scope, CPU affinity) + exit report
 ```
 
 The onboarding UI contract is documented in `docs/TUI_DESIGN.md`. Keep its
diff --git a/README.md b/README.md
index 520c59c..1bd35f6 100644
--- a/README.md
+++ b/README.md
@@ -887,6 +887,43 @@ Code creates that directory unconditionally at startup and ignores `TMPDIR`;
 unlike the session directory, it persists between runs. Use a map or
 `--agent-state` for anything durable.
 
+## Resource limits
+
+rlimits (on by default) cap each process on its own. To cap the sandbox as a
+whole — and to learn why it died — use the cgroup limits (Linux):
+
+```bash
+ai-jail --memory 8G --max-tasks 2000 --cpu-quota 400% --cpus 8-15 claude
+```
+
+- `--memory SIZE` caps RAM for everything inside, with swap off so a runaway
+  agent is killed instead of stalling the host.
+- `--max-tasks N` caps processes **and threads** (`pids.max`); a Node or JVM
+  agent alone runs dozens of threads, so size it generously.
+- `--cpu-quota PCT` caps CPU time, in percent of one CPU.
+- `--cpus LIST` restricts the sandbox to those CPUs (`8,24`, `0-3`).
+
+The first three need a systemd user session and no privilege: ai-jail
+re-execs itself through `systemd-run --user --scope`, which puts the
+supervisor and the sandbox in one fresh cgroup, then checks that the kernel
+really enforces the limits — or refuses to launch. The PID, stdio and signals
+are unchanged, so `--exec` clients (ACP adapters, harnesses) see no
+difference. `--cpus` needs no systemd: it is CPU affinity, and seccomp then
+refuses `sched_setaffinity` so nothing inside can widen it (it therefore
+requires seccomp).
+
+When the sandbox dies, ai-jail says why on stderr, also under `--exec`:
+
+```text
+✗ sandbox exited with 137: out of memory: the kernel killed 1 process(es) at
+  the sandbox memory limit (8.0 GiB, peak 8.0 GiB)
+```
+
+With `--audit-log`, the launch record carries the limits and what the cgroup
+counted (`oom_kills`, `memory_peak`, `tasks_refused`, `cpu_usage_usec`). The
+config fields are `memory_max`, `max_tasks`, `cpu_quota` and `cpus`; a project
+`.ai-jail` may add or lower a limit, never raise it.
+
 ## Browsers
 
 `--browser[=hard|soft]` reuses an isolated browser profile, but browsers still
@@ -947,7 +984,7 @@ Common fields: `command`, `rw_maps`, `ro_maps`, `overlay_maps`, `mask`,
 `macos_host_ipc`, `macos_chromium`, `macos_trustd`, `macos_pasteboard`,
 `allow_loopback_connect`, `systemd_user`, `kvm`, `ssh`, `pictures`,
 `private_home`, `lockdown`, `browser_profile`, `claude_dir`, `allow_tcp_ports`,
-`status_bar_style`.
+`status_bar_style`, `memory_max`, `max_tasks`, `cpu_quota`, `cpus`.
 
 A `ro_maps` or `rw_maps` entry whose source does not exist is skipped with a
 warning at launch, so one config can list service paths that only some hosts
@@ -1069,6 +1106,10 @@ ai-jail [OPTIONS] [--] [COMMAND [ARGS...]]
 --systemd-user / --no-systemd-user  host user manager access (off by default)
 --ssh / --no-ssh                OPEN: full ~/.ssh and ambient-agent sharing (off by default)
 --claude-dir PATH               explicit Claude state directory
+--memory SIZE / --max-tasks N / --cpu-quota PCT
+                                cap the whole sandbox (Linux, systemd user
+                                session; see Resource limits)
+--cpus LIST                     pin the sandbox to CPUs, locked by seccomp
 --browser[=hard|soft]           isolated browser profile (needs --network --display)
 --dry-run                       print the backend invocation
 --init                          write configuration and exit
diff --git a/docs/CLI_TUI_PARITY.md b/docs/CLI_TUI_PARITY.md
index 127f203..1963dc7 100644
--- a/docs/CLI_TUI_PARITY.md
+++ b/docs/CLI_TUI_PARITY.md
@@ -73,6 +73,8 @@ or integration rather than saved sandbox authority.
 - Filtered egress policy: `--allow-host`, `--allow-private-host`,
   `--prompt-hosts`, `--no-prompt-hosts`
 - Port bridges: `--forward-port`, `--publish-port`
+- Whole-sandbox resource limits (tighten only): `--memory`, `--max-tasks`,
+  `--cpu-quota`
 - Environment/secret sources: `--env-from-file`, `--secret`
 - Harness-specific path override: `--claude-dir`
 - Browser command/profile mode: `--browser`, `--no-browser` (command-specific;
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index d2d4997..9aca0b8 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -239,7 +239,25 @@ there bought nothing — an agent with `--network` can learn the same addresses
 by connecting out — while breaking any tool that calls `getifaddrs()`. Every
 other netlink protocol and every other raw socket domain stays denied, and
 under `--lockdown` or without `--network` so does this one, so lockdown's
-`/sys/class/net` mask cannot be walked around. `BWRAP_BIN` must resolve canonically either to a
+`/sys/class/net` mask cannot be walked around.
+
+Resource limits (`--memory`, `--max-tasks`, `--cpu-quota`) are a cgroup the
+supervisor shares with the sandbox, obtained from the user's own systemd
+manager: they bound what a runaway or hostile agent can consume, and they are
+not an isolation boundary. The supervisor re-execs itself through
+`systemd-run`, found on `PATH`, and then verifies from `/proc/self/cgroup` and
+the cgroup's own files that it sits in the scope it named and that every
+requested limit is enforced; any mismatch refuses the launch, so a missing
+controller or a spoofed `AI_JAIL_LIMITS_SCOPE` marker can only stop a launch,
+never run one unlimited. The sandbox's `oom_score_adj` is raised so an OOM
+kill lands on the agent rather than the supervisor that reports it; an agent
+that lowers its own score back can at worst lose that report, not escape the
+limit. `--cpus` is CPU affinity locked by denying `sched_setaffinity` in
+seccomp; it bounds where the sandbox runs, not how much of each CPU it takes
+(that is `--cpu-quota`). `cpuset` isolation is not used because enabling it
+for an unprivileged user requires root.
+
+`BWRAP_BIN` must resolve canonically either to a
 root-owned executable with no group- or world-write bits, or to an executable
 with no write bits at all under a `/nix/store` that is itself owned by root
 (or by an unmapped owner, which a user namespace reports as the overflow uid)
diff --git a/docs/TUI_DESIGN.md b/docs/TUI_DESIGN.md
index 672c057..36d49e6 100644
--- a/docs/TUI_DESIGN.md
+++ b/docs/TUI_DESIGN.md
@@ -227,6 +227,9 @@ must still appear in the final `Complete effective access` review.
   widens is printed as a `profile=NAME widens=FIELD` line before the launch.
 - `--cpus LIST` and `cpus`: the CPU set, locked by seccomp, Linux only. The
   review shows it as `cpus=LIST`.
+- `--memory`, `--max-tasks` and `--cpu-quota` (`memory_max`, `max_tasks`,
+  `cpu_quota`): whole-sandbox cgroup limits, tighten-only, shown by
+  `--dry-run`.
 
 ## Plain-terminal fallback
 
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index c00ffa9..990aebd 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -539,6 +539,17 @@ for <launch dir> is ignored`. Restrictions saved only in that per-directory
 
 The setting is global only. A repository file cannot enable it.
 
+## Terminal appearance and the macOS pasteboard
+
+- `--terminal-appearance` / `--no-terminal-appearance` (config `terminal_appearance`), off by
+  default: in the interactive ai-jail PTY, lets a program ask the terminal for its background
+  colour (OSC 11), its identity (DA1) and light/dark changes (Mode 2031). It enables no other
+  terminal query and no clipboard access, and has no effect under `--exec` or without a TTY.
+- `--macos-pasteboard` / `--no-macos-pasteboard` (config `macos_pasteboard`), macOS only, off by
+  default: permits only `mach-lookup` of `com.apple.pasteboard.1`, so the jail can copy and paste
+  text and images without `--macos-host-ipc`. What you copy is readable inside the jail. Dropped
+  under `--lockdown`; an untrusted project policy cannot enable it.
+
 ## Resource limits and CPU set
 
 Per-process resource limits and the CPU set are advanced CLI/config-only
@@ -571,6 +582,17 @@ data = "8G"
   policy is saved, `status --json` lists it as the `limits_unavailable`
   blocker, and plain `status` warns that a launch would be refused.
 
+Whole-sandbox limits are advanced CLI/config-only controls too, for the same
+reason. They cap everything inside the sandbox together, through a cgroup, and
+need a systemd user session:
+
+- `--memory SIZE` (`memory_max` in config) caps memory, with swap off.
+- `--max-tasks N` (`max_tasks`) caps processes and threads together.
+- `--cpu-quota PCT` (`cpu_quota`) caps CPU time, in percent of one CPU.
+
+A project policy may only tighten them. If the kernel does not enforce them,
+the launch is refused.
+
 The final `Complete effective access` review lists each explicit limit as
 `rlimit NAME=SOFT/HARD (SOURCE)` and the CPU set as `cpus=LIST`. `--dry-run`
 prints every effective limit, defaults included. The README section
diff --git a/src/audit.rs b/src/audit.rs
index b80a046..7cbd115 100644
--- a/src/audit.rs
+++ b/src/audit.rs
@@ -355,6 +355,11 @@ pub(crate) struct LaunchRecord<'a> {
     pub rlimits: &'a [crate::sandbox::rlimits::EffectiveLimit],
     /// The `--cpus` set, when one was given; omitted otherwise.
     pub cpus: Option<&'a str>,
+    /// Resource limits requested for the launch, when any were set.
+    pub limits: Option<serde_json::Value>,
+    /// What the sandbox cgroup counted (OOM kills, peak memory, ...),
+    /// when the launch ran in its own scope.
+    pub cgroup: Option<serde_json::Value>,
 }
 
 pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
@@ -652,6 +657,8 @@ pub(crate) fn launch_record(record: &LaunchRecord<'_>) -> serde_json::Value {
         },
         "exit_code": record.exit_code,
         "duration_s": record.duration.as_millis() as f64 / 1000.0,
+        "limits": record.limits,
+        "cgroup": record.cgroup,
     });
     // Optional and additive: a reader of older records sees no new key,
     // and existing keys are untouched.
@@ -916,6 +923,8 @@ mod tests {
             duration: std::time::Duration::from_millis(1500),
             rlimits: &[],
             cpus: None,
+            limits: Some(serde_json::json!({"memory": 1024})),
+            cgroup: Some(serde_json::json!({"oom_kills": 1})),
         };
         log.record(launch_record(&launch));
         log.record(connect_record(
@@ -939,6 +948,8 @@ mod tests {
         assert_eq!(lines[0]["config"]["project_source"], "legacy_untrusted");
         assert_eq!(lines[0]["config"]["project_grants"], false);
         assert_eq!(lines[0]["config"]["project_constraints"], true);
+        assert_eq!(lines[0]["limits"]["memory"], 1024);
+        assert_eq!(lines[0]["cgroup"]["oom_kills"], 1);
         assert_eq!(lines[1]["type"], "connect");
         assert_eq!(lines[1]["host"], "api.anthropic.com");
         assert_eq!(lines[1]["verdict"], "allow");
@@ -972,6 +983,8 @@ mod tests {
             rlimits,
             profile: None,
             cpus,
+            limits: None,
+            cgroup: None,
         };
         // An old-shaped record: no new key appears.
         let old = launch_record(&base(&[], None));
@@ -1021,6 +1034,8 @@ mod tests {
             profile: None,
             rlimits: &[],
             cpus: None,
+            limits: None,
+            cgroup: None,
             exit_code: 0,
             duration: std::time::Duration::ZERO,
         };
diff --git a/src/cli.rs b/src/cli.rs
index 0a0fd52..bfdcbf4 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -53,6 +53,12 @@ OPTIONS:
     --profile <NAME>               Apply [profiles.NAME] from the global
                                    config (once; every access it widens is
                                    printed before launch)
+    --memory <SIZE>                Cap the whole sandbox's memory (e.g. 8G, 512M;
+                                   swap off). Linux + systemd user session
+    --max-tasks <N>                Cap processes AND threads in the whole sandbox
+                                   (Linux + systemd user session)
+    --cpu-quota <PCT>              Cap CPU time, in percent of one CPU (400% = four
+                                   CPUs; Linux + systemd user session)
     --cpus <LIST>                  Run only on these CPUs (e.g. 8,24 or 0-3); locked
                                    by seccomp so the sandbox cannot widen it (Linux)
     --systemd-user / --no-systemd-user
@@ -233,6 +239,10 @@ pub struct CliArgs {
     /// `--profile NAME`: a `[profiles.NAME]` table of the global config.
     /// Validated against the global config at load, not here.
     pub profile: Option<String>,
+    /// `--memory`: validated at parse time, stored as typed.
+    pub memory_max: Option<String>,
+    pub max_tasks: Option<u64>,
+    pub cpu_quota: Option<u32>,
     /// `--cpus LIST`, normalized (`0-1,3`).
     pub cpus: Option<String>,
     pub systemd_user: Option<bool>,
@@ -483,6 +493,28 @@ pub fn parse_from(mut parser: lexopt::Parser) -> Result<CliArgs, String> {
             Long(s @ ("rlimits" | "no-rlimits")) => {
                 args.rlimits = Some(s == "rlimits");
             }
+            Long("memory") => {
+                let val = parser.value().map_err(|e| e.to_string())?;
+                let text = val.to_string_lossy().into_owned();
+                crate::limits::parse_size(&text)
+                    .map_err(|e| format!("--memory: {e}"))?;
+                args.memory_max = Some(text);
+            }
+            Long("max-tasks") => {
+                let val = parser.value().map_err(|e| e.to_string())?;
+                let text = val.to_string_lossy();
+                let n: u64 =
+                    text.parse().ok().filter(|&n| n > 0).ok_or_else(|| {
+                        format!("--max-tasks: invalid count {text:?}")
+                    })?;
+                args.max_tasks = Some(n);
+            }
+            Long("cpu-quota") => {
+                let val = parser.value().map_err(|e| e.to_string())?;
+                let pct = crate::limits::parse_percent(&val.to_string_lossy())
+                    .map_err(|e| format!("--cpu-quota: {e}"))?;
+                args.cpu_quota = Some(pct);
+            }
             Long("cpus") => {
                 let val = parser.value().map_err(|e| e.to_string())?;
                 let text = val.to_string_lossy();
@@ -1285,6 +1317,10 @@ const SANDBOX_LONG_FLAGS: &[&str] = &[
     "--init",
     "--bootstrap",
     "--verbose",
+    "--memory",
+    "--max-tasks",
+    "--cpu-quota",
+    "--cpus",
 ];
 
 /// Config fields that are runtime state, never written by a user.
@@ -1764,6 +1800,48 @@ mod tests {
         assert_eq!(args.command, vec!["claude"]);
     }
 
+    #[test]
+    fn parse_resource_limits() {
+        let args = parse_test(&[
+            "--memory",
+            "8G",
+            "--max-tasks",
+            "2000",
+            "--cpu-quota",
+            "400%",
+            "--cpus",
+            "3,0-1",
+            "claude",
+        ])
+        .unwrap();
+        assert_eq!(args.memory_max.as_deref(), Some("8G"));
+        assert_eq!(args.max_tasks, Some(2000));
+        assert_eq!(args.cpu_quota, Some(400));
+        assert_eq!(args.cpus.as_deref(), Some("0-1,3"), "normalized");
+        assert_eq!(args.command, vec!["claude"]);
+    }
+
+    #[test]
+    fn parse_resource_limits_rejects_bad_values_early() {
+        for bad in [
+            &["--memory", "lots"][..],
+            &["--memory", "100"],
+            &["--max-tasks", "0"],
+            &["--max-tasks", "-1"],
+            &["--cpu-quota", "0%"],
+            &["--cpus", "3-1"],
+            &["--cpus", "a"],
+        ] {
+            assert!(parse_test(bad).is_err(), "{bad:?} should fail");
+        }
+    }
+
+    #[test]
+    fn resource_limit_flags_after_command_are_recognized() {
+        assert!(is_sandbox_long_flag("--memory"));
+        assert!(is_sandbox_long_flag("--cpus=0-3"));
+    }
+
     #[test]
     fn parse_clean() {
         let args = parse_test(&["--clean", "bash"]).unwrap();
@@ -3671,8 +3749,8 @@ mod interface_profile_tests {
     rw_maps overlay_maps hide_dotdirs mask deny_paths mask_exceptions
     deny_path_exceptions no_gpu no_docker tailscale no_display audio
     aws kube gcloud docker_config kvm prompt_hosts macos_host_ipc
-    macos_chromium macos_trustd macos_pasteboard allow_pty
-    allow_loopback_listen terminal_appearance
+    macos_chromium macos_trustd allow_pty
+    allow_loopback_listen
     allow_loopback_connect x11 host_shm terminal_passthrough
     no_worktree no_mise no_toolchains no_save_config no_hide_config
     pictures browser_profile private_home no_landlock no_status_bar
@@ -3690,9 +3768,9 @@ mod interface_profile_tests {
     --audio --no-audio --no-github --aws --no-aws --kube --no-kube
     --gcloud --no-gcloud --docker-config --no-docker-config --kvm
     --no-kvm --prompt-hosts --no-prompt-hosts --network --no-network
-    --macos-host-ipc --no-macos-host-ipc --macos-chromium
+    --no-macos-host-ipc --macos-chromium
     --no-macos-chromium --macos-trustd --no-macos-trustd
-    --macos-pasteboard --no-macos-pasteboard --allow-pty
+    --allow-pty
     --no-allow-pty --allow-loopback-listen --no-allow-loopback-listen
     --allow-loopback-connect --no-allow-loopback-connect --no-gpu
     --gpu --no-docker --docker --tailscale --no-tailscale --landlock
diff --git a/src/config.rs b/src/config.rs
index f8c8534..0ef5153 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -457,6 +457,19 @@ pub struct Config {
     /// never enable it.
     #[serde(default, skip_serializing_if = "Option::is_none")]
     pub audit_log: Option<bool>,
+    /// Memory ceiling for the whole sandbox (`8G`, `512M`), enforced by
+    /// a systemd user scope with swap pinned to zero. Linux only. The
+    /// project `.ai-jail` may only lower it.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub memory_max: Option<String>,
+    /// Ceiling on processes *and threads* in the whole sandbox
+    /// (cgroup `pids.max`). The project `.ai-jail` may only lower it.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub max_tasks: Option<u64>,
+    /// CPU time for the whole sandbox, in percent of one CPU (400 =
+    /// four CPUs). The project `.ai-jail` may only lower it.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub cpu_quota: Option<u32>,
 }
 
 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
@@ -2316,6 +2329,9 @@ fn merge_trusted(global: Config, local: Config) -> Config {
     take!(inherit_env);
     take!(update_check);
     take!(audit_log);
+    take!(memory_max);
+    take!(max_tasks);
+    take!(cpu_quota);
     c.env_pass.extend(local.env_pass);
     dedup_env_pass(&mut c.env_pass);
     c.env_from_file.extend(local.env_from_file);
@@ -2888,6 +2904,37 @@ pub(crate) fn merge_layer_report(
     monotonic!(update_check, |config: &Config| config
         .update_check_enabled());
     monotonic!(audit_log, |config: &Config| config.audit_log_enabled());
+    // Resource limits: a project may add or lower one, never raise it.
+    let weakens = |field: &str, asked: Option<String>| {
+        Refusal::new(
+            field,
+            asked.into_iter().collect(),
+            format!(
+                "{layer} {field} ignored because it weakens the baseline sandbox"
+            ),
+        )
+    };
+    let asked = local.memory_max.clone();
+    let (memory_max, dropped) =
+        crate::limits::tighten_size(c.memory_max.take(), local.memory_max);
+    c.memory_max = memory_max;
+    if dropped {
+        warnings.push(weakens("memory_max", asked));
+    }
+    let (max_tasks, dropped) =
+        crate::limits::tighten_number(c.max_tasks, local.max_tasks);
+    c.max_tasks = max_tasks;
+    if dropped {
+        warnings
+            .push(weakens("max_tasks", local.max_tasks.map(|n| n.to_string())));
+    }
+    let (cpu_quota, dropped) =
+        crate::limits::tighten_number(c.cpu_quota, local.cpu_quota);
+    c.cpu_quota = cpu_quota;
+    if dropped {
+        warnings
+            .push(weakens("cpu_quota", local.cpu_quota.map(|n| n.to_string())));
+    }
     // These three name or carry secrets: `granted` holds key names only
     // and the text holds none, so neither can leak a value.
     if !local.env_pass.is_empty() {
@@ -3578,6 +3625,9 @@ pub fn merge(cli: &CliArgs, existing: Config) -> Config {
     }
     invert!(status_bar, no_status_bar);
     clone_into!(status_bar_style);
+    clone_into!(memory_max);
+    direct!(max_tasks);
+    direct!(cpu_quota);
     if cli.cpus.is_some() {
         config.cpus_source = Some(crate::sandbox::rlimits::LimitSource::Cli);
     }
@@ -3791,6 +3841,13 @@ pub fn display_status(config: &Config, stored_path: Option<&Path>) {
     print_auto_tristate("  Landlock", config.no_landlock);
     print_auto_tristate("  Seccomp", config.no_seccomp);
     print_auto_tristate("  Rlimits", config.no_rlimits);
+    match crate::limits::ResourceLimits::from_config(config) {
+        Ok(limits) if !limits.is_empty() => {
+            output::status_header("  Limits", &limits.describe());
+        }
+        Ok(_) => {}
+        Err(e) => output::status_header("  Limits", &format!("invalid: {e}")),
+    }
     print_shared_or_hidden("  systemd --user", config.systemd_user);
     print_auto_tristate("  Lockdown", config.lockdown.map(|v| !v));
     print_allow_tcp_ports(&config.allow_tcp_ports, config.lockdown_enabled());
@@ -5712,6 +5769,122 @@ mask = []
         assert!(cfg.overlay_maps.is_empty());
     }
 
+    #[test]
+    fn regression_v2_2_1_config_without_resource_limits() {
+        // Configs written before the resource limits existed must parse
+        // with every limit unset, which keeps the launch unscoped.
+        let toml = r#"
+command = ["claude"]
+rw_maps = ["/tmp/rw"]
+allow_hosts = ["anthropic.com"]
+audit_log = true
+no_rlimits = false
+"#;
+        let cfg = parse_toml(toml).unwrap();
+        assert_eq!(cfg.memory_max, None);
+        assert_eq!(cfg.max_tasks, None);
+        assert_eq!(cfg.cpu_quota, None);
+        assert_eq!(cfg.cpus, None);
+        assert!(
+            crate::limits::ResourceLimits::from_config(&cfg)
+                .unwrap()
+                .is_empty()
+        );
+    }
+
+    #[test]
+    fn resource_limits_round_trip_through_toml() {
+        let toml = r#"
+memory_max = "8G"
+max_tasks = 2000
+cpu_quota = 400
+cpus = "8,24"
+"#;
+        let cfg = parse_toml(toml).unwrap();
+        assert_eq!(cfg.memory_max.as_deref(), Some("8G"));
+        assert_eq!(cfg.max_tasks, Some(2000));
+        assert_eq!(cfg.cpu_quota, Some(400));
+        assert_eq!(cfg.cpus.as_deref(), Some("8,24"));
+        let written = toml::to_string(&cfg).unwrap();
+        assert_eq!(parse_toml(&written).unwrap().cpus, cfg.cpus);
+        assert!(
+            !toml::to_string(&Config::default())
+                .unwrap()
+                .contains("memory_max")
+        );
+    }
+
+    #[test]
+    fn project_resource_limits_only_tighten() {
+        let project = Path::new("/project");
+        let baseline = Config {
+            memory_max: Some("8G".into()),
+            max_tasks: Some(2000),
+            cpu_quota: Some(400),
+            cpus: Some("0-7".into()),
+            ..Config::default()
+        };
+        let tighter = Config {
+            memory_max: Some("4G".into()),
+            max_tasks: Some(100),
+            cpu_quota: Some(100),
+            cpus: Some("2-3".into()),
+            ..Config::default()
+        };
+        let (c, warnings) =
+            merge_with_global_report(baseline.clone(), tighter, project);
+        assert_eq!(c.memory_max.as_deref(), Some("4G"));
+        assert_eq!(c.max_tasks, Some(100));
+        assert_eq!(c.cpu_quota, Some(100));
+        assert_eq!(c.cpus.as_deref(), Some("2-3"));
+        assert!(warnings.is_empty(), "{warnings:?}");
+
+        let looser = Config {
+            memory_max: Some("64G".into()),
+            max_tasks: Some(99999),
+            cpu_quota: Some(3200),
+            cpus: Some("16-31".into()),
+            ..Config::default()
+        };
+        let (c, warnings) = merge_with_global_report(baseline, looser, project);
+        assert_eq!(c.memory_max.as_deref(), Some("8G"));
+        assert_eq!(c.max_tasks, Some(2000));
+        assert_eq!(c.cpu_quota, Some(400));
+        // Disjoint CPUs leave nothing to run on: the empty list is kept
+        // and the launch refuses it (sandbox::affinity::tighten_cpus,
+        // R4.5) instead of quietly keeping the baseline set.
+        assert_eq!(c.cpus.as_deref(), Some(""));
+        assert_eq!(warnings.len(), 4, "{warnings:?}");
+
+        // A project may add a limit the baseline did not set.
+        let (c, _) = merge_with_global_report(
+            Config::default(),
+            Config {
+                memory_max: Some("2G".into()),
+                ..Config::default()
+            },
+            project,
+        );
+        assert_eq!(c.memory_max.as_deref(), Some("2G"));
+    }
+
+    #[test]
+    fn malformed_project_limit_fails_closed() {
+        let project = Path::new("/project");
+        let (c, _) = merge_with_global_report(
+            Config {
+                memory_max: Some("8G".into()),
+                ..Config::default()
+            },
+            Config {
+                memory_max: Some("lots".into()),
+                ..Config::default()
+            },
+            project,
+        );
+        assert!(crate::limits::ResourceLimits::from_config(&c).is_err());
+    }
+
     #[test]
     fn regression_old_config_without_deny_paths() {
         let toml = r#"
@@ -5918,6 +6091,9 @@ no_gpu = true
             trust_project_config: vec![],
             update_check: Some(false),
             audit_log: Some(true),
+            memory_max: Some("8G".into()),
+            max_tasks: Some(2000),
+            cpu_quota: Some(400),
         };
         let serialized = serialize_config(&config).unwrap();
         let deserialized = parse_toml(&serialized).unwrap();
@@ -5977,6 +6153,10 @@ no_gpu = true
         assert!(deserialized.secret_hosts.is_empty());
         assert_eq!(deserialized.update_check, config.update_check);
         assert_eq!(deserialized.audit_log, config.audit_log);
+        assert_eq!(deserialized.memory_max, config.memory_max);
+        assert_eq!(deserialized.max_tasks, config.max_tasks);
+        assert_eq!(deserialized.cpu_quota, config.cpu_quota);
+        assert_eq!(deserialized.cpus, config.cpus);
     }
 
     #[test]
@@ -9338,6 +9518,9 @@ hide_dotdirs = [".my_secrets"]
             trust_project_config: vec![],
             update_check: None,
             audit_log: None,
+            memory_max: None,
+            max_tasks: None,
+            cpu_quota: None,
         };
         save(&config);
 
diff --git a/src/config_store.rs b/src/config_store.rs
index 9716324..c72198d 100644
--- a/src/config_store.rs
+++ b/src/config_store.rs
@@ -1560,6 +1560,9 @@ const CONFIG_FIELD_POLICY: &[ConfigFieldPolicy] = &[
     excluded_policy!("hide_dotdirs", Restriction),
     excluded_policy!("mask", Restriction),
     excluded_policy!("deny_paths", Restriction),
+    excluded_policy!("memory_max", Restriction),
+    excluded_policy!("max_tasks", Restriction),
+    excluded_policy!("cpu_quota", Restriction),
     static_policy!("mask_exceptions", Authority, MaskExceptions),
     static_policy!("deny_path_exceptions", Authority, DenyExceptions),
     directional_policy!("no_gpu", Gpu, "gpu"),
@@ -2378,6 +2381,9 @@ mod tests {
         expected_excluded!("hide_dotdirs", Restriction),
         expected_excluded!("mask", Restriction),
         expected_excluded!("deny_paths", Restriction),
+        expected_excluded!("memory_max", Restriction),
+        expected_excluded!("max_tasks", Restriction),
+        expected_excluded!("cpu_quota", Restriction),
         expected_authority!(
             "mask_exceptions",
             Authority,
@@ -2482,6 +2488,9 @@ mod tests {
             "hide_dotdirs" => config.hide_dotdirs = vec![".secret".into()],
             "mask" => config.mask = vec!["/secret".into()],
             "deny_paths" => config.deny_paths = vec!["/denied".into()],
+            "memory_max" => config.memory_max = Some("1G".into()),
+            "max_tasks" => config.max_tasks = Some(100),
+            "cpu_quota" => config.cpu_quota = Some(200),
             "mask_exceptions" => {
                 config.mask_exceptions = vec!["/outside/mask".into()];
             }
diff --git a/src/limits.rs b/src/limits.rs
new file mode 100644
index 0000000..96293d8
--- /dev/null
+++ b/src/limits.rs
@@ -0,0 +1,814 @@
+//! Whole-sandbox resource limits (`--memory`, `--max-tasks`,
+//! `--cpu-quota`, `--cpus`) and the exit report that explains a death.
+//!
+//! rlimits (`sandbox/rlimits.rs`) are per process: NPROC counts every
+//! process the user owns system-wide, and there is no usable memory
+//! rlimit (RLIMIT_AS kills JVMs and Chromium for reserving address
+//! space). A cgroup caps the sandbox as one unit and counts what it
+//! did, which is also what lets the exit report say *why* a child died.
+//!
+//! No privilege is needed. On a systemd host the user manager already
+//! delegates the `memory`, `pids` and `cpu` controllers to the user, and
+//! `systemd-run --user --scope` asks it for a fresh scope: ai-jail
+//! re-execs itself through it, so the supervisor, the proxy threads and
+//! the sandbox share one cgroup. The supervisor staying inside is the
+//! point -- it outlives an OOM-killed child and can still read the
+//! cgroup's counters before the scope is collected.
+//!
+//! `cpuset` is *not* delegated by default and enabling it needs root,
+//! so `--cpus` is CPU affinity instead, owned by `sandbox::affinity`
+//! (moved there for the no-systemd upstream branch); this module only
+//! carries the parsed set into the summary and the audit record.
+
+use std::collections::BTreeSet;
+
+/// Environment marker naming the scope unit ai-jail asked systemd for.
+/// Present only between the re-exec and the check in [`enter_scope`].
+#[cfg(target_os = "linux")]
+const SCOPE_ENV: &str = "AI_JAIL_LIMITS_SCOPE";
+
+/// Resolved, validated limits for one launch.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct ResourceLimits {
+    /// `MemoryMax`, bytes. Swap is pinned to zero alongside it.
+    pub memory: Option<u64>,
+    /// `TasksMax`: processes *and* threads in the whole sandbox.
+    pub max_tasks: Option<u64>,
+    /// `CPUQuota`, percent of one CPU (400 = four full CPUs).
+    pub cpu_quota: Option<u32>,
+    /// CPU affinity for everything inside the sandbox.
+    pub cpus: Option<BTreeSet<usize>>,
+}
+
+impl ResourceLimits {
+    pub fn from_config(config: &crate::config::Config) -> Result<Self, String> {
+        Ok(ResourceLimits {
+            memory: config
+                .memory_max
+                .as_deref()
+                .map(parse_size)
+                .transpose()
+                .map_err(|e| format!("memory limit: {e}"))?,
+            max_tasks: match config.max_tasks {
+                Some(0) => return Err("max-tasks must be at least 1".into()),
+                other => other,
+            },
+            cpu_quota: match config.cpu_quota {
+                Some(0) => return Err("cpu-quota must be at least 1%".into()),
+                other => other,
+            },
+            cpus: config
+                .cpus
+                .as_deref()
+                .map(crate::sandbox::affinity::parse_cpu_list)
+                .transpose()
+                .map_err(|e| format!("cpus: {e}"))?,
+        })
+    }
+
+    /// Limits that only a cgroup can enforce.
+    pub fn needs_scope(&self) -> bool {
+        self.memory.is_some()
+            || self.max_tasks.is_some()
+            || self.cpu_quota.is_some()
+    }
+
+    pub fn is_empty(&self) -> bool {
+        !self.needs_scope() && self.cpus.is_none()
+    }
+
+    /// The `-p KEY=VALUE` properties handed to `systemd-run`. Built only
+    /// from validated numbers, never from user text.
+    pub fn scope_properties(&self) -> Vec<String> {
+        let mut props = Vec::new();
+        if let Some(bytes) = self.memory {
+            props.push(format!("MemoryMax={bytes}"));
+            // Without this the kernel swaps before it kills, and a
+            // runaway agent stalls the whole host instead of dying.
+            props.push("MemorySwapMax=0".into());
+        }
+        if let Some(n) = self.max_tasks {
+            props.push(format!("TasksMax={n}"));
+        }
+        if let Some(pct) = self.cpu_quota {
+            props.push(format!("CPUQuota={pct}%"));
+        }
+        props
+    }
+
+    /// One line for `--dry-run`, `status` and `--verbose`.
+    pub fn describe(&self) -> String {
+        let mut parts = Vec::new();
+        if let Some(bytes) = self.memory {
+            parts.push(format!("memory {}", format_bytes(bytes)));
+        }
+        if let Some(n) = self.max_tasks {
+            parts.push(format!("max-tasks {n}"));
+        }
+        if let Some(pct) = self.cpu_quota {
+            parts.push(format!("cpu-quota {pct}%"));
+        }
+        if let Some(cpus) = &self.cpus {
+            parts.push(format!(
+                "cpus {}",
+                crate::sandbox::affinity::format_cpu_list(cpus)
+            ));
+        }
+        parts.join(", ")
+    }
+
+    pub fn to_json(&self) -> serde_json::Value {
+        serde_json::json!({
+            "memory": self.memory,
+            "max_tasks": self.max_tasks,
+            "cpu_quota": self.cpu_quota,
+            "cpus": self
+                .cpus
+                .as_ref()
+                .map(crate::sandbox::affinity::format_cpu_list),
+        })
+    }
+}
+
+// ── Parsing ────────────────────────────────────────────────────
+
+/// `512M`, `8G`, `1.5G`, `1073741824`. Suffixes are binary (K = 1024),
+/// as systemd reads them. Anything under 1 MiB is refused: it cannot
+/// even start the supervisor, and is almost certainly a missing suffix.
+pub fn parse_size(text: &str) -> Result<u64, String> {
+    let t = text.trim();
+    let (number, shift) = match t.char_indices().last() {
+        Some((i, c)) if c.is_ascii_alphabetic() => {
+            let shift = match c.to_ascii_uppercase() {
+                'K' => 10,
+                'M' => 20,
+                'G' => 30,
+                'T' => 40,
+                _ => return Err(format!("invalid size suffix in {text:?}")),
+            };
+            (&t[..i], shift)
+        }
+        _ => (t, 0),
+    };
+    let bytes = if let Some((whole, frac)) = number.split_once('.') {
+        if shift == 0 || whole.is_empty() || frac.is_empty() {
+            return Err(format!("invalid size {text:?}"));
+        }
+        let whole: u64 = whole
+            .parse()
+            .map_err(|_| format!("invalid size {text:?}"))?;
+        let frac_digits = frac.len().min(6) as u32;
+        let frac: u64 = frac[..frac_digits as usize]
+            .parse()
+            .map_err(|_| format!("invalid size {text:?}"))?;
+        let unit = 1u64 << shift;
+        whole
+            .checked_mul(unit)
+            .and_then(|w| w.checked_add(frac * unit / 10u64.pow(frac_digits)))
+            .ok_or_else(|| format!("size {text:?} is too large"))?
+    } else {
+        let n: u64 = number
+            .parse()
+            .map_err(|_| format!("invalid size {text:?}"))?;
+        n.checked_shl(shift)
+            .filter(|v| v >> shift == n)
+            .ok_or_else(|| format!("size {text:?} is too large"))?
+    };
+    if bytes < 1 << 20 {
+        return Err(format!("size {text:?} is below the 1M minimum"));
+    }
+    Ok(bytes)
+}
+
+/// `400%` or `400`: percent of one CPU.
+pub fn parse_percent(text: &str) -> Result<u32, String> {
+    let t = text.trim();
+    let n: u32 = t
+        .strip_suffix('%')
+        .unwrap_or(t)
+        .parse()
+        .map_err(|_| format!("invalid percentage {text:?}"))?;
+    if n == 0 {
+        return Err("cpu-quota must be at least 1%".into());
+    }
+    Ok(n)
+}
+
+pub fn format_bytes(bytes: u64) -> String {
+    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
+    let mut value = bytes as f64;
+    let mut unit = 0;
+    while value >= 1024.0 && unit < UNITS.len() - 1 {
+        value /= 1024.0;
+        unit += 1;
+    }
+    if unit == 0 {
+        format!("{bytes} B")
+    } else {
+        format!("{value:.1} {}", UNITS[unit])
+    }
+}
+
+// ── Project-layer tightening ───────────────────────────────────
+//
+// An untrusted project `.ai-jail` may only tighten. Each helper returns
+// the value to keep and whether the project value was (partly) dropped.
+// A value that does not parse is kept as-is so the launch fails closed
+// at `ResourceLimits::from_config` instead of silently dropping policy.
+
+pub fn tighten_size(
+    base: Option<String>,
+    local: Option<String>,
+) -> (Option<String>, bool) {
+    match (base, local) {
+        (base, None) => (base, false),
+        (None, local) => (local, false),
+        (Some(b), Some(l)) => match (parse_size(&b), parse_size(&l)) {
+            (Ok(bv), Ok(lv)) if lv <= bv => (Some(l), false),
+            (Ok(_), Ok(_)) => (Some(b), true),
+            _ => (Some(l), false),
+        },
+    }
+}
+
+pub fn tighten_number<T: Ord>(
+    base: Option<T>,
+    local: Option<T>,
+) -> (Option<T>, bool) {
+    match (base, local) {
+        (base, None) => (base, false),
+        (None, local) => (local, false),
+        (Some(b), Some(l)) if l <= b => (Some(l), false),
+        (Some(b), Some(_)) => (Some(b), true),
+    }
+}
+
+/// OOM score bias for everything inside a memory-limited sandbox.
+/// The supervisor shares the cgroup and is what reports the kill, so
+/// the kernel must pick the agent first. Raising the bias needs no
+/// privilege; it is inherited across fork and exec.
+#[cfg(target_os = "linux")]
+const SANDBOX_OOM_SCORE_ADJ: &str = "500";
+
+/// Called by the in-sandbox wrapper before it execs the command. Best
+/// effort: a failure only makes the report less likely to survive, so
+/// it warns instead of refusing the launch.
+#[cfg(target_os = "linux")]
+pub fn prefer_sandbox_as_oom_victim() {
+    if let Err(e) =
+        std::fs::write("/proc/self/oom_score_adj", SANDBOX_OOM_SCORE_ADJ)
+    {
+        crate::output::warn(&format!(
+            "cannot raise the sandbox OOM score ({e}); an OOM kill may hit \
+             the supervisor and lose the exit report"
+        ));
+    }
+}
+
+// ── Scope entry ────────────────────────────────────────────────
+
+/// The `systemd-run` argument vector that re-execs `exe args…` inside a
+/// fresh user scope named `unit`. No shell is involved at any point:
+/// the vector goes straight to execvp.
+#[cfg(target_os = "linux")]
+fn scope_command(
+    limits: &ResourceLimits,
+    unit: &str,
+    exe: &std::path::Path,
+    args: &[std::ffi::OsString],
+) -> Vec<std::ffi::OsString> {
+    let mut argv: Vec<std::ffi::OsString> = vec![
+        "systemd-run".into(),
+        "--user".into(),
+        "--scope".into(),
+        "--quiet".into(),
+        // systemd-run expands $VAR in the command line by default,
+        // which would rewrite any `$` in ai-jail's own arguments.
+        "--expand-environment=no".into(),
+        format!("--unit={unit}").into(),
+    ];
+    for prop in limits.scope_properties() {
+        argv.push("-p".into());
+        argv.push(prop.into());
+    }
+    argv.push("--".into());
+    argv.push(exe.as_os_str().to_owned());
+    argv.extend(args.iter().cloned());
+    argv
+}
+
+/// The cgroup v2 directory of the calling process.
+#[cfg(target_os = "linux")]
+pub fn own_cgroup_dir() -> Option<std::path::PathBuf> {
+    let text = std::fs::read_to_string("/proc/self/cgroup").ok()?;
+    let path = text.lines().find_map(|l| l.strip_prefix("0::"))?;
+    Some(
+        std::path::Path::new("/sys/fs/cgroup")
+            .join(path.trim_start_matches('/')),
+    )
+}
+
+#[cfg(target_os = "linux")]
+fn read_limit(dir: &std::path::Path, file: &str) -> Option<String> {
+    std::fs::read_to_string(dir.join(file))
+        .ok()
+        .map(|s| s.trim().to_string())
+}
+
+/// Whether the cgroup at `dir` enforces `limits`. memory.max is kept in
+/// pages, so a byte count that is not page-aligned reads back rounded
+/// down; anything within one 64 KiB page of the request counts.
+#[cfg(target_os = "linux")]
+fn cgroup_enforces(dir: &std::path::Path, limits: &ResourceLimits) -> bool {
+    if let Some(want) = limits.memory {
+        let Some(got) =
+            read_limit(dir, "memory.max").and_then(|v| v.parse::<u64>().ok())
+        else {
+            return false;
+        };
+        if got > want || want - got >= 64 * 1024 {
+            return false;
+        }
+        if read_limit(dir, "memory.swap.max").as_deref() != Some("0") {
+            return false;
+        }
+    }
+    if let Some(want) = limits.max_tasks
+        && read_limit(dir, "pids.max") != Some(want.to_string())
+    {
+        return false;
+    }
+    if let Some(want) = limits.cpu_quota {
+        let Some(max) = read_limit(dir, "cpu.max") else {
+            return false;
+        };
+        let mut it = max.split_whitespace();
+        let (Some(Ok(quota)), Some(Ok(period))) = (
+            it.next().map(str::parse::<u64>),
+            it.next().map(str::parse::<u64>),
+        ) else {
+            return false;
+        };
+        // systemd rounds the quota to its own granularity; accept 1%.
+        let got = quota * 100 / period.max(1);
+        if got.abs_diff(u64::from(want)) > 1 {
+            return false;
+        }
+    }
+    true
+}
+
+/// Make sure this process runs inside a cgroup enforcing `limits`.
+///
+/// First call: re-exec through `systemd-run --user --scope`, which only
+/// returns here on failure. Second call (inside the scope): prove the
+/// scope is the one requested *and* that the kernel enforces the
+/// limits, or refuse to launch -- a limit the user asked for and did
+/// not get must never be silent.
+#[cfg(target_os = "linux")]
+pub fn enter_scope(
+    limits: &ResourceLimits,
+    verbose: bool,
+) -> Result<(), String> {
+    use std::os::unix::process::CommandExt;
+
+    if let Some(unit) = std::env::var_os(SCOPE_ENV) {
+        // SAFETY: called from run() before any thread is spawned.
+        unsafe { std::env::remove_var(SCOPE_ENV) };
+        let unit = unit.to_string_lossy().into_owned();
+        let dir = own_cgroup_dir()
+            .ok_or("resource limits: cannot read /proc/self/cgroup")?;
+        let in_unit = dir.file_name().is_some_and(|name| {
+            name.to_string_lossy() == format!("{unit}.scope")
+        });
+        if !in_unit {
+            return Err(format!(
+                "resource limits: expected to run in {unit}.scope, found {}",
+                dir.display()
+            ));
+        }
+        if !cgroup_enforces(&dir, limits) {
+            return Err(format!(
+                "resource limits: {} does not enforce {} -- is the \
+                 controller delegated to the user manager?",
+                dir.display(),
+                limits.describe()
+            ));
+        }
+        if verbose {
+            crate::output::verbose(&format!(
+                "Resource limits: {} ({})",
+                limits.describe(),
+                dir.display()
+            ));
+        }
+        return Ok(());
+    }
+
+    if std::env::var_os("XDG_RUNTIME_DIR").is_none() {
+        return Err(
+            "resource limits need a systemd user session (XDG_RUNTIME_DIR \
+             is unset); --memory, --max-tasks and --cpu-quota are \
+             unavailable here"
+                .into(),
+        );
+    }
+    let exe = std::env::current_exe()
+        .map_err(|e| format!("resource limits: cannot resolve ai-jail: {e}"))?;
+    let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
+    let unit = format!("ai-jail-{}", std::process::id());
+    let argv = scope_command(limits, &unit, &exe, &args);
+    let mut cmd = std::process::Command::new(&argv[0]);
+    cmd.args(&argv[1..]).env(SCOPE_ENV, &unit);
+    // Replaces this process: same PID, stdio and signal disposition, so
+    // an ACP client talking over stdin/stdout never sees the hop.
+    let err = CommandExt::exec(&mut cmd);
+    Err(format!(
+        "resource limits need systemd-run (systemd user session): {err}"
+    ))
+}
+
+// ── Accounting and the exit report ─────────────────────────────
+
+/// What the cgroup counted over the launch. Every field is optional
+/// because the kernel omits files for controllers that are not enabled.
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct CgroupReport {
+    pub memory_peak: Option<u64>,
+    /// Processes the kernel OOM-killed inside the cgroup.
+    pub oom_kills: u64,
+    /// Times the memory limit was hit (reclaim was forced).
+    pub memory_max_hits: u64,
+    /// fork/clone attempts refused by the task limit.
+    pub tasks_refused: u64,
+    pub cpu_usage_usec: Option<u64>,
+    pub cpu_throttled_usec: Option<u64>,
+}
+
+#[cfg(target_os = "linux")]
+fn keyed(text: &str, key: &str) -> Option<u64> {
+    text.lines().find_map(|line| {
+        let (k, v) = line.split_once(' ')?;
+        (k == key).then(|| v.trim().parse().ok()).flatten()
+    })
+}
+
+impl CgroupReport {
+    #[cfg(target_os = "linux")]
+    pub fn read(dir: &std::path::Path) -> Self {
+        let events = read_limit(dir, "memory.events").unwrap_or_default();
+        let pids = read_limit(dir, "pids.events").unwrap_or_default();
+        let cpu = read_limit(dir, "cpu.stat").unwrap_or_default();
+        CgroupReport {
+            memory_peak: read_limit(dir, "memory.peak")
+                .and_then(|v| v.parse().ok()),
+            oom_kills: keyed(&events, "oom_kill").unwrap_or(0),
+            memory_max_hits: keyed(&events, "max").unwrap_or(0),
+            tasks_refused: keyed(&pids, "max").unwrap_or(0),
+            cpu_usage_usec: keyed(&cpu, "usage_usec"),
+            cpu_throttled_usec: keyed(&cpu, "throttled_usec"),
+        }
+    }
+
+    pub fn to_json(&self) -> serde_json::Value {
+        serde_json::json!({
+            "memory_peak": self.memory_peak,
+            "oom_kills": self.oom_kills,
+            "memory_max_hits": self.memory_max_hits,
+            "tasks_refused": self.tasks_refused,
+            "cpu_usage_usec": self.cpu_usage_usec,
+            "cpu_throttled_usec": self.cpu_throttled_usec,
+        })
+    }
+}
+
+/// Signals a user or a harness sends on purpose; their deaths need no
+/// explanation.
+fn deliberate_signal(sig: i32) -> bool {
+    matches!(sig, 1 | 2 | 13 | 15)
+}
+
+/// What the sandbox's cgroup adds to the exit line `exit_reason` already
+/// prints (upstream v3.6.0, #247): an OOM kill at `--memory`, forks refused
+/// at `--max-tasks`, and whether a SIGKILL was this sandbox's memory limit.
+/// A death the signal alone explains (SIGXCPU, SIGXFSZ, SIGSEGV...) is
+/// `exit_reason`'s line only, so no launch prints the same signal twice.
+/// `None` when the cgroup has nothing to add.
+pub fn describe_exit(
+    exit_code: i32,
+    limits: &ResourceLimits,
+    report: Option<&CgroupReport>,
+) -> Option<String> {
+    let signal = (129..=192).contains(&exit_code).then(|| exit_code - 128);
+    let mut lines = Vec::new();
+
+    if let Some(r) = report {
+        if r.oom_kills > 0 {
+            let limit = limits
+                .memory
+                .map(format_bytes)
+                .unwrap_or_else(|| "unset".into());
+            let peak = r
+                .memory_peak
+                .map(format_bytes)
+                .unwrap_or_else(|| "unknown".into());
+            lines.push(format!(
+                "out of memory: the kernel killed {} process(es) at the \
+                 sandbox memory limit ({limit}, peak {peak})",
+                r.oom_kills
+            ));
+        }
+        if r.tasks_refused > 0 {
+            lines.push(format!(
+                "task limit reached: {} fork/clone attempt(s) refused \
+                 (max-tasks {})",
+                r.tasks_refused,
+                limits.max_tasks.map_or("unset".into(), |n| n.to_string())
+            ));
+        }
+    }
+
+    match signal {
+        Some(sig) if !lines.is_empty() || deliberate_signal(sig) => {}
+        Some(9) if limits.memory.is_some() => lines.push(
+            "the SIGKILL was not the sandbox memory limit (no OOM kill was \
+             counted in the sandbox cgroup)"
+                .into(),
+        ),
+        // Without --memory nothing proves the cause, and upstream names a
+        // SIGKILL alone (run_observability: exit_sigkill_names_the_signal_alone).
+        Some(_) | None => {}
+    }
+
+    if lines.is_empty() {
+        None
+    } else {
+        Some(format!(
+            "sandbox exited with {exit_code}: {}",
+            lines.join("; ")
+        ))
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn cpus(list: &[usize]) -> BTreeSet<usize> {
+        list.iter().copied().collect()
+    }
+
+    #[test]
+    fn size_parses_binary_suffixes() {
+        assert_eq!(parse_size("1M").unwrap(), 1 << 20);
+        assert_eq!(parse_size("8G").unwrap(), 8 << 30);
+        assert_eq!(parse_size("8g").unwrap(), 8 << 30);
+        assert_eq!(parse_size("1T").unwrap(), 1 << 40);
+        assert_eq!(parse_size("1.5G").unwrap(), 3 << 29);
+        assert_eq!(parse_size(" 2048K ").unwrap(), 2 << 20);
+        assert_eq!(parse_size("1073741824").unwrap(), 1 << 30);
+    }
+
+    #[test]
+    fn size_refuses_garbage_tiny_and_overflow() {
+        for bad in ["", "G", "8X", "-1G", "1.G", ".5G", "1.5", "8 G", "abc"] {
+            assert!(parse_size(bad).is_err(), "{bad:?} should fail");
+        }
+        assert!(parse_size("512K").is_err(), "below 1M");
+        assert!(parse_size("100").is_err(), "bytes without suffix, tiny");
+        assert!(parse_size("99999999999T").is_err(), "overflow");
+    }
+
+    #[test]
+    fn percent_accepts_suffix_or_bare() {
+        assert_eq!(parse_percent("400%").unwrap(), 400);
+        assert_eq!(parse_percent("50").unwrap(), 50);
+        assert!(parse_percent("0%").is_err());
+        assert!(parse_percent("-5%").is_err());
+        assert!(parse_percent("lots").is_err());
+    }
+
+    #[test]
+    fn scope_properties_pin_swap_with_memory() {
+        let limits = ResourceLimits {
+            memory: Some(8 << 30),
+            max_tasks: Some(2000),
+            cpu_quota: Some(400),
+            cpus: None,
+        };
+        assert_eq!(
+            limits.scope_properties(),
+            vec![
+                "MemoryMax=8589934592",
+                "MemorySwapMax=0",
+                "TasksMax=2000",
+                "CPUQuota=400%",
+            ]
+        );
+        assert!(limits.needs_scope());
+    }
+
+    #[test]
+    fn cpus_alone_need_no_scope() {
+        let limits = ResourceLimits {
+            cpus: Some(cpus(&[0])),
+            ..Default::default()
+        };
+        assert!(!limits.needs_scope());
+        assert!(!limits.is_empty());
+        assert!(limits.scope_properties().is_empty());
+    }
+
+    #[cfg(target_os = "linux")]
+    #[test]
+    fn scope_command_disables_expansion_and_keeps_args_verbatim() {
+        let limits = ResourceLimits {
+            memory: Some(1 << 30),
+            ..Default::default()
+        };
+        let argv = scope_command(
+            &limits,
+            "ai-jail-42",
+            std::path::Path::new("/usr/bin/ai-jail"),
+            &["--env".into(), "X=$HOME".into(), "claude".into()],
+        );
+        let argv: Vec<String> = argv
+            .iter()
+            .map(|a| a.to_string_lossy().into_owned())
+            .collect();
+        assert_eq!(argv[0], "systemd-run");
+        assert!(argv.contains(&"--expand-environment=no".to_string()));
+        assert!(argv.contains(&"--unit=ai-jail-42".to_string()));
+        let sep = argv.iter().position(|a| a == "--").unwrap();
+        assert_eq!(
+            &argv[sep + 1..],
+            &["/usr/bin/ai-jail", "--env", "X=$HOME", "claude"]
+        );
+    }
+
+    #[test]
+    fn tighten_size_keeps_the_smaller() {
+        let s = |v: &str| Some(v.to_string());
+        assert_eq!(tighten_size(s("8G"), s("4G")), (s("4G"), false));
+        assert_eq!(tighten_size(s("4G"), s("8G")), (s("4G"), true));
+        assert_eq!(tighten_size(None, s("4G")), (s("4G"), false));
+        assert_eq!(tighten_size(s("4G"), None), (s("4G"), false));
+        // Unparsable project value is kept, so the launch fails closed.
+        assert_eq!(tighten_size(s("4G"), s("lots")), (s("lots"), false));
+    }
+
+    #[test]
+    fn tighten_number_keeps_the_smaller() {
+        assert_eq!(tighten_number(Some(100), Some(50)), (Some(50), false));
+        assert_eq!(tighten_number(Some(50), Some(100)), (Some(50), true));
+        assert_eq!(tighten_number(None, Some(7)), (Some(7), false));
+        assert_eq!(tighten_number::<u32>(None, None), (None, false));
+    }
+
+    #[cfg(target_os = "linux")]
+    fn scratch(tag: &str) -> std::path::PathBuf {
+        let dir = std::env::temp_dir()
+            .join(format!("ai-jail-{tag}-test-{}", std::process::id()));
+        std::fs::create_dir_all(&dir).unwrap();
+        dir
+    }
+
+    #[cfg(target_os = "linux")]
+    #[test]
+    fn cgroup_enforcement_is_read_back_from_files() {
+        let dir = scratch("limits");
+        let write = |f: &str, v: &str| std::fs::write(dir.join(f), v).unwrap();
+        write("memory.max", "8589934592\n");
+        write("memory.swap.max", "0\n");
+        write("pids.max", "2000\n");
+        write("cpu.max", "400000 100000\n");
+        let limits = ResourceLimits {
+            memory: Some(8 << 30),
+            max_tasks: Some(2000),
+            cpu_quota: Some(400),
+            cpus: None,
+        };
+        assert!(cgroup_enforces(&dir, &limits));
+
+        write("memory.swap.max", "max\n");
+        assert!(!cgroup_enforces(&dir, &limits), "swap must be pinned");
+        write("memory.swap.max", "0\n");
+        write("pids.max", "max\n");
+        assert!(!cgroup_enforces(&dir, &limits), "pids.max unset");
+        write("pids.max", "2000\n");
+        write("cpu.max", "max 100000\n");
+        assert!(!cgroup_enforces(&dir, &limits), "cpu.max unset");
+        write("cpu.max", "400000 100000\n");
+        write("memory.max", "max\n");
+        assert!(!cgroup_enforces(&dir, &limits), "memory.max unset");
+        std::fs::remove_dir_all(&dir).unwrap();
+    }
+
+    #[cfg(target_os = "linux")]
+    #[test]
+    fn cgroup_report_reads_kernel_counters() {
+        let dir = scratch("report");
+        std::fs::write(
+            dir.join("memory.events"),
+            "low 0\nhigh 0\nmax 40\noom 1\noom_kill 1\noom_group_kill 0\n",
+        )
+        .unwrap();
+        std::fs::write(dir.join("memory.peak"), "67108864\n").unwrap();
+        std::fs::write(dir.join("pids.events"), "max 3\n").unwrap();
+        std::fs::write(
+            dir.join("cpu.stat"),
+            "usage_usec 23737\nuser_usec 1\nsystem_usec 2\nnr_periods 0\n\
+             nr_throttled 0\nthrottled_usec 0\n",
+        )
+        .unwrap();
+        let report = CgroupReport::read(&dir);
+        assert_eq!(
+            report,
+            CgroupReport {
+                memory_peak: Some(64 << 20),
+                oom_kills: 1,
+                memory_max_hits: 40,
+                tasks_refused: 3,
+                cpu_usage_usec: Some(23737),
+                cpu_throttled_usec: Some(0),
+            }
+        );
+        std::fs::remove_dir_all(&dir).unwrap();
+    }
+
+    #[cfg(target_os = "linux")]
+    #[test]
+    fn cgroup_report_tolerates_missing_files() {
+        let report =
+            CgroupReport::read(std::path::Path::new("/nonexistent/ai-jail"));
+        assert_eq!(report, CgroupReport::default());
+    }
+
+    #[test]
+    fn exit_report_names_the_oom_kill() {
+        let limits = ResourceLimits {
+            memory: Some(64 << 20),
+            ..Default::default()
+        };
+        let report = CgroupReport {
+            memory_peak: Some(64 << 20),
+            oom_kills: 1,
+            ..Default::default()
+        };
+        let msg = describe_exit(137, &limits, Some(&report)).unwrap();
+        assert!(msg.contains("out of memory"), "{msg}");
+        assert!(msg.contains("64.0 MiB"), "{msg}");
+        assert!(!msg.contains("SIGKILL"), "{msg}");
+    }
+
+    #[test]
+    fn exit_report_names_refused_forks() {
+        let limits = ResourceLimits {
+            max_tasks: Some(20),
+            ..Default::default()
+        };
+        let report = CgroupReport {
+            tasks_refused: 5,
+            ..Default::default()
+        };
+        let msg = describe_exit(1, &limits, Some(&report)).unwrap();
+        assert!(msg.contains("5 fork/clone"), "{msg}");
+        assert!(msg.contains("max-tasks 20"), "{msg}");
+    }
+
+    #[test]
+    fn exit_report_guesses_no_cause_for_an_unlimited_sigkill() {
+        // No --memory, no cgroup evidence: exit_reason's "killed by
+        // SIGKILL" is the whole story.
+        assert_eq!(describe_exit(137, &ResourceLimits::default(), None), None);
+    }
+
+    #[test]
+    fn exit_report_leaves_signal_only_deaths_to_exit_reason() {
+        // exit_reason already prints "sandbox exited with N: killed by
+        // SIG..." for these; a second line would repeat it.
+        let none = ResourceLimits::default();
+        assert_eq!(describe_exit(152, &none, None), None, "SIGXCPU");
+        assert_eq!(describe_exit(153, &none, None), None, "SIGXFSZ");
+        assert_eq!(describe_exit(139, &none, None), None, "SIGSEGV");
+        // ...unless the cgroup counted something the signal does not say.
+        let report = CgroupReport {
+            oom_kills: 1,
+            ..CgroupReport::default()
+        };
+        assert!(describe_exit(139, &none, Some(&report)).is_some());
+    }
+
+    #[test]
+    fn exit_report_stays_quiet_for_normal_and_deliberate_exits() {
+        let none = ResourceLimits::default();
+        assert_eq!(describe_exit(0, &none, None), None);
+        assert_eq!(describe_exit(1, &none, None), None);
+        assert_eq!(describe_exit(130, &none, None), None, "SIGINT");
+        assert_eq!(describe_exit(143, &none, None), None, "SIGTERM");
+        assert_eq!(
+            describe_exit(0, &none, Some(&CgroupReport::default())),
+            None
+        );
+    }
+}
diff --git a/src/main.rs b/src/main.rs
index 8187f57..688734f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -16,6 +16,7 @@ mod forge_auth;
 mod fsutil;
 mod github_auth;
 mod integration;
+mod limits;
 mod onboarding;
 mod output;
 mod proxy;
@@ -319,6 +320,22 @@ fn untrusted_project_command_carries_credentials(
 /// `--allow-tcp-port` stays dead (the filtered-egress proxy is the
 /// strictly better answer, docs/connect-proxy-plan.md), and filtered
 /// egress combines with neither unrestricted network nor browser mode.
+/// Resolve and check the resource limits before anything is launched.
+/// Every refusal here is a limit the user asked for and would not get.
+fn validate_resource_limits(
+    config: &config::Config,
+) -> Result<limits::ResourceLimits, String> {
+    let limits = limits::ResourceLimits::from_config(config)?;
+    #[cfg(not(target_os = "linux"))]
+    if !limits.is_empty() {
+        return Err(
+            "--memory, --max-tasks, --cpu-quota and --cpus are Linux only"
+                .into(),
+        );
+    }
+    Ok(limits)
+}
+
 fn validate_network_flags(config: &config::Config) -> Result<(), String> {
     if !config.allow_tcp_ports().is_empty() {
         return Err("--allow-tcp-port is disabled (UDP cannot be isolated); use --allow-host for filtered egress instead".into());
@@ -1143,6 +1160,13 @@ fn run_landlock_exec(cli: &cli::CliArgs) -> Result<i32, String> {
     #[cfg(target_os = "linux")]
     drop(ecryptfs_lower_fds);
 
+    // --memory: the supervisor sits in the same cgroup and must outlive
+    // an OOM kill to report it, so the sandbox volunteers as the victim.
+    #[cfg(target_os = "linux")]
+    if config.memory_max.is_some() {
+        limits::prefer_sandbox_as_oom_victim();
+    }
+
     // --cpus: pin this process (and so the command it becomes) before
     // seccomp below refuses sched_setaffinity for good. Order: bridges,
     // Landlock, affinity, seccomp, rlimits, then the agent. Linux only:
@@ -1940,6 +1964,7 @@ fn run(
         }
         _ => None,
     };
+    let resource_limits = validate_resource_limits(&config)?;
 
     // Handle status command
     if cli.status {
@@ -2062,6 +2087,17 @@ fn run(
         return Ok(0);
     }
 
+    // Whole-sandbox limits need a cgroup: re-exec through a systemd
+    // user scope (this call does not return on the way in), then prove
+    // on the way back that the limits are really enforced. Placed after
+    // the status/init/bootstrap returns and before the launch is
+    // finalized, so no thread, socket or temp file exists yet and the gh
+    // token is fetched once, inside the scope, never crossing argv.
+    #[cfg(target_os = "linux")]
+    if resource_limits.needs_scope() && !cli.dry_run {
+        limits::enter_scope(&resource_limits, cli.verbose)?;
+    }
+
     let finalized = match prepared_launch.take() {
         Some(finalized) => finalized,
         None => finalize_launch_config_with_ssh(
@@ -2303,6 +2339,23 @@ fn run(
         if let Some(cpus) = &config.cpus {
             output::dry_run_line(&format!("cpus={cpus}"));
         }
+        if resource_limits.needs_scope() {
+            output::info(&format!(
+                "Resource limits: {} (via systemd-run --user --scope {})",
+                resource_limits.describe(),
+                resource_limits
+                    .scope_properties()
+                    .iter()
+                    .map(|p| format!("-p {p}"))
+                    .collect::<Vec<_>>()
+                    .join(" ")
+            ));
+        } else if !resource_limits.is_empty() {
+            output::info(&format!(
+                "Resource limits: {}",
+                resource_limits.describe()
+            ));
+        }
         let formatted = sandbox::dry_run(
             &guard,
             config,
@@ -2657,6 +2710,26 @@ fn run(
         );
     }
 
+    // Read what the sandbox's cgroup counted while the scope still
+    // exists (this process keeps it alive), and explain a death the
+    // exit code alone cannot -- also under --exec, where a harness
+    // otherwise sees only "137".
+    #[cfg(target_os = "linux")]
+    let cgroup_report = if resource_limits.needs_scope() {
+        limits::own_cgroup_dir().map(|dir| limits::CgroupReport::read(&dir))
+    } else {
+        None
+    };
+    #[cfg(not(target_os = "linux"))]
+    let cgroup_report: Option<limits::CgroupReport> = None;
+    if let Some(msg) = limits::describe_exit(
+        exit_code,
+        &resource_limits,
+        cgroup_report.as_ref(),
+    ) {
+        output::error(&msg);
+    }
+
     // Append the launch record only now: exit code and duration are
     // what make it an audit trail rather than a log of intentions.
     if let Some(log) = &audit_log {
@@ -2694,6 +2767,9 @@ fn run(
             duration: launch_start.elapsed(),
             rlimits: &effective_limits,
             cpus: config.cpus.as_deref(),
+            limits: (!resource_limits.is_empty())
+                .then(|| resource_limits.to_json()),
+            cgroup: cgroup_report.as_ref().map(limits::CgroupReport::to_json),
         }));
     }
 
diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs
index f2e6eaf..b270cd5 100644
--- a/src/sandbox/bwrap.rs
+++ b/src/sandbox/bwrap.rs
@@ -1421,6 +1421,12 @@ fn landlock_wrapper_args_with_ecryptfs(
         args.push("--cpus".into());
         args.push(cpus.clone());
     }
+    // --memory: the wrapper marks the sandbox as the preferred OOM
+    // victim, so the supervisor survives to report the kill.
+    if let Some(memory) = &config.memory_max {
+        args.push("--memory".into());
+        args.push(memory.clone());
+    }
 
     args.push(if config.gpu_enabled() {
         "--gpu".into()
diff --git a/tests/resource_limits.rs b/tests/resource_limits.rs
new file mode 100644
index 0000000..83c93e0
--- /dev/null
+++ b/tests/resource_limits.rs
@@ -0,0 +1,348 @@
+// End-to-end tests for the whole-sandbox resource limits: `--cpus`
+// (CPU affinity locked by seccomp) and `--memory` / `--max-tasks` /
+// `--cpu-quota` (a systemd user scope), plus the exit report that
+// explains a death.
+//
+// Linux-only. Tests needing bwrap skip when it cannot create user
+// namespaces; tests needing a cgroup skip when `systemd-run --user
+// --scope` is unavailable (no systemd user session).
+#![cfg(target_os = "linux")]
+
+use std::path::PathBuf;
+use std::process::{Command, Output};
+use std::sync::OnceLock;
+
+fn bwrap_available() -> bool {
+    static RESULT: OnceLock<bool> = OnceLock::new();
+    *RESULT.get_or_init(|| {
+        Command::new("bwrap")
+            .args([
+                "--ro-bind",
+                "/",
+                "/",
+                "--proc",
+                "/proc",
+                "--unshare-pid",
+                "--",
+                "true",
+            ])
+            .output()
+            .map(|o| o.status.success())
+            .unwrap_or(false)
+    })
+}
+
+fn scope_available() -> bool {
+    static RESULT: OnceLock<bool> = OnceLock::new();
+    *RESULT.get_or_init(|| {
+        Command::new("systemd-run")
+            .args([
+                "--user",
+                "--scope",
+                "--quiet",
+                "-p",
+                "TasksMax=100",
+                "true",
+            ])
+            .output()
+            .map(|o| o.status.success())
+            .unwrap_or(false)
+    })
+}
+
+macro_rules! require {
+    ($cond:expr, $why:literal) => {
+        if !$cond {
+            eprintln!(concat!("SKIPPED: ", $why));
+            return;
+        }
+    };
+}
+
+fn ai_jail() -> PathBuf {
+    PathBuf::from(env!("CARGO_BIN_EXE_ai-jail"))
+}
+
+fn test_tree(name: &str) -> (PathBuf, PathBuf) {
+    let root = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
+        .join(format!("resource-limits-{name}-{}", std::process::id()));
+    let _ = std::fs::remove_dir_all(&root);
+    let project = root.join("project");
+    let home = root.join("home");
+    std::fs::create_dir_all(&project).unwrap();
+    std::fs::create_dir_all(&home).unwrap();
+    (project, home)
+}
+
+fn run_in(name: &str, args: &[&str]) -> (Output, PathBuf) {
+    let (project, home) = test_tree(name);
+    let output = Command::new(ai_jail())
+        .args(["--clean", "--no-save-config", "--no-status-bar"])
+        .args(args)
+        .current_dir(&project)
+        .env("HOME", &home)
+        .env_remove("AI_JAIL_LIMITS_SCOPE")
+        .output()
+        .expect("failed to run ai-jail");
+    (output, home)
+}
+
+fn text(bytes: &[u8]) -> String {
+    String::from_utf8_lossy(bytes).into_owned()
+}
+
+/// The first CPU this test process may run on (not necessarily 0).
+fn first_allowed_cpu() -> usize {
+    let status = std::fs::read_to_string("/proc/self/status").unwrap();
+    let list = status
+        .lines()
+        .find_map(|l| l.strip_prefix("Cpus_allowed_list:"))
+        .unwrap()
+        .trim();
+    list.split([',', '-']).next().unwrap().parse().unwrap()
+}
+
+fn launch_record(home: &std::path::Path) -> serde_json::Value {
+    let log = home.join(".local/share/ai-jail/history.jsonl");
+    let content = std::fs::read_to_string(&log).expect("audit log written");
+    content
+        .lines()
+        .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
+        .find(|v| v["type"] == "launch")
+        .expect("launch record")
+}
+
+// ── --cpus ─────────────────────────────────────────────────────
+
+#[test]
+fn cpus_pin_the_sandbox_and_cannot_be_widened() {
+    require!(bwrap_available(), "bwrap cannot create user namespaces");
+    let cpu = first_allowed_cpu().to_string();
+    let (output, _) = run_in(
+        "cpus-pin",
+        &[
+            "--exec",
+            "--cpus",
+            &cpu,
+            "bash",
+            "-c",
+            "grep Cpus_allowed_list /proc/self/status; \
+             echo nproc=$(nproc); \
+             taskset -p -c 0-$(( $(getconf _NPROCESSORS_CONF) - 1 )) $$ \
+               >/dev/null 2>&1; echo widen=$?; \
+             grep Cpus_allowed_list /proc/self/status",
+        ],
+    );
+    let stdout = text(&output.stdout);
+    assert!(output.status.success(), "{stdout} {}", text(&output.stderr));
+    let lists: Vec<&str> = stdout
+        .lines()
+        .filter_map(|l| l.strip_prefix("Cpus_allowed_list:"))
+        .map(str::trim)
+        .collect();
+    assert_eq!(lists, vec![cpu.as_str(), cpu.as_str()], "{stdout}");
+    assert!(stdout.contains("nproc=1"), "{stdout}");
+    assert!(
+        !stdout.contains("widen=0"),
+        "taskset widened the CPU set: {stdout}"
+    );
+}
+
+#[test]
+fn cpus_without_seccomp_are_refused() {
+    let (output, _) = run_in(
+        "cpus-noseccomp",
+        &["--exec", "--no-seccomp", "--cpus", "0", "true"],
+    );
+    assert!(!output.status.success());
+    assert!(
+        text(&output.stderr).contains("--cpus needs seccomp"),
+        "{}",
+        text(&output.stderr)
+    );
+}
+
+#[test]
+fn cpus_the_host_does_not_have_are_refused() {
+    let (output, _) =
+        run_in("cpus-missing", &["--exec", "--cpus", "1023", "true"]);
+    assert!(!output.status.success());
+    assert!(
+        text(&output.stderr).contains("cannot use: 1023"),
+        "{}",
+        text(&output.stderr)
+    );
+}
+
+// ── cgroup scope ───────────────────────────────────────────────
+
+#[test]
+fn memory_limit_death_is_reported_as_oom() {
+    require!(bwrap_available(), "bwrap cannot create user namespaces");
+    require!(scope_available(), "no systemd user session");
+    let (output, home) = run_in(
+        "oom",
+        &[
+            "--exec",
+            "--audit-log",
+            "--memory",
+            "64M",
+            "bash",
+            "-c",
+            // Command substitution holds the whole output in memory.
+            "x=$(head -c 256M /dev/zero | tr '\\0' a); echo ${#x}",
+        ],
+    );
+    let stderr = text(&output.stderr);
+    assert_ne!(output.status.code(), Some(0), "{stderr}");
+    assert!(stderr.contains("out of memory"), "{stderr}");
+    assert!(stderr.contains("64.0 MiB"), "{stderr}");
+
+    let record = launch_record(&home);
+    assert_eq!(record["limits"]["memory"], 64 << 20);
+    assert!(
+        record["cgroup"]["oom_kills"].as_u64().unwrap() >= 1,
+        "{record}"
+    );
+    assert!(record["cgroup"]["memory_peak"].as_u64().is_some());
+}
+
+#[test]
+fn task_limit_refusals_are_reported() {
+    require!(bwrap_available(), "bwrap cannot create user namespaces");
+    require!(scope_available(), "no systemd user session");
+    let (output, _) = run_in(
+        "tasks",
+        &[
+            "--exec",
+            "--max-tasks",
+            "40",
+            "bash",
+            "-c",
+            "for i in $(seq 80); do sleep 1 & done 2>/dev/null; wait",
+        ],
+    );
+    let stderr = text(&output.stderr);
+    assert!(stderr.contains("task limit reached"), "{stderr}");
+    assert!(stderr.contains("max-tasks 40"), "{stderr}");
+}
+
+#[test]
+fn a_clean_run_under_limits_is_quiet_and_accounted() {
+    require!(bwrap_available(), "bwrap cannot create user namespaces");
+    require!(scope_available(), "no systemd user session");
+    let (output, home) = run_in(
+        "clean",
+        &[
+            "--exec",
+            "--audit-log",
+            "--memory",
+            "512M",
+            "--max-tasks",
+            "500",
+            "--cpu-quota",
+            "150%",
+            "bash",
+            "-c",
+            "exit 4",
+        ],
+    );
+    assert_eq!(output.status.code(), Some(4), "{}", text(&output.stderr));
+    // v3 security-warns that the hidden legacy `.ai-jail` mask has nothing
+    // to cover in a fresh project; that notice is upstream's, not a report.
+    let stderr = text(&output.stderr);
+    let report: Vec<&str> = stderr
+        .lines()
+        .filter(|line| {
+            !line.ends_with(".ai-jail does not exist; rule not applied")
+        })
+        .collect();
+    assert!(report.is_empty(), "no report for a normal exit: {stderr}");
+    let record = launch_record(&home);
+    assert_eq!(record["exit_code"], 4);
+    assert_eq!(record["limits"]["max_tasks"], 500);
+    assert_eq!(record["limits"]["cpu_quota"], 150);
+    assert_eq!(record["cgroup"]["oom_kills"], 0);
+    assert!(record["cgroup"]["cpu_usage_usec"].as_u64().is_some());
+}
+
+#[test]
+fn the_sandbox_not_the_supervisor_is_the_oom_victim() {
+    require!(bwrap_available(), "bwrap cannot create user namespaces");
+    require!(scope_available(), "no systemd user session");
+    let read = "cat /proc/self/oom_score_adj";
+    let (limited, _) = run_in(
+        "oomadj",
+        &["--exec", "--memory", "256M", "bash", "-c", read],
+    );
+    assert_eq!(text(&limited.stdout).trim(), "500");
+    let (plain, _) = run_in("oomadj-plain", &["--exec", "bash", "-c", read]);
+    assert_ne!(
+        text(&plain.stdout).trim(),
+        "500",
+        "no --memory, no bias: behaviour unchanged"
+    );
+}
+
+#[test]
+fn arguments_survive_the_scope_hop_verbatim() {
+    require!(bwrap_available(), "bwrap cannot create user namespaces");
+    require!(scope_available(), "no systemd user session");
+    let (output, _) = run_in(
+        "verbatim",
+        &[
+            "--exec",
+            "--memory",
+            "256M",
+            "bash",
+            "-c",
+            "printf '%s|%s' \"$1\" \"$2\"",
+            "_",
+            "lit$HOME",
+            "a b;c",
+        ],
+    );
+    assert!(output.status.success(), "{}", text(&output.stderr));
+    assert_eq!(text(&output.stdout), "lit$HOME|a b;c");
+}
+
+#[test]
+fn a_spoofed_scope_marker_is_refused() {
+    // The marker only names the scope to check; claiming one that this
+    // process is not in must stop the launch, not skip the limits.
+    let (project, home) = test_tree("spoof");
+    let output = Command::new(ai_jail())
+        .args([
+            "--clean",
+            "--no-save-config",
+            "--exec",
+            "--memory",
+            "256M",
+            "true",
+        ])
+        .current_dir(&project)
+        .env("HOME", &home)
+        .env("AI_JAIL_LIMITS_SCOPE", "not-this-one")
+        .output()
+        .unwrap();
+    assert!(!output.status.success());
+    assert!(
+        text(&output.stderr).contains("expected to run in not-this-one.scope"),
+        "{}",
+        text(&output.stderr)
+    );
+}
+
+#[test]
+fn dry_run_names_the_scope_without_entering_it() {
+    let (output, _) = run_in(
+        "dryrun",
+        &["--dry-run", "--memory", "1G", "--cpus", "0", "bash"],
+    );
+    assert!(output.status.success(), "{}", text(&output.stderr));
+    let stderr = text(&output.stderr);
+    assert!(stderr.contains("-p MemoryMax=1073741824"), "{stderr}");
+    assert!(stderr.contains("-p MemorySwapMax=0"), "{stderr}");
+    let stdout = text(&output.stdout);
+    assert!(stdout.contains("--cpus 0"), "wrapper gets --cpus: {stdout}");
+}
