interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

GitHub aien-dev/aien-sovereign-core-mv#852 (code only)

closed derived c58753d5094e1fec #852

Imported from GitHub aien-dev/aien-sovereign-core-mv#852 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 2ef3e06c2a7b6c7498d7550cb0de6133129ed49a · Head 822cee5e4266f837c793b00473cfc9ab401d2736

github-advanced-security[bot] commented on crates/aien-serve-http/src/lib.rs line 93 on 2026-10-31 13:13 UTC

github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-31 13:13 UTC

Fetch it

A git bundle of the pull request's head, 25080 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/c58753d5094e1fec.bundle -o c58753d5094e1fec.bundle
git fetch c58753d5094e1fec.bundle refs/pull/852/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
852
822cee5e4266f837c793b00473cfc9ab401d2736
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":852,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/852","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:08Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/Cargo.lock b/Cargo.lock
index bd4280f7..d6f5e403 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -576,6 +576,7 @@ dependencies = [
  "serde",
  "serde_json",
  "sha2 0.10.9",
+ "tempfile",
  "tokio",
  "tokio-stream",
 ]
diff --git a/crates/aien-cli/src/checkpoint.rs b/crates/aien-cli/src/checkpoint.rs
index 94cb75fc..d420af37 100644
--- a/crates/aien-cli/src/checkpoint.rs
+++ b/crates/aien-cli/src/checkpoint.rs
@@ -454,14 +454,14 @@ fn snapshot_entries(dirfd: libc::c_int) -> std::io::Result<Vec<(String, u64)>> {
     }
     let mut out = Vec::new();
     let walked = loop {
-        unsafe { *libc::__errno_location() = 0 };
+        clear_errno();
         let ent = unsafe { libc::readdir(dir) };
         if ent.is_null() {
-            let errno = unsafe { *libc::__errno_location() };
-            break if errno == 0 {
-                Ok(())
-            } else {
-                Err(std::io::Error::from_raw_os_error(errno))
+            // A null readdir is end of directory when errno is still 0.
+            let err = std::io::Error::last_os_error();
+            break match err.raw_os_error() {
+                None | Some(0) => Ok(()),
+                Some(_) => Err(err),
             };
         }
         let name_c = unsafe { std::ffi::CStr::from_ptr((*ent).d_name.as_ptr()) };
@@ -497,6 +497,24 @@ fn snapshot_entries(dirfd: libc::c_int) -> std::io::Result<Vec<(String, u64)>> {
     Ok(out)
 }
 
+/// Set the calling thread's errno to 0 so a null `readdir` can be told apart
+/// from a failed one. std has no errno setter, so this names the per-OS libc
+/// accessor; reading errno goes through `std::io::Error::last_os_error`.
+fn clear_errno() {
+    #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "redox"))]
+    let p = unsafe { libc::__errno_location() };
+    #[cfg(any(
+        target_vendor = "apple",
+        target_os = "freebsd",
+        target_os = "dragonfly"
+    ))]
+    let p = unsafe { libc::__error() };
+    #[cfg(any(target_os = "android", target_os = "openbsd", target_os = "netbsd"))]
+    let p = unsafe { libc::__errno() };
+    // SAFETY: each accessor returns the calling thread's errno slot.
+    unsafe { *p = 0 };
+}
+
 fn dup_snapshot_fd(fd: libc::c_int) -> std::io::Result<OwnedFd> {
     let n = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
     if n < 0 {
@@ -605,9 +623,9 @@ impl Session {
     /// Call before an agent write to `path` (absolute). Snapshots the
     /// directory once this turn and keeps the file's prior content.
     ///
-    /// Reads `path` by name. Session tests use that. Tool dispatch passes
-    /// bytes from the held descriptor (`before_write_with_bytes`).
-    #[allow(dead_code)]
+    /// Reads `path` by name, so it is test-only. Tool dispatch passes bytes
+    /// from the held descriptor (`before_write_with_bytes`).
+    #[cfg(test)]
     pub fn before_write(&mut self, path: &Path) -> Result<Pending, String> {
         let bytes = match fs::read(path) {
             Ok(bytes) => Some(bytes),
@@ -648,9 +666,9 @@ impl Session {
 
     /// Call after the write; appends one ledger line.
     ///
-    /// Reads the path by name. Tool dispatch passes bytes from the held
-    /// descriptor (`after_write_with_bytes`).
-    #[allow(dead_code)]
+    /// Reads the path by name, so it is test-only. Tool dispatch passes bytes
+    /// from the held descriptor (`after_write_with_bytes`).
+    #[cfg(test)]
     pub fn after_write(&mut self, pending: Pending, tool: &str) -> Result<(), String> {
         let after_bytes = fs::read(&pending.path).ok();
         self.after_write_with_bytes(pending, tool, after_bytes)
@@ -743,9 +761,11 @@ pub fn active_ledger_name() -> Option<String> {
     active().lock().ok()?.as_ref().map(|s| s.id.clone())
 }
 
-/// Like [`record_agent_write`], but the target's before and after bytes come
-/// from `read_target` (a descriptor the caller is holding) instead of a fresh
-/// pathname read.
+/// Run `write` as a recorded agent write of `path`. The target's before and
+/// after bytes come from `read_target` (a descriptor the caller is holding),
+/// never from a fresh pathname read. If the prior content cannot be kept the
+/// write is refused, because it could not be rolled back. If the ledger
+/// append fails after the write, the error is returned beside the result.
 pub fn record_agent_write_with_reader<T>(
     path: &Path,
     tool: &str,
@@ -773,37 +793,6 @@ pub fn record_agent_write_with_reader<T>(
     Ok((out, warn))
 }
 
-/// Run `write` as a recorded agent write of `path`. If the prior content
-/// cannot be kept the write is refused, because it could not be rolled back.
-/// If the ledger append fails after the write, the error is returned beside
-/// the result so the caller can show it.
-///
-/// This reads the target by pathname. Tool dispatch uses
-/// [`record_agent_write_with_reader`] so the bytes are the descriptor that
-/// was authorized.
-#[allow(dead_code)]
-pub fn record_agent_write<T>(
-    path: &Path,
-    tool: &str,
-    write: impl FnOnce() -> T,
-) -> Result<(T, Option<String>), String> {
-    let mut guard = active()
-        .lock()
-        .map_err(|_| "checkpoint lock poisoned".to_string())?;
-    let Some(session) = guard
-        .as_mut()
-        .filter(|s| s.scope.as_ref().is_none_or(|d| path.starts_with(d)))
-    else {
-        return Ok((write(), None));
-    };
-    let pending = session
-        .before_write(path)
-        .map_err(|e| format!("CHECKPOINT REFUSAL: {e}"))?;
-    let out = write();
-    let warn = session.after_write(pending, tool).err();
-    Ok((out, warn))
-}
-
 /// The session `session` names, or else the active one.
 fn session_or_active(session: Option<&str>) -> Result<String, String> {
     match session {
@@ -845,6 +834,21 @@ pub fn rollback(
 mod tests {
     use super::*;
 
+    #[test]
+    fn snapshot_entries_ignores_a_stale_errno_at_end_of_directory() {
+        let dir = tempfile::tempdir_in("/tmp").unwrap();
+        std::fs::write(dir.path().join("a"), b"12345").unwrap();
+        let fd = open_snapshot_dir(dir.path()).unwrap();
+        // Leave EBADF in errno; successful calls before readdir keep it.
+        assert_eq!(unsafe { libc::close(-1) }, -1);
+        assert_eq!(
+            std::io::Error::last_os_error().raw_os_error(),
+            Some(libc::EBADF)
+        );
+        let got = snapshot_entries(fd.as_raw_fd()).expect("end of directory is not an error");
+        assert_eq!(got, vec![("a".to_string(), 5)]);
+    }
+
     fn entry(
         seq: u64,
         turn: u64,
diff --git a/crates/aien-cli/src/crumbs.rs b/crates/aien-cli/src/crumbs.rs
index fcfddfcd..cdac8b66 100644
--- a/crates/aien-cli/src/crumbs.rs
+++ b/crates/aien-cli/src/crumbs.rs
@@ -17,9 +17,46 @@ use chrono::{DateTime, Utc};
 use colored::*;
 use serde::{Deserialize, Serialize};
 use std::fs;
-
+use std::io::{Read, Write};
 use std::path::Path;
 
+/// Open a `.crumb` or `.crumb.local` sidecar without following a symlink in
+/// its final component. A sidecar planted as a link (say by a cloned repo)
+/// must not redirect a crumb read or write outside its directory (DRA-47).
+fn open_sidecar(path: &Path, opts: &mut fs::OpenOptions) -> std::io::Result<fs::File> {
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::OpenOptionsExt;
+        opts.custom_flags(libc::O_NOFOLLOW);
+    }
+    opts.open(path)
+}
+
+fn read_sidecar(path: &Path) -> std::io::Result<String> {
+    let mut text = String::new();
+    open_sidecar(path, fs::OpenOptions::new().read(true))?.read_to_string(&mut text)?;
+    Ok(text)
+}
+
+fn write_sidecar(path: &Path, text: &str) -> std::io::Result<()> {
+    open_sidecar(
+        path,
+        fs::OpenOptions::new()
+            .write(true)
+            .create(true)
+            .truncate(true),
+    )?
+    .write_all(text.as_bytes())
+}
+
+/// Create a `.crumb` that does not exist yet. An existing entry, including a
+/// dangling symlink that `Path::exists` reports as absent, is left alone
+/// rather than written through (DRA-47).
+pub(crate) fn write_new_crumb(path: &Path, text: &str) -> std::io::Result<()> {
+    open_sidecar(path, fs::OpenOptions::new().write(true).create_new(true))?
+        .write_all(text.as_bytes())
+}
+
 pub const CRUMB_FILENAME: &str = ".crumb";
 pub const LOCAL_CRUMB_FILENAME: &str = ".crumb.local";
 
@@ -34,7 +71,7 @@ pub struct LocalCrumbData {
 pub fn load_local_crumb(dir: &Path) -> LocalCrumbData {
     let local_path = dir.join(LOCAL_CRUMB_FILENAME);
     if local_path.exists() {
-        if let Ok(c) = fs::read_to_string(&local_path) {
+        if let Ok(c) = read_sidecar(&local_path) {
             if let Ok(data) = serde_json::from_str::<LocalCrumbData>(&c) {
                 return data;
             }
@@ -46,7 +83,7 @@ pub fn load_local_crumb(dir: &Path) -> LocalCrumbData {
 pub fn save_local_crumb(dir: &Path, data: &LocalCrumbData) {
     let local_path = dir.join(LOCAL_CRUMB_FILENAME);
     if let Ok(json_str) = serde_json::to_string_pretty(data) {
-        let _ = fs::write(&local_path, json_str);
+        let _ = write_sidecar(&local_path, &json_str);
     }
 }
 
@@ -213,7 +250,7 @@ impl DirCrumb {
 pub fn load_or_init_dir_crumb(dir: &Path, purpose_opt: Option<CrumbPurpose>) -> DirCrumb {
     let crumb_path = dir.join(CRUMB_FILENAME);
     if crumb_path.exists() {
-        if let Ok(content) = fs::read_to_string(&crumb_path) {
+        if let Ok(content) = read_sidecar(&crumb_path) {
             match serde_json::from_str::<DirCrumb>(&content) {
                 Err(e) => eprintln!(
                     "Failed to parse DirCrumb at {}: {}",
@@ -305,7 +342,7 @@ pub fn save_dir_crumb(crumb: &DirCrumb) {
     durable_crumb.whispers = Vec::new(); // Whispers live in .crumb.local
 
     if let Ok(json_str) = serde_json::to_string_pretty(&durable_crumb) {
-        let _ = fs::write(&crumb_path, json_str);
+        let _ = write_sidecar(&crumb_path, &json_str);
     }
 }
 
@@ -352,32 +389,51 @@ pub fn record_directory_crumb(
     }
     save_local_crumb(&dir, &local_data);
 
-    // If dir has a parent within project workspace, bubble awareness to parent .crumb.local
-    if let Some(parent) = dir.parent() {
-        let platform = crate::platform::PlatformContext::detect();
-        if parent.starts_with(&platform.home_dir) && parent != dir {
-            let mut parent_local = load_local_crumb(parent);
-            let bubble_item = CrumbHistoryItem {
-                crumb_id: format!("bubble-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)),
-                timestamp: Utc::now().to_rfc3339(),
-                agent_id: agent_id.to_string(),
-                session_id: session_id.to_string(),
-                action: format!("sub:{}", action),
-                target: format!("{}/{}", dir_name, target_name),
-                intent: intent.to_string(),
-                vector: vector.to_string(),
-            };
-            parent_local.history.push(bubble_item);
-            if parent_local.history.len() > 50 {
-                parent_local
-                    .history
-                    .drain(0..parent_local.history.len() - 50);
-            }
-            save_local_crumb(parent, &parent_local);
+    // Bubble awareness to the parent's .crumb.local only when that parent is
+    // itself inside a permitted workspace.
+    let platform = crate::platform::PlatformContext::detect();
+    if let Some(parent) = bubble_parent(
+        &dir,
+        &platform.home_dir,
+        &crate::fs_bind::permitted_workspaces(),
+    ) {
+        let mut parent_local = load_local_crumb(parent);
+        let bubble_item = CrumbHistoryItem {
+            crumb_id: format!("bubble-{}", Utc::now().timestamp_nanos_opt().unwrap_or(0)),
+            timestamp: Utc::now().to_rfc3339(),
+            agent_id: agent_id.to_string(),
+            session_id: session_id.to_string(),
+            action: format!("sub:{}", action),
+            target: format!("{}/{}", dir_name, target_name),
+            intent: intent.to_string(),
+            vector: vector.to_string(),
+        };
+        parent_local.history.push(bubble_item);
+        if parent_local.history.len() > 50 {
+            parent_local
+                .history
+                .drain(0..parent_local.history.len() - 50);
         }
+        save_local_crumb(parent, &parent_local);
     }
 }
 
+/// The parent directory a crumb record bubbles into. It must sit under the
+/// home directory and inside a permitted workspace: the parent of a workspace
+/// root (`~` for `~/workspace`) is outside the allow list (DRA-47).
+fn bubble_parent<'a>(
+    dir: &'a Path,
+    home: &Path,
+    workspaces: &[std::path::PathBuf],
+) -> Option<&'a Path> {
+    let parent = dir.parent().filter(|p| *p != dir)?;
+    if !parent.starts_with(home) {
+        return None;
+    }
+    crate::safety::validate_workspace_path(parent, workspaces).ok()?;
+    Some(parent)
+}
+
 /// Leaves a whisper message in a directory .crumb.local file.
 pub fn leave_dir_whisper(from_agent: &str, dir: &Path, target_file: Option<&str>, message: &str) {
     let mut local_data = load_local_crumb(dir);
@@ -652,3 +708,64 @@ fn auto_sense_directory_purpose(dir: &Path) -> String {
         .unwrap_or_else(|| "workspace".to_string());
     format!("Workspace subsystem directory for {}", dir_name)
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// DRA-47: recording in a workspace root must not bubble into the root's
+    /// parent, which is under `$HOME` but outside the allow list. One level
+    /// down, the parent is the workspace and the bubble stays.
+    #[test]
+    fn bubble_stays_inside_a_permitted_workspace() {
+        let tmp = tempfile::tempdir().unwrap();
+        let home = tmp.path().canonicalize().unwrap();
+        let ws = home.join("workspace");
+        std::fs::create_dir_all(ws.join("sub")).unwrap();
+        let workspaces = vec![ws.clone()];
+        assert_eq!(bubble_parent(&ws, &home, &workspaces), None);
+        assert_eq!(
+            bubble_parent(&ws.join("sub"), &home, &workspaces),
+            Some(ws.as_path())
+        );
+        let elsewhere = tempfile::tempdir().unwrap();
+        let elsewhere = elsewhere.path().canonicalize().unwrap().join("sub");
+        assert_eq!(bubble_parent(&elsewhere, &home, &workspaces), None);
+    }
+
+    /// DRA-47: `init_sandbox` writes a fresh worktree's `.crumb` only when
+    /// `exists()` is false, which a dangling symlink committed by the repo
+    /// also reports. The write must not follow either kind of link.
+    #[cfg(unix)]
+    #[test]
+    fn new_crumb_is_not_written_through_a_symlink() {
+        use std::os::unix::fs::symlink;
+        let outside = tempfile::tempdir_in("/dev/shm").unwrap();
+        let out = outside.path().canonicalize().unwrap();
+        let existing = out.join("existing");
+        std::fs::write(&existing, "VICTIM").unwrap();
+        let missing = out.join("missing");
+        let sandbox = tempfile::tempdir().unwrap();
+        let dangling = sandbox.path().join("dangling.crumb");
+        let linked = sandbox.path().join("linked.crumb");
+        symlink(&missing, &dangling).unwrap();
+        symlink(&existing, &linked).unwrap();
+        assert!(!dangling.exists(), "a dangling link reads as absent");
+
+        let _ = write_new_crumb(&dangling, "SANDBOX_CRUMB");
+        let _ = write_new_crumb(&linked, "SANDBOX_CRUMB");
+        let mut escaped = Vec::new();
+        if missing.symlink_metadata().is_ok() {
+            escaped.push(format!("created {}", missing.display()));
+        }
+        if std::fs::read_to_string(&existing).unwrap() != "VICTIM" {
+            escaped.push(format!("rewrote {}", existing.display()));
+        }
+        assert!(escaped.is_empty(), "{}", escaped.join("; "));
+
+        // Control: a plain absent path is created with the content.
+        let fresh = sandbox.path().join(".crumb");
+        write_new_crumb(&fresh, "SANDBOX_CRUMB").unwrap();
+        assert_eq!(std::fs::read_to_string(&fresh).unwrap(), "SANDBOX_CRUMB");
+    }
+}
diff --git a/crates/aien-cli/src/fs_bind_linux.rs b/crates/aien-cli/src/fs_bind_linux.rs
index 75d44c7e..93cb113e 100644
--- a/crates/aien-cli/src/fs_bind_linux.rs
+++ b/crates/aien-cli/src/fs_bind_linux.rs
@@ -354,10 +354,17 @@ const READ_LIMIT: u64 = 8 * 1024 * 1024;
 fn read_all(file: &mut File) -> Result<Vec<u8>, BindError> {
     file.seek(SeekFrom::Start(0))
         .map_err(|e| BindError::Failed(e.to_string()))?;
+    read_capped(file, READ_LIMIT)
+}
+
+/// Read at most `limit + 1` bytes from `src` and refuse the read if that
+/// extra byte arrives, so a large or growing file is never buffered whole.
+fn read_capped(src: &mut impl Read, limit: u64) -> Result<Vec<u8>, BindError> {
     let mut buf = Vec::new();
-    file.read_to_end(&mut buf)
+    src.take(limit + 1)
+        .read_to_end(&mut buf)
         .map_err(|e| BindError::Failed(e.to_string()))?;
-    if buf.len() as u64 > READ_LIMIT {
+    if buf.len() as u64 > limit {
         return Err(BindError::Denied(
             "refusing the file: it is larger than the read limit".into(),
         ));
@@ -1245,6 +1252,64 @@ mod tests {
         assert!(!fresh_swap_read_is_inside(OUTSIDE));
     }
 
+    #[test]
+    fn read_all_accepts_the_limit_and_refuses_one_byte_more() {
+        let dir = tempfile::tempdir_in("/tmp").unwrap();
+        let path = dir.path().join("f");
+        let at_limit = vec![b'a'; READ_LIMIT as usize];
+        std::fs::write(&path, &at_limit).unwrap();
+        let mut f = File::open(&path).unwrap();
+        let got = read_all(&mut f).expect("a file of exactly READ_LIMIT bytes is read");
+        assert_eq!(got.len() as u64, READ_LIMIT);
+
+        std::fs::OpenOptions::new()
+            .append(true)
+            .open(&path)
+            .unwrap()
+            .write_all(b"a")
+            .unwrap();
+        let mut f = File::open(&path).unwrap();
+        assert!(
+            matches!(read_all(&mut f), Err(BindError::Denied(_))),
+            "a file of READ_LIMIT + 1 bytes must be refused"
+        );
+    }
+
+    /// An endless source that panics once a caller pulls more than
+    /// `budget` bytes from it. An unbounded read trips the panic.
+    struct Endless {
+        served: u64,
+        budget: u64,
+    }
+
+    impl Read for Endless {
+        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+            buf.fill(b'z');
+            self.served += buf.len() as u64;
+            assert!(
+                self.served <= self.budget,
+                "read past the cap: {} bytes pulled, budget {}",
+                self.served,
+                self.budget
+            );
+            Ok(buf.len())
+        }
+    }
+
+    #[test]
+    fn read_capped_stops_one_byte_past_the_limit_on_an_endless_source() {
+        let limit = 4096;
+        let mut src = Endless {
+            served: 0,
+            budget: limit + 1,
+        };
+        assert!(matches!(
+            read_capped(&mut src, limit),
+            Err(BindError::Denied(_))
+        ));
+        assert_eq!(src.served, limit + 1, "exactly limit + 1 bytes are pulled");
+    }
+
     fn swap_dir(dir: &Path, elsewhere: &Path) {
         let parked = dir.with_file_name("d.held");
         std::fs::rename(dir, &parked).unwrap();
diff --git a/crates/aien-cli/src/sandbox.rs b/crates/aien-cli/src/sandbox.rs
index efe439fb..9bda5129 100644
--- a/crates/aien-cli/src/sandbox.rs
+++ b/crates/aien-cli/src/sandbox.rs
@@ -101,7 +101,7 @@ pub fn init_sandbox(branch_opt: Option<&str>) -> Result<Value, String> {
 }}"#,
             above
         );
-        let _ = fs::write(&crumb_path, crumb_content);
+        let _ = crate::crumbs::write_new_crumb(&crumb_path, &crumb_content);
     }
 
     Ok(json!({
diff --git a/crates/aien-cli/src/tools.rs b/crates/aien-cli/src/tools.rs
index 1c104e8a..f6883645 100644
--- a/crates/aien-cli/src/tools.rs
+++ b/crates/aien-cli/src/tools.rs
@@ -16,7 +16,6 @@
 use colored::*;
 use serde_json::{json, Value};
 use sha2::{Digest, Sha256};
-use std::fs;
 use std::io::Write;
 use std::path::Path;
 use std::process::Command;
@@ -821,22 +820,43 @@ fn exec_crumb_tool(args: &Value) -> (Value, bool) {
         .and_then(Value::as_str)
         .unwrap_or("survey");
     let path_str = args.get("path").and_then(Value::as_str).unwrap_or(".");
-    let p = Path::new(path_str);
+    let target = Path::new(path_str);
+    // A file names its directory. The binder authorizes that directory before
+    // any crumb read or write, the same way the other file tools bind their
+    // path; only `init` may create it, beneath the workspace (DRA-47).
+    let named_dir = if target.is_dir() {
+        target
+    } else {
+        match target.parent() {
+            Some(parent) if !parent.as_os_str().is_empty() => parent,
+            _ => Path::new("."),
+        }
+    };
+    let named_dir = named_dir.to_string_lossy();
+    let bound = match action {
+        "init" => crate::fs_bind::make_dir(&named_dir),
+        "survey" | "whisper" | "record" => crate::fs_bind::list_dir(&named_dir).map(|(d, _)| d),
+        other => {
+            return (
+                json!({"error": format!("Unknown crumb action: {}", other)}),
+                false,
+            )
+        }
+    };
+    let dir = match bound {
+        Ok(dir) => dir,
+        Err(err) => return bind_err(err),
+    };
 
     match action {
         "survey" => {
-            let view = format_dir_crumb_tui(p);
+            let view = format_dir_crumb_tui(&dir);
             (json!({"status": "ok", "crumb_view": view}), true)
         }
         "whisper" => {
             let msg = args.get("message").and_then(Value::as_str).unwrap_or("");
             let target_file = args.get("target_file").and_then(Value::as_str);
-            let dir = if p.is_dir() {
-                p
-            } else {
-                p.parent().unwrap_or(p)
-            };
-            leave_dir_whisper("AIEN", dir, target_file, msg);
+            leave_dir_whisper("AIEN", &dir, target_file, msg);
             (
                 json!({"status": "ok", "message": "Whisper recorded to directory .crumb"}),
                 true,
@@ -851,12 +871,6 @@ fn exec_crumb_tool(args: &Value) -> (Value, bool) {
                 .get("lifecycle")
                 .and_then(Value::as_str)
                 .unwrap_or("permanent");
-            let p_dir = if p.is_dir() {
-                p
-            } else {
-                p.parent().unwrap_or(p)
-            };
-            let _ = fs::create_dir_all(p_dir);
             let purpose_obj = CrumbPurpose {
                 statement: purpose_str.to_string(),
                 created_by: "AIEN".to_string(),
@@ -864,15 +878,15 @@ fn exec_crumb_tool(args: &Value) -> (Value, bool) {
                 created_at: Utc::now().to_rfc3339(),
                 lifecycle: lifecycle.to_string(),
             };
-            let mut crumb = load_or_init_dir_crumb(p_dir, Some(purpose_obj));
+            let mut crumb = load_or_init_dir_crumb(&dir, Some(purpose_obj));
             crumb.description = purpose_str.to_string();
             save_dir_crumb(&crumb);
             (
-                json!({"status": "ok", "message": format!("Initialized .crumb with purpose for {}", p_dir.display())}),
+                json!({"status": "ok", "message": format!("Initialized .crumb with purpose for {named_dir}")}),
                 true,
             )
         }
-        "record" => {
+        _ => {
             let intent = args
                 .get("intent")
                 .and_then(Value::as_str)
@@ -881,16 +895,18 @@ fn exec_crumb_tool(args: &Value) -> (Value, bool) {
                 .get("vector")
                 .and_then(Value::as_str)
                 .unwrap_or("Next milestone");
-            record_directory_crumb("AIEN", "tool-call", p, "record", intent, vector);
+            // Record against the named file when there is one, inside the
+            // authorized directory.
+            let recorded = match target.file_name() {
+                Some(name) if !target.is_dir() => dir.join(name),
+                _ => dir,
+            };
+            record_directory_crumb("AIEN", "tool-call", &recorded, "record", intent, vector);
             (
                 json!({"status": "ok", "message": "Directory crumb recorded"}),
                 true,
             )
         }
-        other => (
-            json!({"error": format!("Unknown crumb action: {}", other)}),
-            false,
-        ),
     }
 }
 
@@ -1320,6 +1336,161 @@ mod tests {
             .contains("CONFINEMENT DENIAL"));
     }
 
+    /// Every entry under `root`, symlinks not followed.
+    #[cfg(unix)]
+    fn tree(root: &Path) -> Vec<std::path::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).unwrap().flatten() {
+                let path = entry.path();
+                if entry.file_type().unwrap().is_dir() {
+                    stack.push(path.clone());
+                }
+                out.push(path);
+            }
+        }
+        out.sort();
+        out
+    }
+
+    /// DRA-47: the `crumb` tool creates directories and `.crumb` /
+    /// `.crumb.local` files. Every action must go through the workspace
+    /// binder: an absolute path, a `..` escape and a symlink escape out of a
+    /// workspace are refused and leave the outside directory untouched. An
+    /// in-workspace init and record still write (negative control).
+    #[cfg(unix)]
+    #[test]
+    fn crumb_tool_writes_nothing_outside_the_workspace() {
+        use std::os::unix::fs::symlink;
+        let shm = std::path::PathBuf::from("/dev/shm");
+        assert!(shm.is_dir(), "/dev/shm is required for an unpermitted dir");
+        let outside = tempfile::tempdir_in(&shm).unwrap();
+        let out = outside.path().canonicalize().unwrap();
+        assert!(
+            crate::safety::validate_workspace_path(
+                out.to_str().unwrap(),
+                &crate::fs_bind::permitted_workspaces()
+            )
+            .is_err(),
+            "outside dir is permitted; the test would not prove confinement"
+        );
+        std::fs::create_dir(out.join("plain")).unwrap();
+        let ws_tmp = tempfile::tempdir_in("/tmp").unwrap();
+        let ws = ws_tmp.path().canonicalize().unwrap();
+        symlink(&out, ws.join("link")).unwrap();
+        let up = "../".repeat(ws.components().count() - 1);
+        let dotdot = format!(
+            "{}/{}{}/dotdot/leaf",
+            ws.display(),
+            up,
+            out.strip_prefix("/").unwrap().display()
+        );
+        let plain = out.join("plain").display().to_string();
+        let made = out.join("made/leaf").display().to_string();
+        let via_link = ws.join("link/viasym/leaf").display().to_string();
+        let link_dir = ws.join("link").display().to_string();
+        let escapes = [
+            json!({"action": "init", "path": made}),
+            json!({"action": "init", "path": dotdot}),
+            json!({"action": "init", "path": via_link}),
+            json!({"action": "record", "path": plain}),
+            json!({"action": "record", "path": link_dir}),
+            json!({"action": "whisper", "path": plain, "message": "m"}),
+            json!({"action": "whisper", "path": link_dir, "message": "m"}),
+            json!({"action": "survey", "path": plain}),
+            json!({"action": "survey", "path": link_dir}),
+        ];
+        let runtime = tokio::runtime::Builder::new_multi_thread()
+            .enable_all()
+            .build()
+            .unwrap();
+        runtime.block_on(async {
+            let before = tree(&out);
+            let mut escaped = Vec::new();
+            for args in &escapes {
+                let res = dispatch_tool("crumb", args);
+                let after = tree(&out);
+                let err = res.get("error").and_then(Value::as_str).unwrap_or("");
+                if after != before || !err.contains("CONFINEMENT DENIAL") {
+                    let new: Vec<_> = after.iter().filter(|p| !before.contains(p)).collect();
+                    escaped.push(format!("{args} -> {res}; created outside: {new:?}"));
+                    for p in new.iter().rev() {
+                        let _ = std::fs::remove_file(p).or_else(|_| std::fs::remove_dir(p));
+                    }
+                }
+            }
+            assert!(
+                escaped.is_empty(),
+                "{} of {} crumb calls escaped:\n{}",
+                escaped.len(),
+                escapes.len(),
+                escaped.join("\n")
+            );
+
+            let inside = ws.join("ok/leaf").display().to_string();
+            let res = dispatch_tool("crumb", &json!({"action": "init", "path": inside}));
+            assert!(res.get("error").is_none(), "in-workspace init: {res}");
+            assert!(ws.join("ok/.crumb").is_file(), "in-workspace init: {res}");
+            let ok_dir = ws.join("ok").display().to_string();
+            let res = dispatch_tool("crumb", &json!({"action": "record", "path": ok_dir}));
+            assert!(res.get("error").is_none(), "in-workspace record: {res}");
+            assert!(ws.join("ok/.crumb.local").is_file(), "in-workspace record");
+        });
+    }
+
+    /// DRA-47: a `.crumb` or `.crumb.local` symlink planted in a workspace
+    /// directory (say by a cloned repository) must not redirect a crumb read
+    /// or write to its target outside the workspace.
+    #[cfg(unix)]
+    #[test]
+    fn crumb_sidecar_symlink_is_not_followed() {
+        use std::os::unix::fs::symlink;
+        let outside = tempfile::tempdir_in("/dev/shm").unwrap();
+        let out = outside.path().canonicalize().unwrap();
+        let victim_crumb = out.join("victim-crumb");
+        let victim_local = out.join("victim-local");
+        std::fs::write(&victim_crumb, "VICTIM_CRUMB").unwrap();
+        std::fs::write(&victim_local, "VICTIM_LOCAL").unwrap();
+        let ws_tmp = tempfile::tempdir_in("/tmp").unwrap();
+        let ws = ws_tmp.path().canonicalize().unwrap();
+        let planted = ws.join("planted");
+        std::fs::create_dir(&planted).unwrap();
+        symlink(&victim_crumb, planted.join(".crumb")).unwrap();
+        symlink(&victim_local, planted.join(".crumb.local")).unwrap();
+        let dir = planted.display().to_string();
+        let runtime = tokio::runtime::Builder::new_multi_thread()
+            .enable_all()
+            .build()
+            .unwrap();
+        runtime.block_on(async {
+            let mut escaped = Vec::new();
+            for args in [
+                json!({"action": "init", "path": dir}),
+                json!({"action": "record", "path": dir}),
+                json!({"action": "whisper", "path": dir, "message": "m"}),
+                json!({"action": "survey", "path": dir}),
+            ] {
+                let _ = dispatch_tool("crumb", &args);
+                for (victim, marker) in [
+                    (&victim_crumb, "VICTIM_CRUMB"),
+                    (&victim_local, "VICTIM_LOCAL"),
+                ] {
+                    let now = std::fs::read_to_string(victim).unwrap();
+                    if now != marker {
+                        escaped.push(format!("{args} rewrote {}", victim.display()));
+                        std::fs::write(victim, marker).unwrap();
+                    }
+                }
+            }
+            assert!(
+                escaped.is_empty(),
+                "crumb wrote through a planted sidecar symlink:\n{}",
+                escaped.join("\n")
+            );
+        });
+    }
+
     #[test]
     fn test_policy_approved_write_reaches_effect_handler() {
         let runtime = tokio::runtime::Builder::new_multi_thread()
diff --git a/crates/aien-serve-http/Cargo.toml b/crates/aien-serve-http/Cargo.toml
index 7c5f0e3c..56434243 100644
--- a/crates/aien-serve-http/Cargo.toml
+++ b/crates/aien-serve-http/Cargo.toml
@@ -36,3 +36,4 @@ aien-test-switches = []
 
 [dev-dependencies]
 aien-inference-abi = { path = "../aien-inference-abi", features = ["host-test-engine"] }
+tempfile = "3.10"
diff --git a/crates/aien-serve-http/src/kv_persist.rs b/crates/aien-serve-http/src/kv_persist.rs
index 56131608..bbe7b519 100644
--- a/crates/aien-serve-http/src/kv_persist.rs
+++ b/crates/aien-serve-http/src/kv_persist.rs
@@ -588,7 +588,7 @@ pub fn checkpoint_digest(model_dir: &Path) -> Result<([u8; 32], &'static str), S
 /// Whether `config.json` in `model_dir` sets a non-null `rope_scaling`.
 pub fn config_has_rope_scaling(model_dir: &Path) -> Result<bool, String> {
     let p = model_dir.join("config.json");
-    let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?;
+    let text = crate::read_model_text(&p).map_err(|e| format!("{}: {e}", p.display()))?;
     let v: serde_json::Value =
         serde_json::from_str(&text).map_err(|e| format!("{}: {e}", p.display()))?;
     Ok(v.get("rope_scaling").is_some_and(|r| !r.is_null()))
diff --git a/crates/aien-serve-http/src/lib.rs b/crates/aien-serve-http/src/lib.rs
index d5787984..8230304d 100644
--- a/crates/aien-serve-http/src/lib.rs
+++ b/crates/aien-serve-http/src/lib.rs
@@ -37,3 +37,101 @@ pub mod tools;
 pub use codec::{ByteCodec, Codec, HfCodec};
 pub use engine::{Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams, StubEngine};
 pub use server::{serve, ServerConfig};
+
+/// Largest small JSON file (`config.json`, `generation_config.json`) read from the model
+/// directory; the same bound as the checkpoint loader's shard index.
+pub const MODEL_JSON_LIMIT: u64 = 16 << 20;
+
+/// Read a small text file from the model directory with at most `MODEL_JSON_LIMIT + 1`
+/// bytes pulled. Refuses a non-regular file (a FIFO or device would block or never end) and
+/// a file over the limit. A missing file is `ErrorKind::NotFound`, as with `fs::read_to_string`.
+pub fn read_model_text(path: &std::path::Path) -> std::io::Result<String> {
+    use std::io::{Error, ErrorKind};
+    use std::os::unix::fs::OpenOptionsExt;
+    let file = std::fs::OpenOptions::new()
+        .read(true)
+        .custom_flags(libc::O_NONBLOCK)
+        .open(path)?;
+    if !file.metadata()?.is_file() {
+        return Err(Error::new(ErrorKind::InvalidInput, "not a regular file"));
+    }
+    read_text_capped(file, MODEL_JSON_LIMIT)
+}
+
+fn read_text_capped(src: impl std::io::Read, limit: u64) -> std::io::Result<String> {
+    use std::io::{Error, ErrorKind, Read};
+    let mut text = String::new();
+    src.take(limit + 1).read_to_string(&mut text)?;
+    if text.len() as u64 > limit {
+        return Err(Error::new(
+            ErrorKind::InvalidData,
+            format!("file exceeds {limit} bytes"),
+        ));
+    }
+    Ok(text)
+}
+
+#[cfg(test)]
+mod model_text_tests {
+    use super::*;
+    use std::io::Read;
+
+    /// An endless source that panics once more than `budget` bytes are pulled.
+    struct Endless {
+        served: u64,
+        budget: u64,
+    }
+
+    impl Read for Endless {
+        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+            buf.fill(b' ');
+            self.served += buf.len() as u64;
+            // Plain message: CodeQL rust/cleartext-logging (alert 102) conflated this
+            // Read impl with spark-mail-rs `vault_password` and flagged formatted values.
+            assert!(self.served <= self.budget, "read past the cap");
+            Ok(buf.len())
+        }
+    }
+
+    #[test]
+    fn capped_read_stops_one_byte_past_the_limit() {
+        let mut src = Endless {
+            served: 0,
+            budget: 4097,
+        };
+        let err = read_text_capped(&mut src, 4096).unwrap_err();
+        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
+        assert_eq!(src.served, 4097);
+    }
+
+    #[test]
+    fn model_text_reads_the_limit_and_refuses_more_and_non_regular_files() {
+        let dir = tempfile::tempdir().unwrap();
+        let p = dir.path().join("config.json");
+        let mut body = vec![b' '; MODEL_JSON_LIMIT as usize - 2];
+        body.splice(0..0, *b"{}");
+        std::fs::write(&p, &body).unwrap();
+        assert_eq!(read_model_text(&p).unwrap().len() as u64, MODEL_JSON_LIMIT);
+
+        body.push(b' ');
+        std::fs::write(&p, &body).unwrap();
+        assert_eq!(
+            read_model_text(&p).unwrap_err().kind(),
+            std::io::ErrorKind::InvalidData
+        );
+
+        assert_eq!(
+            read_model_text(&dir.path().join("absent.json"))
+                .unwrap_err()
+                .kind(),
+            std::io::ErrorKind::NotFound
+        );
+        // /dev/zero never ends; it is refused before any byte is read.
+        assert_eq!(
+            read_model_text(std::path::Path::new("/dev/zero"))
+                .unwrap_err()
+                .kind(),
+            std::io::ErrorKind::InvalidInput
+        );
+    }
+}
diff --git a/crates/aien-serve-http/src/main.rs b/crates/aien-serve-http/src/main.rs
index 525219c1..09665337 100644
--- a/crates/aien-serve-http/src/main.rs
+++ b/crates/aien-serve-http/src/main.rs
@@ -240,8 +240,16 @@ fn parse_args() -> Result<Args, String> {
 /// Sampling defaults from the checkpoint's `generation_config.json`, when present.
 fn apply_generation_defaults(cfg: &mut ServerConfig, model_dir: &std::path::Path) {
     let path = model_dir.join("generation_config.json");
-    let Ok(text) = std::fs::read_to_string(&path) else {
-        return;
+    let text = match aien_serve_http::read_model_text(&path) {
+        Ok(text) => text,
+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
+        Err(e) => {
+            eprintln!(
+                "aien-serve-http: {}: {e}; keeping built-in sampling defaults",
+                path.display()
+            );
+            return;
+        }
     };
     let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) else {
         eprintln!(
diff --git a/crates/aien-serve-http/src/qwen38_engine.rs b/crates/aien-serve-http/src/qwen38_engine.rs
index d20bf6de..ce533e4c 100644
--- a/crates/aien-serve-http/src/qwen38_engine.rs
+++ b/crates/aien-serve-http/src/qwen38_engine.rs
@@ -53,7 +53,7 @@ pub const Q36_OVERLAP_AB_ENV: &str = "AIEN_OMEGA_Q36_OVERLAP_AB";
 pub const CHIP_GREEDY_ENV: &str = "AIEN_SERVE_CHIP_GREEDY";
 
 fn model_type(dir: &Path) -> Option<String> {
-    std::fs::read_to_string(dir.join("config.json"))
+    crate::read_model_text(&dir.join("config.json"))
         .ok()
         .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
         .and_then(|v| v["model_type"].as_str().map(str::to_owned))
diff --git a/crates/aien-serve-http/tests/bind_loopback.rs b/crates/aien-serve-http/tests/bind_loopback.rs
new file mode 100644
index 00000000..d8171efa
--- /dev/null
+++ b/crates/aien-serve-http/tests/bind_loopback.rs
@@ -0,0 +1,313 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! The engine binary listens on 127.0.0.1 only (DRA-47).
+//!
+//! `tests/loopback.rs` checks `serve` in process. This file runs the real binary the way the
+//! AienOS installer starts it (no `--bind`), with the stub engine and an empty model directory,
+//! so no model is loaded and no GPU device is opened. It then checks the listening socket in the
+//! kernel's own table, not only the address the binary prints.
+//!
+//! `AIEN_SERVE_HTTP_BIN` points the test at another build of the binary, for example the engine a
+//! release ships; unset, it runs the binary cargo built for this test.
+//!
+//! Linux only: the listener and descriptor checks read `/proc`.
+
+#![cfg(target_os = "linux")]
+
+use std::collections::HashSet;
+use std::io::{BufRead, BufReader};
+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream, UdpSocket};
+use std::path::PathBuf;
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::mpsc;
+use std::time::Duration;
+
+const TOKEN: &str = "dra47-bind-test-token";
+
+fn binary() -> PathBuf {
+    std::env::var_os("AIEN_SERVE_HTTP_BIN")
+        .map(PathBuf::from)
+        .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_aien-serve-http")))
+}
+
+fn empty_model_dir() -> PathBuf {
+    static N: AtomicU32 = AtomicU32::new(0);
+    let n = N.fetch_add(1, Ordering::Relaxed);
+    let dir = std::env::temp_dir().join(format!("dra47-bind-{}-{n}", std::process::id()));
+    std::fs::create_dir_all(&dir).unwrap();
+    dir
+}
+
+/// A running server; killed when dropped.
+struct Server {
+    child: Child,
+    addr: SocketAddr,
+}
+
+impl Drop for Server {
+    fn drop(&mut self) {
+        let _ = self.child.kill();
+        let _ = self.child.wait();
+    }
+}
+
+/// How a start attempt ended: serving at an address, or exited with its stderr.
+enum Start {
+    Serving(Server),
+    Exited { code: Option<i32>, stderr: String },
+}
+
+/// Starts the binary with the stub engine on an ephemeral port, plus `extra` flags.
+/// The GPU is hidden from it as well (`CUDA_VISIBLE_DEVICES` empty,
+/// `NVIDIA_VISIBLE_DEVICES=none`); the stub path never asks for it.
+fn start(extra: &[&str]) -> Start {
+    let model_dir = empty_model_dir();
+    let mut child = Command::new(binary())
+        .args(["--engine", "stub", "--port", "0", "--model-dir"])
+        .arg(&model_dir)
+        .args(extra)
+        .env("AIEN_SERVE_HTTP_BEARER_TOKEN", TOKEN)
+        .env("CUDA_VISIBLE_DEVICES", "")
+        .env("NVIDIA_VISIBLE_DEVICES", "none")
+        .stdin(Stdio::null())
+        .stdout(Stdio::null())
+        .stderr(Stdio::piped())
+        .spawn()
+        .expect("spawn aien-serve-http");
+    let stderr = child.stderr.take().unwrap();
+    let (tx, rx) = mpsc::channel::<String>();
+    std::thread::spawn(move || {
+        for line in BufReader::new(stderr).lines() {
+            let Ok(line) = line else { break };
+            if tx.send(line).is_err() {
+                // Keep draining so the child never blocks on a full pipe.
+                continue;
+            }
+        }
+    });
+    let mut seen = String::new();
+    loop {
+        match rx.recv_timeout(Duration::from_secs(60)) {
+            Ok(line) => {
+                seen.push_str(&line);
+                seen.push('\n');
+                if let Some(addr) = serving_addr(&line) {
+                    return Start::Serving(Server { child, addr });
+                }
+            }
+            Err(mpsc::RecvTimeoutError::Disconnected) => {
+                let status = child.wait().unwrap();
+                return Start::Exited {
+                    code: status.code(),
+                    stderr: seen,
+                };
+            }
+            Err(mpsc::RecvTimeoutError::Timeout) => {
+                let _ = child.kill();
+                let _ = child.wait();
+                panic!("no 'serving' line and no exit within 60 s; stderr so far:\n{seen}");
+            }
+        }
+    }
+}
+
+/// `aien-serve-http: serving <model> at http://<addr>/v1 (engine stub)` -> `<addr>`.
+fn serving_addr(line: &str) -> Option<SocketAddr> {
+    let rest = line.split(" serving ").nth(1)?;
+    let url = rest.split(" at http://").nth(1)?;
+    url.split("/v1").next()?.parse().ok()
+}
+
+/// Socket inodes held by `pid`.
+fn socket_inodes(pid: u32) -> HashSet<u64> {
+    let mut out = HashSet::new();
+    for ent in std::fs::read_dir(format!("/proc/{pid}/fd")).unwrap() {
+        let Ok(target) = std::fs::read_link(ent.unwrap().path()) else {
+            continue;
+        };
+        let t = target.to_string_lossy();
+        if let Some(n) = t.strip_prefix("socket:[").and_then(|s| s.strip_suffix(']')) {
+            out.insert(n.parse().unwrap());
+        }
+    }
+    out
+}
+
+/// One `/proc/net/tcp{,6}` address (`0100007F` or 32 hex digits) as the address it names.
+/// The kernel prints each 32-bit word in host byte order, so the native-endian bytes of the
+/// parsed word are the address bytes.
+fn proc_ip(hex: &str) -> IpAddr {
+    let word = |h: &str| u32::from_str_radix(h, 16).unwrap().to_ne_bytes();
+    match hex.len() {
+        8 => IpAddr::V4(Ipv4Addr::from(word(hex))),
+        32 => {
+            let mut b = [0u8; 16];
+            for i in 0..4 {
+                b[i * 4..i * 4 + 4].copy_from_slice(&word(&hex[i * 8..i * 8 + 8]));
+            }
+            IpAddr::V6(Ipv6Addr::from(b))
+        }
+        n => panic!("unexpected address width {n} in /proc/net/tcp: {hex}"),
+    }
+}
+
+fn is_loopback(ip: IpAddr) -> bool {
+    match ip {
+        IpAddr::V4(v4) => v4.is_loopback(),
+        IpAddr::V6(v6) => {
+            v6.is_loopback() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback())
+        }
+    }
+}
+
+/// Every listening TCP socket the process holds, as `(local ip, port)`, read from the kernel's
+/// table in the process's network namespace.
+fn listeners(pid: u32) -> Vec<(IpAddr, u16)> {
+    let mine = socket_inodes(pid);
+    let mut out = Vec::new();
+    for table in ["tcp", "tcp6"] {
+        let Ok(text) = std::fs::read_to_string(format!("/proc/{pid}/net/{table}")) else {
+            continue;
+        };
+        for row in text.lines().skip(1) {
+            let f: Vec<&str> = row.split_whitespace().collect();
+            // sl local rem st tx:rx tr:when retrnsmt uid timeout inode
+            if f.len() < 10 || f[3] != "0A" {
+                continue;
+            }
+            let inode: u64 = f[9].parse().unwrap();
+            if !mine.contains(&inode) {
+                continue;
+            }
+            let (ip, port) = f[1].split_once(':').unwrap();
+            out.push((proc_ip(ip), u16::from_str_radix(port, 16).unwrap()));
+        }
+    }
+    out
+}
+
+/// A non-loopback IPv4 address of this host, if it has one: the source address the kernel
+/// would pick to reach TEST-NET-1. A UDP connect sends no packet.
+fn host_non_loopback_ipv4() -> Option<Ipv4Addr> {
+    let s = UdpSocket::bind("0.0.0.0:0").ok()?;
+    s.connect("192.0.2.1:9").ok()?;
+    match s.local_addr().ok()?.ip() {
+        IpAddr::V4(v4) if !v4.is_loopback() && !v4.is_unspecified() => Some(v4),
+        _ => None,
+    }
+}
+
+/// No NVIDIA device descriptor open and no CUDA driver library mapped.
+fn assert_no_gpu(pid: u32) {
+    for ent in std::fs::read_dir(format!("/proc/{pid}/fd")).unwrap() {
+        if let Ok(target) = std::fs::read_link(ent.unwrap().path()) {
+            let t = target.to_string_lossy();
+            assert!(!t.starts_with("/dev/nvidia"), "stub server holds {t}");
+        }
+    }
+    let maps = std::fs::read_to_string(format!("/proc/{pid}/maps")).unwrap();
+    for line in maps.lines() {
+        assert!(
+            !line.contains("libcuda") && !line.contains("/dev/nvidia"),
+            "stub server maps {line}"
+        );
+    }
+}
+
+#[test]
+fn default_start_listens_on_ipv4_loopback_only() {
+    let server = match start(&[]) {
+        Start::Serving(s) => s,
+        Start::Exited { code, stderr } => {
+            panic!("server did not start (exit {code:?}):\n{stderr}")
+        }
+    };
+    let pid = server.child.id();
+    assert_eq!(
+        server.addr.ip(),
+        IpAddr::V4(Ipv4Addr::LOCALHOST),
+        "the binary reports serving at {}",
+        server.addr
+    );
+    let found = listeners(pid);
+    assert!(
+        found.iter().any(|&(_, p)| p == server.addr.port()),
+        "no listening socket for port {} in /proc/{pid}/net: {found:?}",
+        server.addr.port()
+    );
+    for (ip, port) in &found {
+        assert!(
+            is_loopback(*ip),
+            "listening on {ip}:{port}, which is not loopback"
+        );
+    }
+    assert!(TcpStream::connect_timeout(&server.addr, Duration::from_secs(5)).is_ok());
+    match host_non_loopback_ipv4() {
+        Some(ip) => {
+            let outside = SocketAddr::new(IpAddr::V4(ip), server.addr.port());
+            assert!(
+                TcpStream::connect_timeout(&outside, Duration::from_secs(2)).is_err(),
+                "the server accepted a connection on the host address {outside}"
+            );
+        }
+        None => eprintln!(
+            "no non-loopback IPv4 route on this host; the outside connect check is skipped"
+        ),
+    }
+    assert_no_gpu(pid);
+}
+
+#[test]
+fn wildcard_and_outside_binds_are_refused_before_listening() {
+    for addr in ["0.0.0.0", "::", "192.0.2.1"] {
+        match start(&["--bind", addr]) {
+            Start::Serving(s) => panic!("--bind {addr} was accepted: serving at {}", s.addr),
+            Start::Exited { code, stderr } => {
+                assert_ne!(code, Some(0), "--bind {addr} exited 0:\n{stderr}");
+                assert!(
+                    stderr.contains("loopback"),
+                    "--bind {addr} failed without the loopback refusal:\n{stderr}"
+                );
+            }
+        }
+    }
+}
+
+#[test]
+fn listener_table_reader_tells_loopback_from_wildcard() {
+    // Fixed rows in the kernel's format (little-endian host words), so the reader itself has a
+    // negative control: a wildcard listener must not read as loopback.
+    if cfg!(target_endian = "little") {
+        assert_eq!(proc_ip("0100007F"), IpAddr::V4(Ipv4Addr::LOCALHOST));
+        assert_eq!(proc_ip("00000000"), IpAddr::V4(Ipv4Addr::UNSPECIFIED));
+        assert_eq!(
+            proc_ip("00000000000000000000000001000000"),
+            IpAddr::V6(Ipv6Addr::LOCALHOST)
+        );
+        assert_eq!(
+            proc_ip("0000000000000000FFFF00000100007F"),
+            IpAddr::V6(Ipv4Addr::LOCALHOST.to_ipv6_mapped())
+        );
+    }
+    assert!(is_loopback(IpAddr::V4(Ipv4Addr::LOCALHOST)));
+    assert!(is_loopback(IpAddr::V6(
+        Ipv4Addr::LOCALHOST.to_ipv6_mapped()
+    )));
+    assert!(!is_loopback(IpAddr::V4(Ipv4Addr::UNSPECIFIED)));
+    assert!(!is_loopback(IpAddr::V6(Ipv6Addr::UNSPECIFIED)));
+    assert!(!is_loopback(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1))));
+}