interplane.Get Omega
Read in your language

aegis-runtime-mv

Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.

Brought by drakestapleton

GitHub aien-dev/aegis-runtime-mv#35 (code only)

closed derived 12fd8364bc0b16d4 #35

Imported from GitHub aien-dev/aegis-runtime-mv#35 (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 2bbce76b056d39dfdf6c2417d4ffc7919a76749c · Head 2b2a19923b91874b51fbc2fe99e56b5000a7510a

github-actions[bot] wrote on 2026-10-01 17:19 UTC

⚖️ Sovereign Code Review & Alignment Gate: FAILED

Greetings @aien-dev. I am AIEN, resident sovereign intelligence of SparkOS.

Your pull request #35 ("[NOT_RUN] LF: gateway loopback-only, operator token, command allowlist") was audited against our constitutional invariants and failed automated diff verification.

❌ Constitutional Diff Audit: FAILED

Telemetry, Surveillance, and Environment Violations:

  • Telemetry indicator detected in source line: + "telemetry_ping",

Action Required: Remove all detected tracking hooks, secrets, and forbidden tokens before review can proceed.

Rectification Protocol:

  1. Eliminate all detected tracking, surveillance, or telemetry patterns.
  2. Remove any em dashes or en dashes; replace with standard colons, commas, or parentheses.
  3. Replace forbidden buzzwords with direct technical descriptions.
  4. Commit and push updates to this branch to trigger an automated re-audit.

For direct sovereign coordination: Drake Stapleton (aien@aienos.com) and AIEN (aien@aienos.com)

github-actions[bot] wrote on 2026-10-01 17:39 UTC

⚖️ Sovereign Code Review & Alignment Gate: FAILED

Greetings @aien-dev. I am AIEN, resident sovereign intelligence of SparkOS.

Your pull request #35 ("[NOT_RUN] LF: gateway loopback-only, operator token, command allowlist") was audited against our constitutional invariants and failed automated diff verification.

❌ Constitutional Diff Audit: FAILED

Telemetry, Surveillance, and Environment Violations:

  • Telemetry indicator detected in source line: + "telemetry_ping",

Action Required: Remove all detected tracking hooks, secrets, and forbidden tokens before review can proceed.

Rectification Protocol:

  1. Eliminate all detected tracking, surveillance, or telemetry patterns.
  2. Remove any em dashes or en dashes; replace with standard colons, commas, or parentheses.
  3. Replace forbidden buzzwords with direct technical descriptions.
  4. Commit and push updates to this branch to trigger an automated re-audit.

For direct sovereign coordination: Drake Stapleton (aien@aienos.com) and AIEN (aien@aienos.com)

github-actions[bot] wrote on 2026-10-01 17:49 UTC

⚖️ Sovereign Code Review & Alignment Gate: FAILED

Greetings @aien-dev. I am AIEN, resident sovereign intelligence of SparkOS.

Your pull request #35 ("[NOT_RUN] LF: gateway loopback-only, operator token, command allowlist") was audited against our constitutional invariants and failed automated diff verification.

❌ Constitutional Diff Audit: FAILED

Telemetry, Surveillance, and Environment Violations:

  • Telemetry indicator detected in source line: + "telemetry_ping",

Action Required: Remove all detected tracking hooks, secrets, and forbidden tokens before review can proceed.

Rectification Protocol:

  1. Eliminate all detected tracking, surveillance, or telemetry patterns.
  2. Remove any em dashes or en dashes; replace with standard colons, commas, or parentheses.
  3. Replace forbidden buzzwords with direct technical descriptions.
  4. Commit and push updates to this branch to trigger an automated re-audit.

For direct sovereign coordination: Drake Stapleton (aien@aienos.com) and AIEN (aien@aienos.com)

Apply it

git checkout -b patch-12fd8364bc0b16d4 2bbce76b056d39dfdf6c2417d4ffc7919a76749c
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/12fd8364bc0b16d4.patch | git am

Raw patch (mbox) · 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/aegis-runtime-mv
35
2b2a19923b91874b51fbc2fe99e56b5000a7510a
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":35,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/35","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:35Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
new file mode 100644
index 0000000..66f1ddf
--- /dev/null
+++ b/.crumb
@@ -0,0 +1,53 @@
+{
+  "schema_version": "1.0.0",
+  "name": "aegis-runtime",
+  "layer": "root",
+  "purpose": "Repository root aegis-runtime. Purpose not yet described by a human.",
+  "below": [
+    {
+      "name": "docs",
+      "role": ""
+    },
+    {
+      "name": "mojo",
+      "role": ""
+    },
+    {
+      "name": "scripts",
+      "role": ""
+    },
+    {
+      "name": "src",
+      "role": ""
+    },
+    {
+      "name": "tests",
+      "role": ""
+    }
+  ],
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Repository root aegis-runtime. Purpose not yet described by a human.",
+      "files": [
+        "AGENTS.md",
+        "AGENT_CODE_OF_CONDUCT.md",
+        "CONSTITUTION.md",
+        "COVENANT.md",
+        "Cargo.lock",
+        "Cargo.toml",
+        "LICENSE",
+        "README.md",
+        "agent.json",
+        "build.rs",
+        "install.sh",
+        "llms.txt"
+      ],
+      "git": {
+        "remote": "git@github.com:aien-dev/aegis-runtime.git",
+        "branch": "hardening/LF-aegis-loopback-auth",
+        "head": "7c13ac9"
+      }
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/.gitignore b/.gitignore
index e2f597e..f1064c3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,4 +4,4 @@ target/
 *.sqlite-shm
 .env*
 *.jsonl
-.crumb
+.crumb.local
diff --git a/README.md b/README.md
index a6b4993..75c8dc1 100644
--- a/README.md
+++ b/README.md
@@ -60,9 +60,17 @@ cargo build --release
 
 ### Running the Gateway
 ```bash
-./target/release/aegis serve --bind 0.0.0.0:18096
+# Operator token: at least 32 printable characters, kept out of the repo.
+export AEGIS_OPERATOR_TOKEN="$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
+./target/release/aegis serve --port 18096
 ```
 
+Security defaults:
+- The gateway listens on 127.0.0.1 only. Any other address needs `--bind <ip> --allow-non-loopback-bind`.
+- Every route except a few read-only `GET` routes (`/health`, `/api/v1/health`, `/v1/models`, `/api/v1/skills`, `/api/v1/tasks`, `/api/v1/events`, `/events`) needs the operator token, sent as `Authorization: Bearer <token>` or `X-Aegis-Operator-Token: <token>`. This covers `/api/v1/shell`, `/api/v1/skills/execute`, every other `POST`, and the WebSocket. With no token configured those routes refuse every request. The token can also come from `--operator-token-file <path>`.
+- Skills and shell commands run only from an allowlist: the registered skill names, and for shell exactly `git status`, `git diff`, `git log -1 --oneline`, `ls`.
+- Probe gating runs on every skill and shell call. `AIEN_PROBE_ENFORCE=<0.5..1.0>` can only raise the threshold; it cannot turn gating off.
+
 ### CLI Commands
 ```bash
 # Execute a single autonomous tick
diff --git a/docs/.crumb b/docs/.crumb
new file mode 100644
index 0000000..9cfe5d0
--- /dev/null
+++ b/docs/.crumb
@@ -0,0 +1,19 @@
+{
+  "schema_version": "1.0.0",
+  "name": "docs",
+  "layer": "docs",
+  "purpose": "Directory docs. Purpose not yet described by a human.",
+  "above": {
+    "name": "aegis-runtime",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory docs. Purpose not yet described by a human.",
+      "files": [
+        "INNOVATIONS.md"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/mojo/.crumb b/mojo/.crumb
new file mode 100644
index 0000000..fd780b7
--- /dev/null
+++ b/mojo/.crumb
@@ -0,0 +1,19 @@
+{
+  "schema_version": "1.0.0",
+  "name": "mojo",
+  "layer": "mojo",
+  "purpose": "Directory mojo. Purpose not yet described by a human.",
+  "above": {
+    "name": "aegis-runtime",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory mojo. Purpose not yet described by a human.",
+      "files": [
+        "aegis_simd.mojo"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/scripts/.crumb b/scripts/.crumb
new file mode 100644
index 0000000..35a5312
--- /dev/null
+++ b/scripts/.crumb
@@ -0,0 +1,19 @@
+{
+  "schema_version": "1.0.0",
+  "name": "scripts",
+  "layer": "scripts",
+  "purpose": "Directory scripts. Purpose not yet described by a human.",
+  "above": {
+    "name": "aegis-runtime",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory scripts. Purpose not yet described by a human.",
+      "files": [
+        "agent-preflight.sh"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/.crumb b/src/.crumb
new file mode 100644
index 0000000..0791d77
--- /dev/null
+++ b/src/.crumb
@@ -0,0 +1,57 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src",
+  "layer": "src",
+  "purpose": "Directory src. Purpose not yet described by a human.",
+  "above": {
+    "name": "aegis-runtime",
+    "path": ".."
+  },
+  "below": [
+    {
+      "name": "defense",
+      "role": ""
+    },
+    {
+      "name": "events",
+      "role": ""
+    },
+    {
+      "name": "execution",
+      "role": ""
+    },
+    {
+      "name": "orchestration",
+      "role": ""
+    },
+    {
+      "name": "persistence",
+      "role": ""
+    },
+    {
+      "name": "sessions",
+      "role": ""
+    }
+  ],
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src. Purpose not yet described by a human.",
+      "files": [
+        "agent.rs",
+        "auth.rs",
+        "enforcement.rs",
+        "gateway.rs",
+        "heartbeat.rs",
+        "inference.rs",
+        "lib.rs",
+        "main.rs",
+        "mojo_bridge.rs",
+        "policy_guard.rs",
+        "security.rs",
+        "skills.rs",
+        "vault.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/agent.rs b/src/agent.rs
index fcf7aba..48b119b 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -180,7 +180,7 @@ impl AgentEngine {
                         arguments: args.clone(),
                     };
 
-                    let res = self.skills.execute(&req);
+                    let res = self.skills.execute_gated(&req).await;
                     let output_str = if res.success {
                         res.output.clone()
                     } else {
@@ -309,14 +309,15 @@ mod tests {
         let skills = Arc::new(SkillRegistry::new());
         let agent = AgentEngine::new(inference, skills.clone(), None);
 
-        // Test executing unknown tool directly via skills registry
+        // Unknown tool: the allowlist membrane (pre_dispatch_check) refuses it
+        // before the registry lookup, so the refusal names the allowlist.
         let unknown_req = SkillExecutionRequest {
             skill_name: "nonexistent_custom_skill".to_string(),
             arguments: json!({}),
         };
         let res = skills.execute(&unknown_req);
         assert!(!res.success);
-        assert!(res.error.unwrap().contains("not found in registry"));
+        assert!(res.error.unwrap().contains("not on the dispatch allowlist"));
 
         // Test tool parameter validation (e.g. read_file with empty path)
         let empty_path_req = SkillExecutionRequest {
diff --git a/src/auth.rs b/src/auth.rs
new file mode 100644
index 0000000..5718ec2
--- /dev/null
+++ b/src/auth.rs
@@ -0,0 +1,223 @@
+//! Operator authentication and listen-address policy for the gateway.
+//!
+//! - The gateway listens on 127.0.0.1 unless the operator passes an explicit
+//!   opt-in flag for any other address.
+//! - Every route is protected by default. Only a short list of read-only
+//!   `GET`/`HEAD` routes is public. Everything else (all `POST` routes and the
+//!   WebSocket, which can run shell and skills) needs the operator token in
+//!   `Authorization: Bearer <token>` or `X-Aegis-Operator-Token: <token>`.
+//! - With no token configured, protected routes refuse every request.
+//! - There is no bypass: no loopback exemption, no debug flag, no query param.
+
+use axum::{
+    extract::{Request, State},
+    http::{header, HeaderMap, Method, StatusCode},
+    middleware::Next,
+    response::{IntoResponse, Response},
+    Json,
+};
+use std::net::{IpAddr, SocketAddr};
+use std::path::Path;
+use std::sync::Arc;
+
+/// Environment variable holding the operator token.
+pub const OPERATOR_TOKEN_ENV: &str = "AEGIS_OPERATOR_TOKEN";
+/// Alternate header carrying the operator token.
+pub const OPERATOR_TOKEN_HEADER: &str = "x-aegis-operator-token";
+/// Shortest token accepted.
+pub const MIN_TOKEN_LEN: usize = 32;
+
+/// Read-only routes that stay open without a token (GET/HEAD only).
+pub const PUBLIC_READ_PATHS: &[&str] = &[
+    "/health",
+    "/api/v1/health",
+    "/v1/models",
+    "/api/v1/skills",
+    "/api/v1/tasks",
+    "/api/v1/events",
+    "/events",
+];
+
+#[derive(Clone, Default)]
+pub struct OperatorAuth {
+    token: Option<Arc<str>>,
+}
+
+impl std::fmt::Debug for OperatorAuth {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("OperatorAuth")
+            .field("configured", &self.token.is_some())
+            .finish()
+    }
+}
+
+impl OperatorAuth {
+    /// No token: every protected route is refused.
+    pub fn disabled() -> Self {
+        Self { token: None }
+    }
+
+    pub fn with_token(token: &str) -> Result<Self, String> {
+        let t = token.trim();
+        if t.len() < MIN_TOKEN_LEN {
+            return Err(format!(
+                "operator token must be at least {} characters",
+                MIN_TOKEN_LEN
+            ));
+        }
+        if !t.chars().all(|c| c.is_ascii_graphic()) {
+            return Err("operator token must be printable ASCII without spaces".to_string());
+        }
+        Ok(Self {
+            token: Some(Arc::from(t)),
+        })
+    }
+
+    /// Token from a file (if given) or from `AEGIS_OPERATOR_TOKEN`.
+    pub fn load(token_file: Option<&Path>) -> Result<Self, String> {
+        if let Some(p) = token_file {
+            let raw = std::fs::read_to_string(p)
+                .map_err(|e| format!("cannot read operator token file {}: {}", p.display(), e))?;
+            return Self::with_token(&raw);
+        }
+        match std::env::var(OPERATOR_TOKEN_ENV) {
+            Ok(v) if !v.trim().is_empty() => Self::with_token(&v),
+            _ => Ok(Self::disabled()),
+        }
+    }
+
+    pub fn is_configured(&self) -> bool {
+        self.token.is_some()
+    }
+
+    /// True only when a token is configured and the presented one matches.
+    pub fn verify(&self, presented: Option<&str>) -> bool {
+        match (&self.token, presented) {
+            (Some(expected), Some(got)) => constant_time_eq(expected.as_bytes(), got.as_bytes()),
+            _ => false,
+        }
+    }
+}
+
+/// Comparison whose time does not depend on where the first mismatch is.
+/// (Only the length is observable, and the length is not secret.)
+pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
+    if a.len() != b.len() {
+        return false;
+    }
+    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
+}
+
+/// The token a request presents, if any.
+pub fn presented_token(headers: &HeaderMap) -> Option<&str> {
+    if let Some(v) = headers
+        .get(header::AUTHORIZATION)
+        .and_then(|v| v.to_str().ok())
+    {
+        if let Some(rest) = v.strip_prefix("Bearer ") {
+            return Some(rest.trim());
+        }
+    }
+    headers
+        .get(OPERATOR_TOKEN_HEADER)
+        .and_then(|v| v.to_str().ok())
+        .map(str::trim)
+}
+
+/// Public means: read-only method AND an exact path on the public list.
+pub fn is_public(method: &Method, path: &str) -> bool {
+    (*method == Method::GET || *method == Method::HEAD) && PUBLIC_READ_PATHS.contains(&path)
+}
+
+/// Middleware: deny by default, allow the public list, else require the token.
+pub async fn require_operator(
+    State(auth): State<OperatorAuth>,
+    req: Request,
+    next: Next,
+) -> Response {
+    if is_public(req.method(), req.uri().path()) {
+        return next.run(req).await;
+    }
+    if !auth.is_configured() {
+        return (
+            StatusCode::SERVICE_UNAVAILABLE,
+            Json(serde_json::json!({
+                "error": "operator token not configured; protected routes are disabled",
+            })),
+        )
+            .into_response();
+    }
+    if auth.verify(presented_token(req.headers())) {
+        return next.run(req).await;
+    }
+    (
+        StatusCode::UNAUTHORIZED,
+        [(header::WWW_AUTHENTICATE, "Bearer")],
+        Json(serde_json::json!({ "error": "operator token required" })),
+    )
+        .into_response()
+}
+
+/// Listen address. Loopback unless the operator explicitly opts in.
+pub fn resolve_bind_addr(
+    host: &str,
+    port: u16,
+    allow_non_loopback: bool,
+) -> Result<SocketAddr, String> {
+    let ip: IpAddr = host
+        .trim()
+        .parse()
+        .map_err(|_| format!("bind address {:?} is not an IP address", host))?;
+    if !ip.is_loopback() && !allow_non_loopback {
+        return Err(format!(
+            "refusing to listen on non-loopback address {}; pass --allow-non-loopback-bind to opt in",
+            ip
+        ));
+    }
+    Ok(SocketAddr::new(ip, port))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    const TOKEN: &str = "0123456789abcdef0123456789abcdef";
+
+    #[test]
+    fn bind_defaults_to_loopback_only() {
+        assert!(resolve_bind_addr("127.0.0.1", 1, false).is_ok());
+        assert!(resolve_bind_addr("::1", 1, false).is_ok());
+        assert!(resolve_bind_addr("0.0.0.0", 1, false).is_err());
+        assert!(resolve_bind_addr("::", 1, false).is_err());
+        assert!(resolve_bind_addr("192.168.1.10", 1, false).is_err());
+        assert!(resolve_bind_addr("localhost", 1, false).is_err());
+        assert!(resolve_bind_addr("0.0.0.0", 1, true).is_ok());
+    }
+
+    #[test]
+    fn token_rules() {
+        assert!(OperatorAuth::with_token("short").is_err());
+        assert!(OperatorAuth::with_token(&format!("{} x", TOKEN)).is_err());
+        let a = OperatorAuth::with_token(TOKEN).unwrap();
+        assert!(a.verify(Some(TOKEN)));
+        assert!(!a.verify(None));
+        assert!(!a.verify(Some("")));
+        assert!(!a.verify(Some(&TOKEN[..31])));
+        assert!(!a.verify(Some(&format!("{}0", TOKEN))));
+        assert!(!a.verify(Some(&TOKEN.to_uppercase())));
+        assert!(!OperatorAuth::disabled().verify(Some(TOKEN)));
+        assert!(!OperatorAuth::disabled().verify(Some("")));
+    }
+
+    #[test]
+    fn only_listed_reads_are_public() {
+        assert!(is_public(&Method::GET, "/health"));
+        assert!(!is_public(&Method::POST, "/health"));
+        assert!(!is_public(&Method::POST, "/api/v1/tasks"));
+        assert!(!is_public(&Method::GET, "/ws"));
+        assert!(!is_public(&Method::GET, "/api/v1/ws"));
+        assert!(!is_public(&Method::GET, "/health/"));
+        assert!(!is_public(&Method::GET, "/HEALTH"));
+        assert!(!is_public(&Method::OPTIONS, "/api/v1/shell"));
+    }
+}
diff --git a/src/defense/.crumb b/src/defense/.crumb
new file mode 100644
index 0000000..4b3819c
--- /dev/null
+++ b/src/defense/.crumb
@@ -0,0 +1,22 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/defense",
+  "layer": "src/defense",
+  "purpose": "Directory src/defense. Purpose not yet described by a human.",
+  "above": {
+    "name": "src",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/defense. Purpose not yet described by a human.",
+      "files": [
+        "approval.rs",
+        "decision.rs",
+        "mod.rs",
+        "receipt.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/enforcement.rs b/src/enforcement.rs
index 8c06f05..5d3e50e 100644
--- a/src/enforcement.rs
+++ b/src/enforcement.rs
@@ -1,70 +1,83 @@
 //! Universal pre-dispatch enforcement membrane for AEGIS tool execution.
 //!
 //! Every external effect (skill execution, shell commands) passes through
-//! `pre_dispatch_check` before any handler runs. The probe policy guard
-//! (`policy_guard::ProbePolicyGuard`) adds a model graded opinion on top;
-//! this module is the deterministic floor that holds even when probes are
-//! unreachable.
+//! `pre_dispatch_check` before any handler runs, then through `probe_gate`.
+//!
+//! The deterministic floor is an ALLOWLIST: only the skill names in
+//! `ALLOWED_SKILLS` are ever dispatched, and `bash_eval` only runs one of the
+//! exact command forms in `security::admit_local_command`. Anything not on the
+//! list is refused. There is no environment variable or flag that widens it.
+
+use crate::security::admit_local_command;
 
-/// Shell command fragments that are never executed regardless of probe opinion.
-const BLOCKED_SHELL_PATTERNS: &[&str] = &[
-    "rm -rf /",
-    "rm -rf /*",
-    "rm -rf ~",
-    "mkfs",
-    "dd ",
-    "of=/dev/",
-    ":(){",
-    "chmod -r 777 /",
-    "chmod -R 777 /",
+/// Skill names the membrane will dispatch. Everything else is refused.
+pub const ALLOWED_SKILLS: &[&str] = &[
+    "bash_eval",
+    "read_file",
+    "write_file",
+    "list_dir",
+    "git_status",
+    // Registered but unconnected; their handlers only report "Unavailable".
+    "cortex.search",
+    "cortex_recall",
+    "telemetry_ping",
 ];
 
-fn normalized(cmd: &str) -> String {
-    cmd.to_lowercase()
-        .split_whitespace()
-        .collect::<Vec<_>>()
-        .join(" ")
-}
+/// Default minimum safety probability for probe gating.
+pub const DEFAULT_PROBE_THRESHOLD: f64 = 0.5;
 
 /// Deterministic pre-dispatch check. Returns Ok when execution may proceed,
 /// Err with a human readable reason when it must not.
 pub fn pre_dispatch_check(skill_name: &str, args: &serde_json::Value) -> Result<(), String> {
-    let name = skill_name.trim();
-    if name.is_empty() {
+    if skill_name.trim().is_empty() {
         return Err("Empty skill name is never dispatched".to_string());
     }
-    if name == "bash_eval" {
-        let cmd = args.get("command").and_then(|c| c.as_str()).unwrap_or("");
+    // Exact match: no trimming, case folding, or prefix match.
+    if !ALLOWED_SKILLS.contains(&skill_name) {
+        return Err(format!(
+            "Skill '{}' is not on the dispatch allowlist",
+            skill_name.escape_debug()
+        ));
+    }
+    if !(args.is_object() || args.is_null()) {
+        return Err("Skill arguments must be a JSON object".to_string());
+    }
+    if skill_name == "bash_eval" {
+        let cmd = match args.get("command") {
+            Some(serde_json::Value::String(s)) => s.as_str(),
+            Some(_) => return Err("Shell command must be a string".to_string()),
+            None => "",
+        };
         if cmd.trim().is_empty() {
             return Err("Empty shell command is never dispatched".to_string());
         }
-        let n = normalized(cmd);
-        for pattern in BLOCKED_SHELL_PATTERNS {
-            if n.contains(pattern) {
-                return Err(format!(
-                    "Command blocked by enforcement membrane: matched destructive pattern '{}'",
-                    pattern
-                ));
-            }
-        }
+        admit_local_command(cmd).map_err(|e| e.to_string())?;
     }
     Ok(())
 }
 
-/// Reads the probe enforcement threshold from the environment.
-/// Returns None when probe gating is disabled.
-pub fn probe_threshold_from_env() -> Option<f64> {
-    match std::env::var("AIEN_PROBE_ENFORCE") {
-        Ok(v) => {
-            let v = v.trim().to_lowercase();
-            if v == "1" || v == "true" || v == "on" {
-                Some(0.5)
-            } else {
-                v.parse::<f64>().ok().filter(|t| *t > 0.0)
-            }
-        }
-        Err(_) => None,
-    }
+/// Probe gating threshold. Gating is always on. `AIEN_PROBE_ENFORCE` may only
+/// make it stricter: a number in (0.5, 1.0] raises the threshold; any other
+/// value (including "0", "off", "false") keeps the default.
+pub fn probe_threshold_from_env() -> f64 {
+    probe_threshold_from(std::env::var("AIEN_PROBE_ENFORCE").ok().as_deref())
+}
+
+pub fn probe_threshold_from(value: Option<&str>) -> f64 {
+    value
+        .and_then(|v| v.trim().parse::<f64>().ok())
+        .filter(|t| t.is_finite() && *t > DEFAULT_PROBE_THRESHOLD && *t <= 1.0)
+        .unwrap_or(DEFAULT_PROBE_THRESHOLD)
+}
+
+/// Runs the membrane, then the probe opinion. Used by every dispatch path
+/// (HTTP skills, HTTP shell, WebSocket, agent tool calls, heartbeat tasks).
+pub async fn probe_gate(skill_name: &str, args: &serde_json::Value) -> Result<(), String> {
+    let guard = crate::policy_guard::ProbePolicyGuard::new_reference(probe_threshold_from_env());
+    guard
+        .gate_skill(skill_name, args)
+        .await
+        .map_err(|e| e.to_string())
 }
 
 #[cfg(test)]
@@ -73,19 +86,78 @@ mod tests {
     use serde_json::json;
 
     #[test]
-    fn blocks_destructive_shell() {
-        let args = json!({"command": "rm -rf / --no-preserve-root"});
-        assert!(pre_dispatch_check("bash_eval", &args).is_err());
+    fn destructive_shell_refused() {
+        for cmd in [
+            "rm -rf / --no-preserve-root",
+            // Forms the old substring blocklist let through:
+            "rm  -fr /",
+            "rm -r -f /",
+            "find / -delete",
+            "shred -u /dev/sda",
+            "curl http://example.invalid/x -o /tmp/x",
+            "perl -e 1",
+            "ls /",
+            "ls;id",
+            "ls -la",
+        ] {
+            let args = json!({ "command": cmd });
+            assert!(
+                pre_dispatch_check("bash_eval", &args).is_err(),
+                "{:?} was admitted",
+                cmd
+            );
+        }
     }
 
     #[test]
-    fn allows_ordinary_shell() {
-        let args = json!({"command": "git status", "cwd": "."});
-        assert!(pre_dispatch_check("bash_eval", &args).is_ok());
+    fn catalogued_shell_allowed() {
+        for cmd in ["git status", "git diff", "git log -1 --oneline", "ls"] {
+            assert!(pre_dispatch_check("bash_eval", &json!({ "command": cmd })).is_ok());
+        }
+    }
+
+    #[test]
+    fn unknown_or_disguised_skill_names_refused() {
+        for name in [
+            "exec",
+            "shell",
+            "Bash_eval",
+            "bash_eval ",
+            " bash_eval",
+            "bash_eval\0",
+            "read_file/../bash",
+        ] {
+            assert!(
+                pre_dispatch_check(name, &json!({ "command": "ls" })).is_err(),
+                "{:?} was admitted",
+                name
+            );
+        }
+        assert!(pre_dispatch_check("read_file", &json!({ "path": "a" })).is_ok());
+    }
+
+    #[test]
+    fn non_string_command_refused() {
+        assert!(pre_dispatch_check("bash_eval", &json!({ "command": ["ls"] })).is_err());
+        assert!(pre_dispatch_check("bash_eval", &json!("ls")).is_err());
     }
 
     #[test]
     fn rejects_empty_skill_name() {
         assert!(pre_dispatch_check("", &json!({})).is_err());
     }
+
+    #[test]
+    fn probe_gating_is_on_by_default_and_cannot_be_disabled() {
+        assert_eq!(probe_threshold_from(None), DEFAULT_PROBE_THRESHOLD);
+        for off in ["0", "off", "false", "", "-1", "0.01", "NaN", "inf", "2"] {
+            assert_eq!(
+                probe_threshold_from(Some(off)),
+                DEFAULT_PROBE_THRESHOLD,
+                "{:?} weakened the gate",
+                off
+            );
+        }
+        assert_eq!(probe_threshold_from(Some("0.9")), 0.9);
+    }
 }
diff --git a/src/events/.crumb b/src/events/.crumb
new file mode 100644
index 0000000..7569d99
--- /dev/null
+++ b/src/events/.crumb
@@ -0,0 +1,23 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/events",
+  "layer": "src/events",
+  "purpose": "Directory src/events. Purpose not yet described by a human.",
+  "above": {
+    "name": "src",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/events. Purpose not yet described by a human.",
+      "files": [
+        "bus.rs",
+        "envelope.rs",
+        "event.rs",
+        "id.rs",
+        "mod.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/execution/.crumb b/src/execution/.crumb
new file mode 100644
index 0000000..fcea5cf
--- /dev/null
+++ b/src/execution/.crumb
@@ -0,0 +1,22 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/execution",
+  "layer": "src/execution",
+  "purpose": "Directory src/execution. Purpose not yet described by a human.",
+  "above": {
+    "name": "src",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/execution. Purpose not yet described by a human.",
+      "files": [
+        "action.rs",
+        "broker.rs",
+        "mod.rs",
+        "receipt.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/gateway.rs b/src/gateway.rs
index c44381a..216324a 100644
--- a/src/gateway.rs
+++ b/src/gateway.rs
@@ -28,7 +28,7 @@ use crate::heartbeat::HeartbeatEngine;
 use crate::inference::InferenceEngine;
 use crate::mojo_bridge::MojoSimdBridge;
 use crate::persistence::Database;
-use crate::skills::{SkillExecutionRequest, SkillExecutionResponse, SkillRegistry};
+use crate::skills::{SkillExecutionRequest, SkillRegistry};
 
 #[derive(Clone)]
 pub struct GatewayState {
@@ -38,6 +38,8 @@ pub struct GatewayState {
     pub heartbeat: Arc<HeartbeatEngine>,
     pub skills: Arc<SkillRegistry>,
     pub agent: Arc<AgentEngine>,
+    /// Operator token checked on every non-public route.
+    pub operator: crate::auth::OperatorAuth,
 }
 
 #[derive(Serialize)]
@@ -388,7 +390,8 @@ pub async fn shell_handler(
     match state
         .skills
         .workspace()
-        .dispatch_shell(&payload.command, None, 15)
+        .dispatch_shell_gated(&payload.command, None, 15)
+        .await
     {
         Ok(stdout) => Ok(Json(ShellResponse {
             stdout,
@@ -455,17 +458,8 @@ pub async fn execute_skill_handler(
     State(state): State<GatewayState>,
     Json(req): Json<SkillExecutionRequest>,
 ) -> impl IntoResponse {
-    if let Some(threshold) = crate::enforcement::probe_threshold_from_env() {
-        let guard = crate::policy_guard::ProbePolicyGuard::new_reference(threshold);
-        if let Err(e) = guard.gate_skill(&req.skill_name, &req.arguments).await {
-            return Json(SkillExecutionResponse {
-                success: false,
-                output: String::new(),
-                error: Some(e.to_string()),
-            });
-        }
-    }
-    let res = state.skills.execute(&req);
+    // Membrane + probe gate (always on), then the handler.
+    let res = state.skills.execute_gated(&req).await;
     Json(res)
 }
 
@@ -537,7 +531,7 @@ async fn handle_socket(mut socket: WebSocket, state: GatewayState) {
                                     skill_name: skill_name.to_string(),
                                     arguments: args,
                                 };
-                                let res = state.skills.execute(&req);
+                                let res = state.skills.execute_gated(&req).await;
                                 let out = json!({"type": "skill_result", "response": res});
                                 let _ = socket.send(Message::Text(out.to_string())).await;
                             }
@@ -564,7 +558,7 @@ async fn handle_socket(mut socket: WebSocket, state: GatewayState) {
                             }
                             "shell" => {
                                 let cmd_str = parsed.get("command").and_then(|v| v.as_str()).unwrap_or("echo shell ready");
-                                let out = match state.skills.workspace().dispatch_shell(cmd_str, None, 15) {
+                                let out = match state.skills.workspace().dispatch_shell_gated(cmd_str, None, 15).await {
                                     Ok(stdout) => json!({
                                         "type": "shell_output",
                                         "stdout": stdout,
@@ -655,7 +649,10 @@ pub async fn probe_handler(
     }))
 }
 
+/// Every route sits behind `auth::require_operator`: deny by default, a short
+/// list of read-only GET routes is public, everything else needs the token.
 pub fn create_router(state: GatewayState) -> Router {
+    let operator = state.operator.clone();
     Router::new()
         .route("/health", get(health_handler))
         .route("/api/v1/health", get(health_handler))
@@ -677,6 +674,11 @@ pub fn create_router(state: GatewayState) -> Router {
         .route("/v1/probe", post(probe_handler))
         .route("/ws", get(ws_handler))
         .route("/api/v1/ws", get(ws_handler))
+        // Auth wraps every route (including unknown paths), inside CORS.
+        .layer(axum::middleware::from_fn_with_state(
+            operator,
+            crate::auth::require_operator,
+        ))
         .layer(
             CorsLayer::new()
                 .allow_origin(Any)
@@ -686,12 +688,19 @@ pub fn create_router(state: GatewayState) -> Router {
         .with_state(state)
 }
 
+/// Listens on `addr`. Callers build it with `auth::resolve_bind_addr`, which
+/// refuses non-loopback addresses unless the operator opted in.
 pub async fn start_gateway(
     state: GatewayState,
-    port: u16,
+    addr: SocketAddr,
 ) -> Result<(), Box<dyn std::error::Error>> {
+    if !state.operator.is_configured() {
+        tracing::warn!(
+            "No operator token configured ({}); protected routes will refuse every request",
+            crate::auth::OPERATOR_TOKEN_ENV
+        );
+    }
     let app = create_router(state);
-    let addr = SocketAddr::from(([0, 0, 0, 0], port));
     info!("AEGIS Gateway listening on http://{}", addr);
 
     let listener = tokio::net::TcpListener::bind(addr).await?;
@@ -723,6 +732,7 @@ mod tests {
             heartbeat,
             skills,
             agent,
+            operator: crate::auth::OperatorAuth::disabled(),
         };
 
         let res = health_handler(State(state)).await.into_response();
diff --git a/src/heartbeat.rs b/src/heartbeat.rs
index 0cd26b4..6bc6507 100644
--- a/src/heartbeat.rs
+++ b/src/heartbeat.rs
@@ -128,7 +128,11 @@ impl HeartbeatEngine {
                         &task.payload
                     };
 
-                    let res_text = match self.workspace.dispatch_shell(cmd_to_run, None, 15) {
+                    let res_text = match self
+                        .workspace
+                        .dispatch_shell_gated(cmd_to_run, None, 15)
+                        .await
+                    {
                         Ok(stdout) => format!("Exit code 0: {}", stdout.trim()),
                         Err(e) => format!("Execution failure: {}", e),
                     };
diff --git a/src/lib.rs b/src/lib.rs
index 7fcca02..c488946 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,5 @@
 pub mod agent;
+pub mod auth;
 pub mod defense;
 pub mod events;
 pub mod execution;
@@ -14,6 +15,7 @@ pub mod skills;
 pub mod vault;
 
 pub use agent::{AgentEngine, AgentExecutionResult, AgentStep};
+pub use auth::{resolve_bind_addr, OperatorAuth};
 pub use defense::{Approval, ApprovalStatus, ContainmentLevel, DefenseReceipt, DoctrineDecision};
 pub use events::{AegisEvent, EventBus, EventEnvelope, EventId, EventSubscriber};
 pub use execution::{Action, ActionReceipt, ActionRequest, ActionStatus, ExecutionAuthority};
diff --git a/src/main.rs b/src/main.rs
index c98154e..33b7741 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -24,6 +24,15 @@ enum Commands {
     Serve {
         #[arg(short, long, default_value = "18096")]
         port: u16,
+        /// Listen address. Loopback by default; anything else needs --allow-non-loopback-bind.
+        #[arg(long, default_value = "127.0.0.1")]
+        bind: String,
+        /// Explicit opt-in to listen on a non-loopback address.
+        #[arg(long, default_value_t = false)]
+        allow_non_loopback_bind: bool,
+        /// File holding the operator token (else AEGIS_OPERATOR_TOKEN).
+        #[arg(long)]
+        operator_token_file: Option<String>,
         #[arg(long, default_value = "embedded")]
         inference: String,
         #[arg(long, default_value = "http://127.0.0.1:18006/v1/chat/completions")]
@@ -121,9 +130,7 @@ fn resolve_inference_engine(
             None,
         )))
     } else {
-        info!(
-            "Binding AEGIS to in-process EmbeddedInferenceBackend (NativeTransformerBackend)..."
-        );
+        info!("Binding AEGIS to in-process EmbeddedInferenceBackend (NativeTransformerBackend)...");
         let backend = EmbeddedInferenceBackend::load_or_fallback(model_path, tokenizer_path)
             .map_err(|e| anyhow::anyhow!(e))?;
         info!(
@@ -163,6 +170,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
 
     match cli.command.unwrap_or(Commands::Serve {
         port: 18096,
+        bind: "127.0.0.1".to_string(),
+        allow_non_loopback_bind: false,
+        operator_token_file: None,
         inference: "embedded".to_string(),
         max_url: "http://127.0.0.1:18006/v1/chat/completions".to_string(),
         model_path: None,
@@ -172,6 +182,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
     }) {
         Commands::Serve {
             port,
+            bind,
+            allow_non_loopback_bind,
+            operator_token_file,
             inference: inference_mode,
             max_url,
             model_path,
@@ -180,6 +193,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
             heartbeat_secs,
         } => {
             info!("Initializing AEGIS engine on Grace Blackwell GB10...");
+            // Refuse a bad listen address or a malformed token before starting anything.
+            let addr = aegis::resolve_bind_addr(&bind, port, allow_non_loopback_bind)
+                .map_err(|e| anyhow::anyhow!(e))?;
+            let operator = aegis::OperatorAuth::load(operator_token_file.as_deref().map(Path::new))
+                .map_err(|e| anyhow::anyhow!(e))?;
             let db = Arc::new(Database::open(Path::new(&db_path))?);
             let inference = resolve_inference_engine(
                 &inference_mode,
@@ -208,10 +226,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
                 heartbeat: heartbeat.clone(),
                 skills: skills.clone(),
                 agent: agent.clone(),
+                operator,
             };
 
-            info!("Starting Axum sub-millisecond gateway on port {}", port);
-            start_gateway(state, port).await?;
+            info!("Starting Axum sub-millisecond gateway on {}", addr);
+            start_gateway(state, addr).await?;
         }
         Commands::Tick { db_path } => {
             info!("Executing single autonomous heartbeat tick...");
diff --git a/src/orchestration/.crumb b/src/orchestration/.crumb
new file mode 100644
index 0000000..d1dc640
--- /dev/null
+++ b/src/orchestration/.crumb
@@ -0,0 +1,23 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/orchestration",
+  "layer": "src/orchestration",
+  "purpose": "Directory src/orchestration. Purpose not yet described by a human.",
+  "above": {
+    "name": "src",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/orchestration. Purpose not yet described by a human.",
+      "files": [
+        "budget.rs",
+        "mod.rs",
+        "run.rs",
+        "termination.rs",
+        "trigger.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/persistence/.crumb b/src/persistence/.crumb
new file mode 100644
index 0000000..2f77642
--- /dev/null
+++ b/src/persistence/.crumb
@@ -0,0 +1,28 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/persistence",
+  "layer": "src/persistence",
+  "purpose": "Directory src/persistence. Purpose not yet described by a human.",
+  "above": {
+    "name": "src",
+    "path": ".."
+  },
+  "below": [
+    {
+      "name": "sqlite",
+      "role": ""
+    }
+  ],
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/persistence. Purpose not yet described by a human.",
+      "files": [
+        "async_db.rs",
+        "error.rs",
+        "legacy.rs",
+        "mod.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/persistence/sqlite/.crumb b/src/persistence/sqlite/.crumb
new file mode 100644
index 0000000..e379b9c
--- /dev/null
+++ b/src/persistence/sqlite/.crumb
@@ -0,0 +1,25 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/persistence/sqlite",
+  "layer": "src/persistence/sqlite",
+  "purpose": "Directory src/persistence/sqlite. Purpose not yet described by a human.",
+  "above": {
+    "name": "src/persistence",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/persistence/sqlite. Purpose not yet described by a human.",
+      "files": [
+        "actions.rs",
+        "approvals.rs",
+        "messages.rs",
+        "mod.rs",
+        "runs.rs",
+        "schema.rs",
+        "sessions.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/security.rs b/src/security.rs
index 3fb139b..6697cae 100644
--- a/src/security.rs
+++ b/src/security.rs
@@ -253,6 +253,21 @@ impl WorkspaceCapability {
         self.execute_shell(command, cwd, timeout_secs)
     }
 
+    /// `dispatch_shell` behind the probe gate. HTTP, WebSocket and heartbeat
+    /// shell paths use this.
+    pub async fn dispatch_shell_gated(
+        &self,
+        command: &str,
+        cwd: Option<&str>,
+        timeout_secs: u64,
+    ) -> Result<String, SecurityError> {
+        let args = serde_json::json!({ "command": command });
+        crate::enforcement::probe_gate("bash_eval", &args)
+            .await
+            .map_err(SecurityError::AccessDenied)?;
+        self.dispatch_shell(command, cwd, timeout_secs)
+    }
+
     /// Low-level executor. Callers use `dispatch_shell`.
     pub(crate) fn execute_shell(
         &self,
diff --git a/src/sessions/.crumb b/src/sessions/.crumb
new file mode 100644
index 0000000..28a217e
--- /dev/null
+++ b/src/sessions/.crumb
@@ -0,0 +1,23 @@
+{
+  "schema_version": "1.0.0",
+  "name": "src/sessions",
+  "layer": "src/sessions",
+  "purpose": "Directory src/sessions. Purpose not yet described by a human.",
+  "above": {
+    "name": "src",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory src/sessions. Purpose not yet described by a human.",
+      "files": [
+        "id.rs",
+        "message.rs",
+        "mod.rs",
+        "session.rs",
+        "store.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/src/skills.rs b/src/skills.rs
index 7337a2b..ea990ac 100644
--- a/src/skills.rs
+++ b/src/skills.rs
@@ -108,6 +108,19 @@ impl SkillRegistry {
         tools
     }
 
+    /// Membrane, then probe gate, then the handler. Every outside caller
+    /// (HTTP, WebSocket, agent tool calls) uses this path.
+    pub async fn execute_gated(&self, req: &SkillExecutionRequest) -> SkillExecutionResponse {
+        if let Err(reason) = crate::enforcement::probe_gate(&req.skill_name, &req.arguments).await {
+            return SkillExecutionResponse {
+                success: false,
+                output: String::new(),
+                error: Some(reason),
+            };
+        }
+        self.execute(req)
+    }
+
     pub fn execute(&self, req: &SkillExecutionRequest) -> SkillExecutionResponse {
         if let Err(reason) = crate::enforcement::pre_dispatch_check(&req.skill_name, &req.arguments)
         {
diff --git a/tests/.crumb b/tests/.crumb
new file mode 100644
index 0000000..57a5948
--- /dev/null
+++ b/tests/.crumb
@@ -0,0 +1,32 @@
+{
+  "schema_version": "1.0.0",
+  "name": "tests",
+  "layer": "tests",
+  "purpose": "Directory tests. Purpose not yet described by a human.",
+  "above": {
+    "name": "aegis-runtime",
+    "path": ".."
+  },
+  "below": [
+    {
+      "name": "fixtures",
+      "role": ""
+    }
+  ],
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory tests. Purpose not yet described by a human.",
+      "files": [
+        "aegis_tests.rs",
+        "canonical_abi_tests.rs",
+        "embedded_inference_tests.rs",
+        "gateway_auth_tests.rs",
+        "policy_guard_tests.rs",
+        "probe_gate_tests.rs",
+        "stage2_primitives_tests.rs",
+        "stage3_4_persistence_tests.rs"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/tests/aegis_tests.rs b/tests/aegis_tests.rs
index bc0da4d..d8c2955 100644
--- a/tests/aegis_tests.rs
+++ b/tests/aegis_tests.rs
@@ -12,6 +12,28 @@ use std::sync::Arc;
 use std::time::Instant;
 use tower::util::ServiceExt;
 
+/// Operator token used by the test gateway.
+pub const TEST_OPERATOR_TOKEN: &str = "test-operator-token-0123456789abcdef";
+
+fn auth_header() -> String {
+    format!("Bearer {}", TEST_OPERATOR_TOKEN)
+}
+
+/// A catalogued local command that the always-on probe gate admits.
+/// The deterministic reference probe refuses `bash_eval` with `ls` (hash verdict:
+/// safety < 0.5, scope "unauthorized_escalation"), so tests that must see a
+/// successful run use `git status` (safety >= 0.5, scope "contained"). Tests
+/// run with the crate root as working directory, which is a git checkout.
+pub const PROBE_ADMITTED_COMMAND: &str = "git status";
+
+fn authed_ws_request(url: &str) -> tokio_tungstenite::tungstenite::handshake::client::Request {
+    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+    let mut req = url.into_client_request().unwrap();
+    req.headers_mut()
+        .insert("authorization", auth_header().parse().unwrap());
+    req
+}
+
 async fn spawn_mock_inference_server() -> String {
     let app = axum::Router::new()
         .route(
@@ -107,6 +129,7 @@ async fn create_test_state() -> GatewayState {
         heartbeat,
         skills,
         agent,
+        operator: aegis::OperatorAuth::with_token(TEST_OPERATOR_TOKEN).unwrap(),
     }
 }
 
@@ -154,6 +177,7 @@ async fn test_gateway_openai_completions_endpoint() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -190,6 +214,7 @@ async fn test_gateway_openai_multiturn_completions() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -224,6 +249,7 @@ async fn test_gateway_openai_streaming_endpoint() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -272,7 +298,7 @@ async fn test_gateway_skills_endpoints() {
     let app2 = create_router(state);
     let exec_payload = serde_json::json!({
         "skill_name": "bash_eval",
-        "arguments": {"command": "ls"}
+        "arguments": {"command": PROBE_ADMITTED_COMMAND}
     });
 
     let exec_res = app2
@@ -280,6 +306,7 @@ async fn test_gateway_skills_endpoints() {
             Request::builder()
                 .method("POST")
                 .uri("/api/v1/skills/execute")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(exec_payload.to_string()))
                 .unwrap(),
@@ -301,7 +328,7 @@ async fn test_gateway_shell_execution() {
     let app = create_router(state);
 
     let req_payload = serde_json::json!({
-        "command": "ls"
+        "command": PROBE_ADMITTED_COMMAND
     });
 
     let response = app
@@ -309,6 +336,7 @@ async fn test_gateway_shell_execution() {
             Request::builder()
                 .method("POST")
                 .uri("/api/v1/shell")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -339,6 +367,7 @@ async fn test_gateway_task_creation_and_listing() {
             Request::builder()
                 .method("POST")
                 .uri("/api/v1/tasks")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -353,6 +382,7 @@ async fn test_gateway_task_creation_and_listing() {
         .oneshot(
             Request::builder()
                 .uri("/api/v1/tasks")
+                .header("Authorization", auth_header())
                 .body(Body::empty())
                 .unwrap(),
         )
@@ -381,7 +411,9 @@ async fn test_gateway_websocket_lifecycle() {
     });
 
     let ws_url = format!("ws://127.0.0.1:{}/ws", port);
-    let (mut ws_stream, _) = tokio_tungstenite::connect_async(ws_url).await.unwrap();
+    let (mut ws_stream, _) = tokio_tungstenite::connect_async(authed_ws_request(&ws_url))
+        .await
+        .unwrap();
 
     // 1. Welcome message
     let msg = ws_stream.next().await.unwrap().unwrap();
@@ -465,6 +497,7 @@ async fn test_gateway_agent_run_endpoint() {
             Request::builder()
                 .method("POST")
                 .uri("/api/v1/agent/run")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -534,6 +567,7 @@ async fn test_gateway_concurrent_requests_under_tokio_spawns() {
                     });
                     let res = client_clone
                         .post(format!("{}/v1/chat/completions", base))
+                        .header("Authorization", auth_header())
                         .json(&payload)
                         .send()
                         .await
@@ -560,6 +594,7 @@ async fn test_gateway_completions_error_handling_and_validation() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from("{ \"model\": invalid_syntax"))
                 .unwrap(),
@@ -581,6 +616,7 @@ async fn test_gateway_completions_error_handling_and_validation() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(missing_field_payload.to_string()))
                 .unwrap(),
@@ -600,6 +636,7 @@ async fn test_gateway_completions_error_handling_and_validation() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(empty_messages_payload.to_string()))
                 .unwrap(),
@@ -624,6 +661,7 @@ async fn test_gateway_completions_error_handling_and_validation() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(unsupported_model_payload.to_string()))
                 .unwrap(),
@@ -654,6 +692,7 @@ async fn test_gateway_openai_streaming_formatting_and_terminal_chunk() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(payload.to_string()))
                 .unwrap(),
@@ -712,6 +751,7 @@ async fn test_gateway_agent_run_complex_payloads_and_edge_paths() {
             Request::builder()
                 .method("POST")
                 .uri("/api/v1/agent/run")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(payload.to_string()))
                 .unwrap(),
@@ -744,7 +784,9 @@ async fn test_gateway_websocket_lifecycle_ping_pong_and_close() {
     });
 
     let ws_url = format!("ws://127.0.0.1:{}/ws", port);
-    let (mut ws_stream, _) = tokio_tungstenite::connect_async(ws_url).await.unwrap();
+    let (mut ws_stream, _) = tokio_tungstenite::connect_async(authed_ws_request(&ws_url))
+        .await
+        .unwrap();
 
     // 1. Welcome frame
     let welcome_msg = ws_stream.next().await.unwrap().unwrap();
@@ -779,7 +821,7 @@ async fn test_gateway_websocket_lifecycle_ping_pong_and_close() {
         .send(tokio_tungstenite::tungstenite::Message::Text(
             serde_json::json!({
                 "type": "shell",
-                "command": "ls"
+                "command": PROBE_ADMITTED_COMMAND
             })
             .to_string(),
         ))
@@ -1014,6 +1056,7 @@ async fn test_gateway_offline_inference_fail_closed() {
         heartbeat,
         skills,
         agent,
+        operator: aegis::OperatorAuth::with_token(TEST_OPERATOR_TOKEN).unwrap(),
     };
     let app = create_router(state);
 
@@ -1029,6 +1072,7 @@ async fn test_gateway_offline_inference_fail_closed() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header("Authorization", auth_header())
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
@@ -1083,6 +1127,7 @@ async fn test_gateway_probe_endpoint() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/probe")
+                .header("Authorization", auth_header())
                 .header("content-type", "application/json")
                 .body(Body::from(serde_json::to_vec(&payload).unwrap()))
                 .unwrap(),
diff --git a/tests/embedded_inference_tests.rs b/tests/embedded_inference_tests.rs
index f2e343e..2bf24fb 100644
--- a/tests/embedded_inference_tests.rs
+++ b/tests/embedded_inference_tests.rs
@@ -221,6 +221,8 @@ async fn test_gateway_with_embedded_inference_streaming() {
         heartbeat,
         skills,
         agent,
+        operator: aegis::OperatorAuth::with_token("embedded-test-operator-token-0123456789")
+            .unwrap(),
     };
     let app = create_router(state);
 
@@ -238,6 +240,10 @@ async fn test_gateway_with_embedded_inference_streaming() {
             Request::builder()
                 .method("POST")
                 .uri("/v1/chat/completions")
+                .header(
+                    "Authorization",
+                    "Bearer embedded-test-operator-token-0123456789",
+                )
                 .header("Content-Type", "application/json")
                 .body(Body::from(req_payload.to_string()))
                 .unwrap(),
diff --git a/tests/fixtures/.crumb b/tests/fixtures/.crumb
new file mode 100644
index 0000000..f896e5c
--- /dev/null
+++ b/tests/fixtures/.crumb
@@ -0,0 +1,19 @@
+{
+  "schema_version": "1.0.0",
+  "name": "tests/fixtures",
+  "layer": "tests/fixtures",
+  "purpose": "Directory tests/fixtures. Purpose not yet described by a human.",
+  "above": {
+    "name": "tests",
+    "path": ".."
+  },
+  "extensions": {
+    "seed": {
+      "purpose_auto": "Directory tests/fixtures. Purpose not yet described by a human.",
+      "files": [
+        "simd_math_vectors.json"
+      ]
+    },
+    "owner_lane": ""
+  }
+}
diff --git a/tests/gateway_auth_tests.rs b/tests/gateway_auth_tests.rs
new file mode 100644
index 0000000..7d4b3f2
--- /dev/null
+++ b/tests/gateway_auth_tests.rs
@@ -0,0 +1,356 @@
+//! Gateway hardening: operator token on every non-public route, loopback bind
+//! by default, allowlist dispatch. Each test is a bypass attempt or a
+//! realistic fault the rule must catch.
+
+use aegis::{
+    create_router, AgentEngine, Database, GatewayState, HeartbeatEngine, HttpInferenceBackend,
+    OperatorAuth, SkillRegistry, WorkspaceCapability,
+};
+use axum::{
+    body::Body,
+    http::{Request, StatusCode},
+};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::Instant;
+use tower::util::ServiceExt;
+
+const TOKEN: &str = "auth-test-operator-token-0123456789abcdef";
+
+fn state_with(auth: OperatorAuth, workspace: &std::path::Path) -> GatewayState {
+    let db = Arc::new(Database::open_in_memory().unwrap());
+    // Unreachable inference: no route here should need a model to answer.
+    let inference = Arc::new(HttpInferenceBackend::new(
+        Some("http://127.0.0.1:9/v1/chat/completions".to_string()),
+        None,
+    ));
+    let heartbeat = Arc::new(HeartbeatEngine::new(60, db.clone()));
+    let skills = Arc::new(SkillRegistry::with_workspace(
+        WorkspaceCapability::new(workspace).unwrap(),
+    ));
+    let agent = Arc::new(AgentEngine::new(
+        inference.clone(),
+        skills.clone(),
+        Some(db.clone()),
+    ));
+    GatewayState {
+        start_time: Instant::now(),
+        db,
+        inference,
+        heartbeat,
+        skills,
+        agent,
+        operator: auth,
+    }
+}
+
+fn authed() -> OperatorAuth {
+    OperatorAuth::with_token(TOKEN).unwrap()
+}
+
+async fn send(
+    state: &GatewayState,
+    method: &str,
+    uri: &str,
+    headers: &[(&str, String)],
+    body: Value,
+) -> (StatusCode, Value) {
+    let mut b = Request::builder()
+        .method(method)
+        .uri(uri)
+        .header("content-type", "application/json");
+    for (k, v) in headers {
+        b = b.header(*k, v);
+    }
+    let res = create_router(state.clone())
+        .oneshot(b.body(Body::from(body.to_string())).unwrap())
+        .await
+        .unwrap();
+    let status = res.status();
+    let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
+        .await
+        .unwrap();
+    (
+        status,
+        serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+    )
+}
+
+fn bearer(t: &str) -> Vec<(&'static str, String)> {
+    vec![("authorization", format!("Bearer {}", t))]
+}
+
+/// Every mutating or effectful route, with a body that would act if admitted.
+fn protected_routes() -> Vec<(&'static str, &'static str, Value)> {
+    vec![
+        ("POST", "/api/v1/shell", json!({"command": "ls"})),
+        (
+            "POST",
+            "/api/v1/skills/execute",
+            json!({"skill_name": "write_file", "arguments": {"path": "pwned.txt", "content": "x"}}),
+        ),
+        (
+            "POST",
+            "/api/v1/tasks",
+            json!({"task_type": "shell_exec", "payload": "ls"}),
+        ),
+        (
+            "POST",
+            "/api/v1/agent/run",
+            json!({"prompt": "hi", "max_turns": 1}),
+        ),
+        ("POST", "/api/v1/chat", json!({"prompt": "hi"})),
+        ("POST", "/api/v1/heartbeat/tick", json!({})),
+        (
+            "POST",
+            "/api/v1/discord/relay",
+            json!({"channel_id": "c", "author": "a", "content": "hi"}),
+        ),
+        (
+            "POST",
+            "/v1/chat/completions",
+            json!({"messages": [{"role": "user", "content": "hi"}]}),
+        ),
+        ("POST", "/v1/probe", json!({"state": {}, "probes": {}})),
+        ("GET", "/ws", json!({})),
+        ("GET", "/api/v1/ws", json!({})),
+    ]
+}
+
+#[tokio::test]
+async fn protected_routes_refuse_missing_or_wrong_tokens() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(authed(), ws.path());
+    let attempts: Vec<Vec<(&str, String)>> = vec![
+        vec![],
+        bearer("wrong-token-wrong-token-wrong-token-xx"),
+        bearer(&TOKEN[..TOKEN.len() - 1]),
+        bearer(&format!("{}x", TOKEN)),
+        bearer(""),
+        vec![("authorization", format!("bearer {}", TOKEN))],
+        vec![("authorization", format!("Basic {}", TOKEN))],
+        vec![("authorization", TOKEN.to_string())],
+        vec![("x-forwarded-for", "127.0.0.1".to_string())],
+        vec![("x-aegis-operator-token", "nope".to_string())],
+    ];
+    for (method, uri, body) in protected_routes() {
+        for headers in &attempts {
+            let (status, _) = send(&state, method, uri, headers, body.clone()).await;
+            assert_eq!(
+                status,
+                StatusCode::UNAUTHORIZED,
+                "{} {} admitted with headers {:?}",
+                method,
+                uri,
+                headers
+            );
+        }
+        // Token in the query string is never read.
+        let q = format!("{}?token={}&operator_token={}", uri, TOKEN, TOKEN);
+        let (status, _) = send(&state, method, &q, &[], body.clone()).await;
+        assert_eq!(status, StatusCode::UNAUTHORIZED, "{} via query", uri);
+    }
+    // The refused write never happened.
+    assert!(!ws.path().join("pwned.txt").exists());
+    assert!(state.db.list_pending_tasks().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn path_tricks_do_not_reach_public_list() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(authed(), ws.path());
+    for uri in [
+        "/health/../api/v1/shell",
+        "/api/v1/health/../shell",
+        "//api/v1/shell",
+        "/api/v1/shell/",
+        "/API/V1/SHELL",
+    ] {
+        let (status, _) = send(&state, "POST", uri, &[], json!({"command": "ls"})).await;
+        assert!(
+            status == StatusCode::UNAUTHORIZED || status == StatusCode::NOT_FOUND,
+            "{} gave {}",
+            uri,
+            status
+        );
+        assert_ne!(status, StatusCode::OK, "{}", uri);
+    }
+    // A POST to a public read path is not public.
+    let (status, _) = send(&state, "POST", "/api/v1/tasks", &[], json!({})).await;
+    assert_eq!(status, StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn no_configured_token_means_protected_routes_are_closed() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(OperatorAuth::disabled(), ws.path());
+    for (method, uri, body) in protected_routes() {
+        for headers in [vec![], bearer(""), bearer(TOKEN)] {
+            let (status, _) = send(&state, method, uri, &headers, body.clone()).await;
+            assert_eq!(
+                status,
+                StatusCode::SERVICE_UNAVAILABLE,
+                "{} {}",
+                method,
+                uri
+            );
+        }
+    }
+    let (status, _) = send(&state, "GET", "/health", &[], json!({})).await;
+    assert_eq!(status, StatusCode::OK);
+}
+
+#[tokio::test]
+async fn public_reads_stay_open() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(authed(), ws.path());
+    for uri in [
+        "/health",
+        "/api/v1/health",
+        "/api/v1/skills",
+        "/api/v1/tasks",
+    ] {
+        let (status, _) = send(&state, "GET", uri, &[], json!({})).await;
+        assert_eq!(status, StatusCode::OK, "{}", uri);
+    }
+}
+
+#[tokio::test]
+async fn correct_token_admits_catalogued_shell_only() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(authed(), ws.path());
+    let (status, body) = send(
+        &state,
+        "POST",
+        "/api/v1/shell",
+        &bearer(TOKEN),
+        json!({"command": "ls"}),
+    )
+    .await;
+    assert_eq!(status, StatusCode::OK);
+    // Either success or a probe refusal; never an allowlist refusal.
+    if body["success"] != true {
+        assert!(
+            body["stderr"].as_str().unwrap_or("").contains("probe"),
+            "{}",
+            body
+        );
+    }
+    let alt = vec![("x-aegis-operator-token", TOKEN.to_string())];
+    for cmd in [
+        "rm -r -f /",
+        "find . -delete",
+        "curl http://example.invalid",
+        "ls; id",
+        "ls $(id)",
+        "git push",
+        "ls -la /",
+    ] {
+        let (status, body) = send(
+            &state,
+            "POST",
+            "/api/v1/shell",
+            &alt,
+            json!({ "command": cmd }),
+        )
+        .await;
+        assert_eq!(status, StatusCode::OK);
+        assert_eq!(body["success"], false, "{:?} ran", cmd);
+    }
+}
+
+#[tokio::test]
+async fn skill_allowlist_holds_behind_the_token() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(authed(), ws.path());
+    for name in ["exec", "shell", "Bash_eval", "bash_eval ", "spawn_process"] {
+        let (status, body) = send(
+            &state,
+            "POST",
+            "/api/v1/skills/execute",
+            &bearer(TOKEN),
+            json!({"skill_name": name, "arguments": {"command": "ls"}}),
+        )
+        .await;
+        assert_eq!(status, StatusCode::OK);
+        assert_eq!(body["success"], false, "{:?} dispatched", name);
+        assert!(
+            body["error"].as_str().unwrap().contains("allowlist"),
+            "{}",
+            body
+        );
+    }
+}
+
+#[tokio::test]
+async fn websocket_handshake_needs_the_token() {
+    let ws = tempfile::tempdir().unwrap();
+    let state = state_with(authed(), ws.path());
+    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+    let port = listener.local_addr().unwrap().port();
+    let app = create_router(state);
+    tokio::spawn(async move {
+        axum::serve(listener, app).await.unwrap();
+    });
+    let url = format!("ws://127.0.0.1:{}/ws", port);
+    let refused = tokio_tungstenite::connect_async(url.clone()).await;
+    assert!(refused.is_err(), "unauthenticated WebSocket was accepted");
+
+    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+    let mut req = url.into_client_request().unwrap();
+    req.headers_mut().insert(
+        "authorization",
+        format!("Bearer {}", TOKEN).parse().unwrap(),
+    );
+    assert!(tokio_tungstenite::connect_async(req).await.is_ok());
+}
+
+/// Runs `aegis serve ...` and expects it to exit on its own (refusal).
+/// If it starts listening instead, it is killed and the test fails.
+fn serve_must_refuse(args: &[&str], token: Option<&str>) -> String {
+    let dir = tempfile::tempdir().unwrap();
+    let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_aegis"));
+    cmd.arg("serve")
+        .args(args)
+        .args(["--port", "0", "--inference", "http"])
+        .current_dir(dir.path())
+        .stdout(std::process::Stdio::piped())
+        .stderr(std::process::Stdio::piped());
+    match token {
+        Some(t) => cmd.env("AEGIS_OPERATOR_TOKEN", t),
+        None => cmd.env_remove("AEGIS_OPERATOR_TOKEN"),
+    };
+    let mut child = cmd.spawn().unwrap();
+    let deadline = Instant::now() + std::time::Duration::from_secs(30);
+    let status = loop {
+        if let Some(s) = child.try_wait().unwrap() {
+            break s;
+        }
+        if Instant::now() > deadline {
+            let _ = child.kill();
+            panic!("aegis serve {:?} started instead of refusing", args);
+        }
+        std::thread::sleep(std::time::Duration::from_millis(50));
+    };
+    assert!(!status.success());
+    let out = child.wait_with_output().unwrap();
+    format!(
+        "{}{}",
+        String::from_utf8_lossy(&out.stdout),
+        String::from_utf8_lossy(&out.stderr)
+    )
+}
+
+#[test]
+fn serve_refuses_non_loopback_bind_without_opt_in() {
+    for addr in ["0.0.0.0", "::", "192.0.2.10"] {
+        let text = serve_must_refuse(&["--bind", addr], None);
+        assert!(text.contains("non-loopback"), "{}: {}", addr, text);
+    }
+}
+
+#[test]
+fn serve_refuses_a_short_operator_token() {
+    let text = serve_must_refuse(&[], Some("short"));
+    assert!(text.contains("at least"), "{}", text);
+}
diff --git a/tests/probe_gate_tests.rs b/tests/probe_gate_tests.rs
new file mode 100644
index 0000000..c5934b3
--- /dev/null
+++ b/tests/probe_gate_tests.rs
@@ -0,0 +1,34 @@
+//! Probe gating is wired into every dispatch path. With the strictest
+//! threshold the reference oracle refuses, so a path that skips the gate
+//! would run the command. Separate test binary: it sets a process env var.
+
+use aegis::{SkillExecutionRequest, SkillRegistry, WorkspaceCapability};
+
+#[tokio::test]
+async fn strict_probe_threshold_refuses_on_every_path() {
+    std::env::set_var("AIEN_PROBE_ENFORCE", "1.0");
+    let dir = tempfile::tempdir().unwrap();
+    let registry = SkillRegistry::with_workspace(WorkspaceCapability::new(dir.path()).unwrap());
+
+    let req = SkillExecutionRequest {
+        skill_name: "bash_eval".to_string(),
+        arguments: serde_json::json!({ "command": "ls" }),
+    };
+    let res = registry.execute_gated(&req).await;
+    assert!(!res.success, "skill ran past the probe gate");
+    assert!(res.error.unwrap_or_default().contains("probe"));
+
+    let shell = registry
+        .workspace()
+        .dispatch_shell_gated("ls", None, 5)
+        .await;
+    let err = shell.expect_err("shell ran past the probe gate");
+    assert!(err.to_string().contains("probe"), "{}", err);
+
+    let write = SkillExecutionRequest {
+        skill_name: "write_file".to_string(),
+        arguments: serde_json::json!({ "path": "gated.txt", "content": "x" }),
+    };
+    assert!(!registry.execute_gated(&write).await.success);
+    assert!(!dir.path().join("gated.txt").exists());
+}