A read-only --map nested directly inside a --rw-map stays read-only, instead
of the writable parent being dropped.

ai-jail 3.7.1 refuses any --rw-map that overlaps a --map destination in either
direction: `--rw-map S --map S/hooks` prints "ignoring rw-map that overlaps a
read-only map destination" and the sandbox loses S altogether. The reverse
rule (an RW parent re-exposing its RO child) was needed when RW maps were
emitted after RO maps; since upstream sorts extra mounts parent-first (#183),
the child is bound after, and on top of, its parent, so the obvious way to
protect agent state -- a writable ~/.claude with read-only hooks/ and
settings.json -- can now be expressed.

The parent is kept only where the child can actually hold. An RW parent is
refused, as before and with a security warning naming both paths and the
reason, unless every requested RO map strictly inside it:

  - is a direct child (a deeper one sits under an ordinary directory the agent
    can rename away, then recreate the path writable: measured,
    `mv S/a S/a2; mkdir -p S/a/b`);
  - exists, and its mount point exists under the parent's source (a missing
    child is never mounted -- the parent would fail open -- and a missing mount
    point would be created on the host by bwrap as a side effect of launch);
  - is not a symlink on the host (bwrap follows it).

Why a direct child holds: its only ancestors inside the writable parent are
the parent's mount root and the child itself, both mount points, which the
kernel locks in the sandbox's namespaces -- they cannot be unmounted,
remounted or renamed, even with --no-seccomp --no-landlock. Landlock grants
are additive, so the parent's write rule covers the child: the bind mount
alone keeps it read-only, which docs/SECURITY.md and the Landlock comment now
say. An --rw-map at or under a --map is still refused (the message now says
"at or under"), same-path conflicts still resolve to read-only, and a project
.ai-jail's rw_maps that overlap a trusted read-only map are still dropped in
config.rs, in both directions: an untrusted project config cannot open a
writable parent around a read-only map. Linux only; seatbelt has no overlap
rule. The README states the remaining limits (per destination, not per file;
any map two or more levels inside a writable area can be moved away whole).

Carried from the fork's feat/nested-ro-maps (7b9e999, e1f5bf9, ac047fd,
written against v3.2.0 and never merged anywhere), re-derived onto 3.7.1: the
code applied with offsets only; the README section moved to just before
"Ephemeral home and temp" so the patch also applies to pristine v3.7.1 alone
(offsets, no fuzz), and tests/nested_maps.rs now uses tests/common (its
sandbox lock, binary path and bwrap probe, which needs a fresh /proc and so
skips in a container that cannot mount one) and runs each launch with a
private HOME and XDG_CONFIG_HOME.

Tests: unit tests per refusal reason with injectable existence and symlink
predicates (including a SOURCE:DEST parent and a missing mount point), and
five end-to-end runs in tests/nested_maps.rs that check the host filesystem.
Red without the fix (bwrap.rs and landlock.rs reverted, tests kept), on the
desktop: ro_children_stay_read_only_inside_rw_parent fails ("write parent:
blocked" -- the parent was dropped) and rw_map_under_ro_map_is_still_refused
fails on the old warning text; the three attack tests (missing, deep-rename,
symlinked child) pass on upstream, which refuses the parent, and guard this
change against failing open. Green with it: 5/5. On the whole series
(kekkai-3.7.1-r1, desktop): clippy --all-targets -D warnings and rustfmt
--check clean; cargo test 2000 passed, 27 failed, against 1993 passed and the
same 27 failed for the series without this patch and the secret-https test,
both trees in the same location -- three host-dependent roots
(browser_soft_profile_uses_ai_jail_state_dir sees this machine's legacy
~/.local/share/ai-jail; forge_auth's git helper meets the host's credential
helper; a signals race) and the env-lock poisoning they cascade into.

Written against ai-jail (it applies before kekkai-rename.patch), so it can go
upstream on its own.

diff --git a/CLAUDE.md b/CLAUDE.md
index c65e032..468447c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -200,7 +200,7 @@ The bwrap command mounts are order-dependent. The sequence in `sandbox/bwrap.rs`
 16. SSH agent socket and `~/.ssh` exemption mounts
 17. Pictures mount
 18. Browser profile state mount
-19. Extra user mounts (`--map`, `--rw-map`), then the mise command-wrapper lock (a jail-owned empty file bound writable over `<mise data dir>/command-wrappers/bin.lock`, only when a read-only map holds that path; it is not a user map, so the rule that no RW map may sit under a RO one does not apply: it exposes no host data)
+19. Extra user mounts (`--map`, `--rw-map`; sorted parent-first by destination depth, so a read-only map that is a direct child of a read-write map lands on top of it; deeper, missing or symlinked children make the read-write parent refused), then the mise command-wrapper lock (a jail-owned empty file bound writable over `<mise data dir>/command-wrappers/bin.lock`, only when a read-only map holds that path; it is not a user map, so the rule that no RW map may sit under a RO one does not apply: it exposes no host data)
 20. Overlay maps (`--overlay-map` — copy-on-write `--overlay-src`/`--overlay`)
 21. Project directory (pwd, rw or ro depending on mode)
 22. In-project agent-state mounts, then in-project user mounts (after the project bind; masks and deny overlays still follow both)
diff --git a/README.md b/README.md
index 485af83..627c0d6 100644
--- a/README.md
+++ b/README.md
@@ -921,6 +921,51 @@ _directory_ — a directory's mount covers files replaced within it — or
 restart the sandbox after saving. macOS matches by path, not inode, and is
 not affected.
 
+### Read-only holes in a writable map
+
+A `--map` that is a **direct child** of a `--rw-map` stays read-only on
+Linux: maps are mounted parent-first, so the read-only child sits on top of
+the writable parent. The kernel locks that mount in the sandbox's
+namespaces, so it can be neither unmounted nor remounted from inside (this
+holds even with `--no-seccomp --no-landlock`), and as a mount point it can
+be neither renamed nor deleted.
+
+```bash
+ai-jail --rw-map ~/.agent-state --map ~/.agent-state/hooks \
+  --map ~/.agent-state/settings.json my-agent
+```
+
+The writable parent is refused with a warning, as before, whenever a
+read-only map inside it could not hold:
+
+- the child is deeper than one level (an ordinary directory above it could
+  be renamed away, taking the protected subtree with it);
+- the child, or its mount point under the writable map, does not exist at
+  launch (it would never be mounted, or bwrap would create the mount point
+  on the host);
+- the child is a symlink on the host (bwrap would follow it);
+- the `--rw-map` is at or under a `--map` destination (a read-only map is a
+  policy boundary).
+
+A project `.ai-jail` cannot use this: its `rw_maps` that overlap a trusted
+read-only map are still dropped, in either direction, so an untrusted project
+config can never open a writable parent around a read-only map.
+
+The protection is per destination, not per file: another writable route to
+the same host file bypasses it — a hardlink that already existed, the same
+source mapped writable elsewhere, or the project directory. And any
+read-only map that sits two or more levels inside a writable area — the
+project directory or another `--rw-map` — can be moved away whole by
+renaming a directory above it, after which the agent recreates the path
+writable. That holds for every `--map`, nested or not; only a map one level
+below a writable root (whose root is itself a mount point) is anchored. It also covers
+only the paths you name. For Claude Code in particular, a later unjailed
+session also runs what `~/.claude.json` (`mcpServers`) and
+`~/.claude/plugins` define, so holes in `~/.claude` are not a complete
+boundary: `--claude-dir` with a separate directory is. For the `claude`
+command itself, `--agent-state` plus `--map` already gives read-only holes
+without this rule.
+
 ## Ephemeral home and temp
 
 The private home is a fresh tmpfs per launch. Nothing persists between runs
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index 1a180c6..2674835 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -230,6 +230,16 @@ separate `--macos-host-ipc` flag grants broad host IPC.
 
 ## Platform notes and residual risks
 
+A `--map` nested as a direct child of a `--rw-map` is kept read-only by its
+bind mount alone: Landlock grants are additive, so the parent's write rule
+also covers the child. The mount itself is locked in the sandbox's
+namespaces and cannot be undone from inside. Deeper, missing or symlinked
+children refuse the writable parent instead (see the README). More generally,
+any `--map` two or more levels inside a writable area (the project directory
+or a `--rw-map`) can be moved away by renaming an ordinary directory above it,
+and its path recreated writable; the bind mount protects the files, not the
+path they are reached by.
+
 Linux combines bubblewrap namespaces with Landlock, seccomp, and resource
 limits where available. Seccomp denies raw and packet sockets, with one
 narrow exception: `socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)`, which
diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs
index 7dc0ba3..2657ce8 100644
--- a/src/sandbox/bwrap.rs
+++ b/src/sandbox/bwrap.rs
@@ -4419,36 +4419,87 @@ fn mise_wrappers_lock_mount(extra: &[Mount], create: bool) -> Option<Mount> {
 }
 
 fn extra_mounts(rw_maps: &[PathBuf], ro_maps: &[PathBuf]) -> Vec<Mount> {
-    extra_mounts_with_check(rw_maps, ro_maps, super::path_exists)
+    extra_mounts_with_checks(rw_maps, ro_maps, super::path_exists, |path| {
+        path.symlink_metadata()
+            .is_ok_and(|m| m.file_type().is_symlink())
+    })
 }
 
 /// Inner implementation of [`extra_mounts`] that accepts an injectable
 /// path-existence predicate. This makes the logic unit-testable in hermetic
 /// environments (e.g. the Nix build sandbox) where host paths like `/usr`
 /// may not exist.
+#[cfg(test)]
 fn extra_mounts_with_check(
     rw_maps: &[PathBuf],
     ro_maps: &[PathBuf],
     path_exists: impl Fn(&Path) -> bool,
+) -> Vec<Mount> {
+    extra_mounts_with_checks(rw_maps, ro_maps, path_exists, |path| {
+        path.symlink_metadata()
+            .is_ok_and(|m| m.file_type().is_symlink())
+    })
+}
+
+/// Why a read-only map strictly inside a read-write map cannot be kept on
+/// top of it, or `None` when it can. Only a *direct* child holds: its only
+/// ancestors inside the writable parent are the parent's mount root and
+/// the child itself, both mount points, which the sandbox can neither
+/// rename nor unmount. A deeper child sits under an ordinary directory
+/// the agent can rename, taking the protected subtree with it (measured:
+/// `mv S/a S/a2; mkdir -p S/a/b` made `S/a/b` writable again). A child
+/// that does not exist is never mounted at all, and a symlinked one is
+/// followed by bwrap to wherever it points.
+fn nested_ro_refusal(
+    parent: &MapSpec,
+    child: &MapSpec,
+    child_mounted: bool,
+    path_exists: &impl Fn(&Path) -> bool,
+    is_symlink: &impl Fn(&Path) -> bool,
+) -> Option<&'static str> {
+    let rel = child.destination.strip_prefix(&parent.destination).ok()?;
+    if rel.components().count() != 1 {
+        return Some("it is not a direct child");
+    }
+    if !child_mounted {
+        return Some("its source does not exist");
+    }
+    // bwrap would create a missing mount point on the host, inside the
+    // writable parent, as a side effect of the launch.
+    if !path_exists(&parent.source.join(rel)) {
+        return Some("its mount point does not exist under the writable map");
+    }
+    if is_symlink(&parent.source.join(rel)) {
+        return Some("it is a symlink");
+    }
+    None
+}
+
+/// [`extra_mounts`] with injectable path-existence and symlink predicates.
+fn extra_mounts_with_checks(
+    rw_maps: &[PathBuf],
+    ro_maps: &[PathBuf],
+    path_exists: impl Fn(&Path) -> bool,
+    is_symlink: impl Fn(&Path) -> bool,
 ) -> Vec<Mount> {
     let mut mounts = Vec::new();
 
-    let trusted_ro_destinations: Vec<PathBuf> = ro_maps
+    // Every requested read-only map, and whether it will be mounted: a
+    // request whose source is missing is still a policy boundary.
+    let requested_ro: Vec<(MapSpec, bool)> = ro_maps
         .iter()
         .filter_map(|encoded| MapSpec::parse_validated(encoded, "read-only"))
-        .map(|spec| spec.destination)
+        .map(|spec| {
+            let mounted = path_exists(&spec.source);
+            (spec, mounted)
+        })
         .collect();
 
-    // Read-only destinations are policy boundaries: no RW map may shadow
-    // them or a subtree beneath them.
-    for encoded in ro_maps {
-        let Some(spec) = MapSpec::parse_validated(encoded, "read-only") else {
-            continue;
-        };
-        if path_exists(&spec.source) {
+    for (spec, mounted) in &requested_ro {
+        if *mounted {
             mounts.push(Mount::RoBind {
-                src: spec.source,
-                dest: spec.destination,
+                src: spec.source.clone(),
+                dest: spec.destination.clone(),
             });
         } else {
             output::warn(&format!(
@@ -4458,24 +4509,48 @@ fn extra_mounts_with_check(
         }
     }
 
-    for encoded in rw_maps {
+    'rw: for encoded in rw_maps {
         let Some(spec) = MapSpec::parse_validated(encoded, "read-write") else {
             continue;
         };
-        // Overlap must be rejected in BOTH directions: an RW child
-        // under an RO destination would be shadowed read-only (the
-        // original check), and an RW parent over an RO destination
-        // would silently re-expose the read-only subtree as writable
-        // because the later RW bind wins in bwrap's mount order.
-        if trusted_ro_destinations.iter().any(|ro| {
-            spec.destination.starts_with(ro)
-                || ro.starts_with(&spec.destination)
-        }) {
+        // An RW map at or under an RO destination is rejected: the RO
+        // map is a policy boundary, and nothing beneath it may become
+        // writable.
+        if requested_ro
+            .iter()
+            .any(|(ro, _)| spec.destination.starts_with(&ro.destination))
+        {
             output::security_warn(
-                "ignoring rw-map that overlaps a read-only map destination",
+                "ignoring rw-map at or under a read-only map destination",
             );
             continue;
         }
+        // An RW map strictly ABOVE an RO destination is kept only when the
+        // RO map can hold on top of it (see nested_ro_refusal): mounts are
+        // ordered parent-first below, so the RO child is bound after the
+        // RW parent. Otherwise the parent is refused, as before nesting
+        // was supported -- a silently writable subtree is the one outcome
+        // this must never produce.
+        for (ro, mounted) in &requested_ro {
+            if !ro.destination.starts_with(&spec.destination) {
+                continue;
+            }
+            if let Some(why) = nested_ro_refusal(
+                &spec,
+                ro,
+                *mounted,
+                &path_exists,
+                &is_symlink,
+            ) {
+                output::security_warn(&format!(
+                    "ignoring rw-map {}: the read-only map {} inside it \
+                     cannot be kept read-only ({why})",
+                    spec.destination.display(),
+                    ro.destination.display()
+                ));
+                continue 'rw;
+            }
+        }
         if path_exists(&spec.source) {
             mounts.push(Mount::Bind {
                 src: spec.source,
@@ -6563,8 +6638,8 @@ mod tests {
     fn extra_mounts_rw_child_overrides_ro_parent() {
         // Inject |_| true so the test is hermetic: it doesn't require
         // /usr or /usr/bin to exist on the host (they won't in the Nix
-        // build sandbox). The ordering guarantee — ro first, rw after —
-        // is the invariant under test, not path existence.
+        // build sandbox). The invariant under test: an RW map under an
+        // RO destination is dropped, and the RO parent survives.
         let ro = vec![PathBuf::from("/usr")];
         let rw = vec![PathBuf::from("/usr/bin")];
         let mounts = extra_mounts_with_check(&rw, &ro, |_| true);
@@ -6579,33 +6654,98 @@ mod tests {
     }
 
     #[test]
-    fn extra_mounts_rw_parent_shadowing_ro_child_is_rejected() {
-        // The reverse overlap: an RW map of a PARENT directory would
-        // be mounted after the RO child (rw maps are emitted last),
-        // and bwrap's later mount wins — silently re-exposing the
-        // read-only subtree as writable. Must be rejected in both
-        // directions.
-        let ro = vec![PathBuf::from("/data/keys")];
+    fn extra_mounts_rw_parent_keeps_ro_child_on_top() {
+        // An RW map of a PARENT directory with an RO direct child. bwrap's
+        // later mount wins, so the RW parent must be emitted FIRST and the
+        // RO child after it -- the child then stays read-only inside a
+        // writable parent. Emitting the parent last would silently
+        // re-expose the read-only subtree as writable.
+        let ro = vec![PathBuf::from("/data/keys"), PathBuf::from("/data/cfg")];
         let rw = vec![PathBuf::from("/data")];
-        let mounts = extra_mounts_with_check(&rw, &ro, |_| true);
+        let mounts = extra_mounts_with_checks(&rw, &ro, |_| true, |_| false);
+        let dests: Vec<_> = mounts.iter().map(Mount::dest).collect();
         assert_eq!(
-            mounts.len(),
-            1,
-            "rw parent must be dropped, keeping only the ro child"
+            dests,
+            vec![
+                Path::new("/data"),
+                Path::new("/data/keys"),
+                Path::new("/data/cfg")
+            ]
         );
-        assert!(matches!(
-            &mounts[0],
-            Mount::RoBind { src, dest }
-                if src == Path::new("/data/keys")
-                    && dest == Path::new("/data/keys")
-        ));
+        assert!(matches!(&mounts[0], Mount::Bind { .. }));
+        assert!(matches!(&mounts[1], Mount::RoBind { .. }));
 
-        // Component boundaries matter: /data-keys is NOT under /data.
+        // An RW map of the SAME path as an RO map is still rejected: the
+        // RO map is the boundary.
+        let ro = vec![PathBuf::from("/data/keys")];
+        let rw = vec![PathBuf::from("/data/keys")];
+        let mounts = extra_mounts_with_checks(&rw, &ro, |_| true, |_| false);
+        assert_eq!(mounts.len(), 1);
+        assert!(matches!(&mounts[0], Mount::RoBind { .. }));
+
+        // Component boundaries matter: /data-keys is NOT under /data/keys.
         let rw = vec![PathBuf::from("/data-keys")];
-        let mounts = extra_mounts_with_check(&rw, &ro, |_| true);
+        let mounts = extra_mounts_with_checks(&rw, &ro, |_| true, |_| false);
         assert_eq!(mounts.len(), 2);
     }
 
+    #[test]
+    fn extra_mounts_refuse_rw_parent_when_ro_child_cannot_hold() {
+        let rw = vec![PathBuf::from("/data")];
+        let only_rw = |mounts: &[Mount]| {
+            !mounts
+                .iter()
+                .any(|m| matches!(m, Mount::Bind { dest, .. } if dest == Path::new("/data")))
+        };
+        // Deeper than a direct child: an intermediate directory could be
+        // renamed away with the protected subtree inside it.
+        let ro = vec![PathBuf::from("/data/a/deep")];
+        let mounts = extra_mounts_with_checks(&rw, &ro, |_| true, |_| false);
+        assert!(only_rw(&mounts), "deep child must refuse the RW parent");
+        // A child that does not exist is never mounted: fail closed.
+        let ro = vec![PathBuf::from("/data/hooks")];
+        let mounts = extra_mounts_with_checks(
+            &rw,
+            &ro,
+            |p| p != Path::new("/data/hooks"),
+            |_| false,
+        );
+        assert!(only_rw(&mounts), "missing child must refuse the RW parent");
+        // A symlinked child would be followed by bwrap.
+        let mounts = extra_mounts_with_checks(
+            &rw,
+            &ro,
+            |_| true,
+            |p| p == Path::new("/data/hooks"),
+        );
+        assert!(
+            only_rw(&mounts),
+            "symlinked child must refuse the RW parent"
+        );
+        // The symlink is checked where it lives on the host: under the RW
+        // parent's SOURCE, not its destination.
+        let rw = vec![PathBuf::from("/host/state:/data")];
+        let mounts = extra_mounts_with_checks(
+            &rw,
+            &ro,
+            |_| true,
+            |p| p == Path::new("/host/state/hooks"),
+        );
+        assert!(only_rw(&mounts), "symlink under the source must refuse");
+        // A SOURCE:DEST child whose own source exists but whose mount point
+        // is missing under the writable map: bwrap would create it on the
+        // host, so the parent is refused instead.
+        let rw = vec![PathBuf::from("/data")];
+        let ro = vec![PathBuf::from("/elsewhere/cfg:/data/cfg")];
+        let mounts = extra_mounts_with_checks(
+            &rw,
+            &ro,
+            |p| p != Path::new("/data/cfg"),
+            |_| false,
+        );
+        assert!(only_rw(&mounts), "missing mount point must refuse");
+    }
+
     #[test]
     fn extra_mounts_use_alternate_source_and_destination() {
         let ro = vec![PathBuf::from("/host/ro:/jail/ro")];
diff --git a/src/sandbox/landlock.rs b/src/sandbox/landlock.rs
index 7fe1b48..9fb1458 100644
--- a/src/sandbox/landlock.rs
+++ b/src/sandbox/landlock.rs
@@ -524,7 +524,10 @@ fn collect_lockdown_paths(
 /// mount namespace hides paths not explicitly bind-mounted. The
 /// two layers are complementary — Landlock prevents writes to
 /// ro-bind-mounted paths, bwrap prevents access to unmounted
-/// paths.
+/// paths. One exception: a read-only map nested directly inside a
+/// read-write map inherits the parent's write grant (Landlock rules
+/// only add access), so there the read-only bind mount alone keeps it
+/// read-only.
 fn collect_normal_paths_with_mounted_paths(
     config: &Config,
     project_dir: &Path,
diff --git a/tests/nested_maps.rs b/tests/nested_maps.rs
new file mode 100644
index 0000000..ef5c2e1
--- /dev/null
+++ b/tests/nested_maps.rs
@@ -0,0 +1,248 @@
+// End-to-end tests for nested maps: a read-only map strictly inside a
+// read-write map stays read-only, and the rest of the parent stays
+// writable. The typical use is agent state -- `--rw-map ~/.claude` with
+// `--map ~/.claude/hooks` and `--map ~/.claude/settings.json`, so the
+// jailed agent keeps its history but cannot plant a hook that a later,
+// unjailed session would run.
+//
+// Linux-only (requires bwrap, and a fresh /proc: a container that cannot
+// mount one skips); tests skip gracefully when unavailable.
+#![cfg(target_os = "linux")]
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+mod common;
+use common::{SANDBOX_RUN_LOCK, ai_jail};
+
+/// A fresh state dir shaped like agent state, plus a project dir and a
+/// private HOME/XDG_CONFIG_HOME, so a run never reads or writes the real
+/// user's configuration.
+fn fixture(name: &str) -> (PathBuf, PathBuf) {
+    let root = std::env::temp_dir()
+        .join(format!("ai-jail-nested.{}.{name}", std::process::id()));
+    let _ = std::fs::remove_dir_all(&root);
+    let state = root.join("state");
+    std::fs::create_dir_all(state.join("hooks")).unwrap();
+    std::fs::create_dir_all(state.join("projects")).unwrap();
+    std::fs::write(state.join("settings.json"), "orig\n").unwrap();
+    std::fs::write(state.join("hooks/h.sh"), "echo hook\n").unwrap();
+    std::fs::create_dir_all(root.join("project")).unwrap();
+    std::fs::create_dir_all(root.join("home")).unwrap();
+    std::fs::create_dir_all(root.join("xdg")).unwrap();
+    (root, state)
+}
+
+/// An ai-jail command isolated to the fixture rooted at `root`.
+fn jail(root: &Path) -> Command {
+    let mut command = Command::new(ai_jail());
+    command
+        .args(["--clean", "--no-status-bar", "--exec", "--no-save-config"])
+        .current_dir(root.join("project"))
+        .env("HOME", root.join("home"))
+        .env("XDG_CONFIG_HOME", root.join("xdg"));
+    command
+}
+
+/// Run `bash -c <script>` with `--rw-map <state>` plus RO children,
+/// returning one `label: ALLOWED|blocked` line per probe.
+fn probe(
+    state: &Path,
+    ro_children: &[&str],
+    probes: &[(&str, &str)],
+) -> String {
+    let _lock = SANDBOX_RUN_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+    let mut script = String::new();
+    for (label, cmd) in probes {
+        script.push_str(&format!(
+            "if ( {cmd} ) 2>/dev/null; then echo '{label}: ALLOWED'; \
+             else echo '{label}: blocked'; fi\n"
+        ));
+    }
+    let mut command = jail(state.parent().unwrap());
+    command.arg("--rw-map").arg(state);
+    for child in ro_children {
+        command.arg("--map").arg(state.join(child));
+    }
+    let output = command
+        .env("S", state)
+        .args(["--env", "S", "bash", "-c", &script])
+        .output()
+        .expect("failed to spawn ai-jail");
+    assert!(
+        output.status.success(),
+        "sandbox run failed: {}",
+        String::from_utf8_lossy(&output.stderr)
+    );
+    String::from_utf8_lossy(&output.stdout).into_owned()
+}
+
+#[test]
+fn ro_children_stay_read_only_inside_rw_parent() {
+    require_bwrap!();
+    let (root, state) = fixture("children");
+    let out = probe(
+        &state,
+        &["hooks", "settings.json"],
+        &[
+            ("write parent", "echo x > \"$S/projects/x\""),
+            ("edit hook", "echo evil >> \"$S/hooks/h.sh\""),
+            ("new hook", "echo evil > \"$S/hooks/evil.sh\""),
+            ("edit settings", "echo evil >> \"$S/settings.json\""),
+            (
+                "replace settings",
+                "echo evil > \"$S/t.json\" && mv -f \"$S/t.json\" \"$S/settings.json\"",
+            ),
+            ("move hooks away", "mv \"$S/hooks\" \"$S/hooks.old\""),
+            ("delete settings", "rm -f \"$S/settings.json\""),
+        ],
+    );
+    let host_settings =
+        std::fs::read_to_string(state.join("settings.json")).unwrap();
+    let host_hook = std::fs::read_to_string(state.join("hooks/h.sh")).unwrap();
+    let wrote_parent = state.join("projects/x").exists();
+    let _ = std::fs::remove_dir_all(&root);
+
+    assert!(out.contains("write parent: ALLOWED"), "{out}");
+    for label in [
+        "edit hook",
+        "new hook",
+        "edit settings",
+        "replace settings",
+        "move hooks away",
+        "delete settings",
+    ] {
+        assert!(out.contains(&format!("{label}: blocked")), "{out}");
+    }
+    assert_eq!(host_settings, "orig\n");
+    assert_eq!(host_hook, "echo hook\n");
+    assert!(wrote_parent);
+}
+
+#[test]
+fn rw_map_under_ro_map_is_still_refused() {
+    // The other direction keeps upstream's policy: an RO map is a
+    // boundary, and nothing beneath it may become writable.
+    require_bwrap!();
+    let (root, state) = fixture("boundary");
+    let _lock = SANDBOX_RUN_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+    let output = jail(&root)
+        .arg("--map")
+        .arg(&state)
+        .arg("--rw-map")
+        .arg(state.join("projects"))
+        .args(["bash", "-c"])
+        .arg(format!(
+            "echo x > '{}' 2>/dev/null && echo ALLOWED || echo blocked",
+            state.join("projects/x").display()
+        ))
+        .output()
+        .expect("failed to spawn ai-jail");
+    let _ = std::fs::remove_dir_all(&root);
+    let stdout = String::from_utf8_lossy(&output.stdout);
+    let stderr = String::from_utf8_lossy(&output.stderr);
+    assert_eq!(stdout.trim(), "blocked");
+    assert!(stderr.contains("at or under a read-only map"), "{stderr}");
+}
+
+/// Files under `root` modified after `since` -- the host-side truth, since
+/// a refused map leaves the agent writing into the sandbox's own tmpfs.
+fn changed_on_host(root: &Path, since: std::time::SystemTime) -> Vec<PathBuf> {
+    let mut out = Vec::new();
+    let mut stack = vec![root.to_path_buf()];
+    while let Some(dir) = stack.pop() {
+        for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
+            let path = entry.path();
+            let Ok(meta) = path.symlink_metadata() else {
+                continue;
+            };
+            if meta.is_dir() {
+                stack.push(path.clone());
+            }
+            if meta.modified().is_ok_and(|m| m > since) {
+                out.push(path);
+            }
+        }
+    }
+    out
+}
+
+fn attack(
+    name: &str,
+    setup: impl Fn(&Path),
+    maps: &[(&str, &str)],
+    script: &str,
+) -> (Vec<PathBuf>, String) {
+    let (root, state) = fixture(name);
+    std::fs::remove_dir_all(state.join("hooks")).unwrap();
+    setup(&state);
+    let since = std::time::SystemTime::now();
+    std::thread::sleep(std::time::Duration::from_millis(1100));
+    let _lock = SANDBOX_RUN_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+    let mut command = jail(&root);
+    for (flag, rel) in maps {
+        command.arg(flag).arg(if rel.is_empty() {
+            state.clone()
+        } else {
+            state.join(rel)
+        });
+    }
+    let output = command
+        .env("S", &state)
+        .args(["--env", "S", "sh", "-c", script])
+        .output()
+        .expect("failed to spawn ai-jail");
+    let changed = changed_on_host(&state, since);
+    let _ = std::fs::remove_dir_all(&root);
+    (
+        changed,
+        String::from_utf8_lossy(&output.stdout).into_owned(),
+    )
+}
+
+#[test]
+fn missing_ro_child_refuses_the_rw_parent() {
+    require_bwrap!();
+    // hooks/ does not exist at launch: it must not become writable.
+    let (changed, _) = attack(
+        "missing",
+        |_| {},
+        &[("--rw-map", ""), ("--map", "hooks")],
+        "mkdir \"$S/hooks\"; echo evil > \"$S/hooks/p\"; echo x > \"$S/x\"",
+    );
+    assert!(changed.is_empty(), "host changed: {changed:?}");
+}
+
+#[test]
+fn renaming_an_intermediate_dir_cannot_expose_a_deep_ro_child() {
+    require_bwrap!();
+    let (changed, _) = attack(
+        "deep",
+        |s| {
+            std::fs::create_dir_all(s.join("a/b")).unwrap();
+            std::fs::write(s.join("a/b/h.sh"), "orig\n").unwrap();
+        },
+        &[("--rw-map", ""), ("--map", "a/b")],
+        "mv \"$S/a\" \"$S/a2\"; mkdir -p \"$S/a/b\"; echo evil > \"$S/a/b/h.sh\"",
+    );
+    assert!(changed.is_empty(), "host changed: {changed:?}");
+}
+
+#[test]
+fn symlinked_ro_child_refuses_the_rw_parent() {
+    require_bwrap!();
+    let (changed, stdout) = attack(
+        "symlink",
+        |s| {
+            std::fs::create_dir_all(s.join("real")).unwrap();
+            std::os::unix::fs::symlink(s.join("real"), s.join("hooks"))
+                .unwrap();
+        },
+        &[("--rw-map", ""), ("--map", "hooks")],
+        "echo evil > \"$S/real/p\"; echo x > \"$S/x\"; echo RAN",
+    );
+    // The launch must go ahead with the parent refused -- not abort in
+    // bwrap on the symlinked mount point, which also writes nothing.
+    assert!(stdout.contains("RAN"), "agent did not run: {stdout:?}");
+    assert!(changed.is_empty(), "host changed: {changed:?}");
+}
