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
About Files History Releases Proposed changes Issues For developers
Make piped installation and release bundles reproducible
merged fcdf833876e476dc #134 · opened 2026-09-29 19:52 UTC · closed 2026-09-29 20:06 UTC · merged 2026-09-29 20:06 UTC
Imported from GitHub aien-dev/aien-sovereign-core-mv#134, by drakestapleton
Base 4e82c46f35b56df741efdc5d95b16051fbab5342 · Head 773be497816f98065119c2b46a48bfd6ad393d3f
Merged on GitHub as f0b631e2316a19e242d15a80e4f46bc200c9d610 ; reachable from main 007ac4ac5ee5edc6f79f411b1706752293604044 (observed 2026-11-18T16:35:50Z)
drakestapleton wrote on 2026-09-29 19:52 UTC
Problem
Piped installs depended on the caller directory, an absolute symlink (crates/spark-aegis pointing into a home directory) broke clean checkouts, and release packaging silently omitted binaries.
Solution
Bootstrap canonical source and pinned sibling protocols (7ac6fac ) when install.sh is piped to bash; use --locked builds; install the correct CLI name.
Release packaging moves to scripts/package-release.sh and fails on missing executables.
spark-aegis is kept: its source is now tracked in crates/spark-aegis (replacing the symlink), it stays a workspace member, and install.sh still builds and installs it, so aien aegis keeps working. Hard-coded home-directory fallbacks in spark-aegis were replaced with .; the locally built Mojo library is gitignored.
Installer smoke test is scripts/test-install.sh (shell; the earlier Python version was removed per the no-Python rule). It pipes install.sh into bash from an empty directory with stand-in git/cargo, and checks the locked build, all eight installed binaries (including spark-aegis), the pinned protocols checkout, operator profile, and cleanup.
Verification
bash -n on all shell scripts; shellcheck not installed locally.
scripts/test-install.sh PASS; a mutation (dropping spark-aegis from the build line) makes it FAIL as expected.
Fresh clone next to aien-protocols at 7ac6fac : cargo build --release --locked --workspace OK; scripts/package-release.sh produced a bundle with all 8 binaries; cargo clippy -p spark-aegis --all-targets -D warnings clean; cargo test -p spark-aegis 26 passed.
Notes
aien-protocols pin: ci.yml, release.yml and install.sh now all use 7ac6fac . Before this PR, CI built against latest aien-protocols; keep the three in step when the pin moves.
Pre-existing, not changed here: other source/test files still contain absolute home-directory paths (runtime defaults, examples, tests), several .py files remain in the repo, and crates/aien-inference-abi/tests/fixtures is a symlink.
No deployment or live install performed.
🤖 Generated with Claude Code
Apply it
git checkout -b patch-fcdf833876e476dc 4e82c46f35b56df741efdc5d95b16051fbab5342
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/fcdf833876e476dc .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/aien-sovereign-core-mv
134
773be497816f98065119c2b46a48bfd6ad393d3f
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":134,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/134","export_sha256":"d815604dc795b494a931d4c9d256159461266bed51d6da460421ed1d94dab90f ","imported_utc":"2026-11-18T16:35:50Z"}
Changes
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cefa763a ..f5bd02ce 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -22,6 +22,7 @@ jobs:
uses: actions/checkout@v4
with:
repository: aien-dev/aien-protocols
+ ref: 7ac6facb630ca7e9a6ab4125b292203fe2bb6687
path: aien-protocols
- name: Setup Sibling Dependencies
@@ -37,6 +38,9 @@ jobs:
- name: Verify Code Formatting
run: cargo fmt --all -- --check
+ - name: Verify Piped Installer Bootstrap
+ run: bash scripts/test-install.sh
+
- name: Cargo Workspace Check
run: cargo check --workspace --all-targets
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c2a11e0d ..d02dcff3 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -30,28 +30,26 @@ jobs:
- name: Checkout Source
uses: actions/checkout@v4
+ - name: Checkout pinned protocols
+ uses: actions/checkout@v4
+ with:
+ repository: aien-dev/aien-protocols
+ ref: 7ac6facb630ca7e9a6ab4125b292203fe2bb6687
+ path: protocols-checkout
+
+ - name: Place sibling dependency
+ run: mv protocols-checkout ../aien-protocols
+
- name: Install Rust Toolchain
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Build Workspace
- run: cargo build --release --workspace
+ run: cargo build --locked --release --workspace
- name: Package Release Assets
- run: |
- mkdir -p dist/bin dist/imprints
- cp target/release/aien dist/bin/ 2>/dev/null || true
- cp target/release/spark-cockpit-rs dist/bin/ 2>/dev/null || true
- cp target/release/spark-inquisitor dist/bin/ 2>/dev/null || true
- cp target/release/cortex-encoder-rs dist/bin/ 2>/dev/null || true
- cp target/release/cortex-rs dist/bin/ 2>/dev/null || true
- cp target/release/spark-supervisor dist/bin/ 2>/dev/null || true
- cp target/release/spark-debugger dist/bin/ 2>/dev/null || true
- cp target/release/bench_inference_stack dist/bin/ 2>/dev/null || true
- cp -r imprints/en2-trinity dist/imprints/ 2>/dev/null || true
- cp CONSTITUTION.md README.md install.sh dist/ 2>/dev/null || true
- tar -czvf ${{ matrix.artifact_name }} -C dist .
+ run: bash scripts/package-release.sh "${{ matrix.artifact_name }}"
- name: Upload Artifact
uses: actions/upload-artifact@v4
diff --git a/.gitignore b/.gitignore
index 53239de3 ..1e0a6a70 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,6 @@ __pycache__/
receipt.json
tests_results.json
aien-protocols/
+
+# spark-aegis Mojo build output (built locally by build.rs, never tracked)
+crates/spark-aegis/mojo/libsimd_matcher.so
diff --git a/crates/spark-aegis b/crates/spark-aegis
deleted file mode 120000
index 1da9dae2 ..00000000
--- a/crates/spark-aegis
+++ /dev/null
@@ -1 +0,0 @@
-/home/drakestapleton/workspace/spark-aegis
\ No newline at end of file
diff --git a/crates/spark-aegis/.gitignore b/crates/spark-aegis/.gitignore
new file mode 100644
index 00000000 ..de1598c2
--- /dev/null
+++ b/crates/spark-aegis/.gitignore
@@ -0,0 +1,10 @@
+target/
+**/*.rs.bk
+*.orig
+.env
+.env.*
+*.pem
+*.key
+id_rsa
+id_ed25519
+.quarantine/
diff --git a/crates/spark-aegis/Cargo.toml b/crates/spark-aegis/Cargo.toml
new file mode 100644
index 00000000 ..88035ee8
--- /dev/null
+++ b/crates/spark-aegis/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "spark-aegis"
+version = "0.1.0"
+edition = "2021"
+authors = ["Drake Stapleton <drake.aien@proton.me>"]
+license.workspace = true
+description = "Sovereign defensive boundary and containment engine"
+
+[dependencies]
+tokio = { version = "1.43", features = ["full"] }
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+clap = { version = "4.5", features = ["derive"] }
+blake3 = "1.5"
+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
+chrono = { version = "0.4", features = ["serde"] }
+regex = "1.10"
+anyhow = "1.0"
+libloading = "0.8"
+libc = "0.2"
+
+[dev-dependencies]
+tempfile = "3.17"
diff --git a/crates/spark-aegis/README.md b/crates/spark-aegis/README.md
new file mode 100644
index 00000000 ..2115dd87
--- /dev/null
+++ b/crates/spark-aegis/README.md
@@ -0,0 +1,64 @@
+# spark-aegis
+
+Sovereign defensive boundary and containment engine for the NVIDIA DGX Spark workstation.
+
+## Sovereign Doctrine
+
+"The network is the house. Cut the session. Isolate the host. Close the door. Keep the evidence."
+
+## Invariants
+
+- **SECURE_TPM_ONLY**: Plaintext secrets and `.env` files must never touch disk. All credentials resolve dynamically via the hardware TPM vault.
+- **UNSLOP_COMPLIANCE**: Strict zero em dash and en dash policy. All AI buzzwords, transitional filler, and antithesis tropes are forbidden.
+- **PURE_NATIVE_SYSTEMS**: The entire security runtime is compiled native Rust with Mojo SIMD vector acceleration.
+- **BLAKE3_CORTEX_TRAIL**: Every incident and triage verdict commits a Blake3 cryptographic audit entity to Cortex memory.
+
+## Architecture
+
+`spark-aegis` consists of the following components:
+
+- `doctrine`: Formal definition of the four defensive actions and system invariants.
+- `scanner`: High-speed scanner detecting secrets, slop, and dangerous commands across files, directories, and git diffs.
+- `containment`: Realization of the four defensive directives (`cut_session`, `isolate_host`, `close_door`, `keep_evidence`).
+- `pr_triage`: Autonomous PR review and diff verification engine outputting cryptographically signed safety verdicts.
+- `mojo_bridge`: Dynamic bridge to Mojo 1.0 SIMD vector routines with pure Rust compiled fallback.
+- `audit`: Live system audit inspecting listening sockets, workspace confinement, and Cortex connectivity.
+
+## CLI Usage
+
+### Deep Scan
+```bash
+spark-aegis scan /path/to/target
+```
+
+### PR Triage and Review
+```bash
+spark-aegis review-pr diff.patch
+git diff | spark-aegis review-pr -
+```
+
+### Live System Audit
+```bash
+spark-aegis audit
+```
+
+### Containment Actions
+```bash
+# Terminate session
+spark-aegis contain --session pts/2
+
+# Isolate process
+spark-aegis contain --pid 12345
+
+# Quarantine path
+spark-aegis contain --close /path/to/malicious_file
+```
+
+### Display Doctrine
+```bash
+spark-aegis doctrine
+```
+
+## License
+
+Apache-2.0 WITH LLVM-exception
diff --git a/crates/spark-aegis/build.rs b/crates/spark-aegis/build.rs
new file mode 100644
index 00000000 ..79c8b3dc
--- /dev/null
+++ b/crates/spark-aegis/build.rs
@@ -0,0 +1,35 @@
+use std::path::Path;
+use std::process::Command;
+
+fn main() {
+ println!("cargo:rerun-if-changed=mojo/simd_matcher.mojo");
+ let out_dir = match std::env::var("OUT_DIR") {
+ Ok(d) => d,
+ Err(_) => return,
+ };
+ let dest_path = Path::new(&out_dir).join("libsimd_matcher.so");
+
+ if let Ok(status) = Command::new("mojo")
+ .args([
+ "build",
+ "--emit",
+ "shared-lib",
+ "mojo/simd_matcher.mojo",
+ "-o",
+ ])
+ .arg(&dest_path)
+ .status()
+ {
+ if status.success() {
+ println!(
+ "cargo:rustc-env=SPARK_AEGIS_SO_BUILT={}",
+ dest_path.display()
+ );
+ let _ = std::fs::copy(&dest_path, "mojo/libsimd_matcher.so");
+ } else {
+ println!("cargo:warning=mojo build failed, fallback to pure Rust engine");
+ }
+ } else {
+ println!("cargo:warning=mojo toolchain unavailable, fallback to pure Rust engine");
+ }
+}
diff --git a/crates/spark-aegis/mojo/simd_matcher.mojo b/crates/spark-aegis/mojo/simd_matcher.mojo
new file mode 100644
index 00000000 ..5d95d437
--- /dev/null
+++ b/crates/spark-aegis/mojo/simd_matcher.mojo
@@ -0,0 +1,82 @@
+# spark-aegis Mojo SIMD acceleration module
+# Vector signature matching and byte scanning
+
+@export("mojo_simd_version")
+def mojo_simd_version() abi("C") -> Int32:
+ return 1
+
+@export("mojo_simd_scan_byte")
+def mojo_simd_scan_byte(data: Pointer[UInt8, MutUntrackedOrigin], length: Int, target: UInt8) abi("C") -> Int:
+ comptime width = 16
+ var i: Int = 0
+ var target_vec = SIMD[DType.uint8, width](target)
+
+ while i + width <= length:
+ var chunk = data.unsafe_load[width=width](i)
+ var cmp = chunk.eq(target_vec)
+ if cmp.reduce_or():
+ for offset in range(width):
+ if data.unsafe_load(i + offset) == target:
+ return i + offset
+ i += width
+
+ while i < length:
+ if data.unsafe_load(i) == target:
+ return i
+ i += 1
+
+ return -1
+
+@export("mojo_simd_count_matches")
+def mojo_simd_count_matches(data: Pointer[UInt8, MutUntrackedOrigin], length: Int, target: UInt8) abi("C") -> Int:
+ comptime width = 16
+ var i: Int = 0
+ var count: Int = 0
+ var target_vec = SIMD[DType.uint8, width](target)
+
+ while i + width <= length:
+ var chunk = data.unsafe_load[width=width](i)
+ var cmp = chunk.eq(target_vec)
+ if cmp.reduce_or():
+ for offset in range(width):
+ if data.unsafe_load(i + offset) == target:
+ count += 1
+ i += width
+
+ while i < length:
+ if data.unsafe_load(i) == target:
+ count += 1
+ i += 1
+
+ return count
+
+@export("mojo_simd_find_pattern")
+def mojo_simd_find_pattern(data: Pointer[UInt8, MutUntrackedOrigin], data_len: Int, pattern: Pointer[UInt8, MutUntrackedOrigin], pattern_len: Int) abi("C") -> Int:
+ if pattern_len <= 0 or data_len < pattern_len:
+ return -1
+
+ var first_byte = pattern.unsafe_load(0)
+ var cursor: Int = 0
+
+ while cursor <= data_len - pattern_len:
+ var remaining = data_len - cursor
+ var relative_match = mojo_simd_scan_byte(data.unsafe_offset(cursor), remaining, first_byte)
+ if relative_match < 0:
+ return -1
+
+ var cand = cursor + relative_match
+ if cand > data_len - pattern_len:
+ return -1
+
+ var full_match = True
+ for j in range(1, pattern_len):
+ if data.unsafe_load(cand + j) != pattern.unsafe_load(j):
+ full_match = False
+ break
+
+ if full_match:
+ return cand
+
+ cursor = cand + 1
+
+ return -1
diff --git a/crates/spark-aegis/src/audit.rs b/crates/spark-aegis/src/audit.rs
new file mode 100644
index 00000000 ..fd780756
--- /dev/null
+++ b/crates/spark-aegis/src/audit.rs
@@ -0,0 +1,210 @@
+// spark-aegis Live System and Workspace Confinement Audit Engine
+// Inspects active listening sockets, workspace secrets, and host invariants
+
+use crate::mojo_bridge;
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SocketAudit {
+ pub protocol: String,
+ pub local_address: String,
+ pub is_loopback: bool,
+ pub process_name: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WorkspaceAudit {
+ pub path: PathBuf,
+ pub dot_env_found: Vec<PathBuf>,
+ pub exposed_keys_found: Vec<PathBuf>,
+ pub secure_tpm_only: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LiveAuditReport {
+ pub timestamp: DateTime<Utc>,
+ pub sockets: Vec<SocketAudit>,
+ pub non_loopback_sockets_count: usize,
+ pub workspace: WorkspaceAudit,
+ pub cortex_online: bool,
+ pub cortex_version: Option<String>,
+ pub mojo_simd_active: bool,
+ pub blake3_digest: String,
+ pub overall_safe: bool,
+}
+
+pub async fn audit_system() -> Result<LiveAuditReport> {
+ let ts = Utc::now();
+
+ // 1. Audit listening sockets
+ let sockets = audit_listening_sockets();
+ let non_loopback_count = sockets.iter().filter(|s| !s.is_loopback).count();
+
+ // 2. Audit workspace confinement
+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
+ let workspace_dir = PathBuf::from(home).join("workspace");
+ let workspace = audit_workspace_dir(&workspace_dir);
+
+ // 3. Audit Cortex memory engine
+ let (cortex_online, cortex_version) = check_cortex_health().await;
+
+ // 4. Audit Mojo SIMD acceleration
+ let mojo_simd_active = mojo_bridge::is_simd_accelerated();
+
+ // Overall safety: no plaintext secrets in workspace
+ let overall_safe = workspace.secure_tpm_only;
+
+ // Cryptographic hash of audit report
+ let digest_seed = format!(
+ "{}:{}:{}:{}:{}",
+ ts, non_loopback_count, workspace.secure_tpm_only, cortex_online, mojo_simd_active
+ );
+ let blake3_digest = blake3::hash(digest_seed.as_bytes()).to_hex().to_string();
+
+ Ok(LiveAuditReport {
+ timestamp: ts,
+ sockets,
+ non_loopback_sockets_count: non_loopback_count,
+ workspace,
+ cortex_online,
+ cortex_version,
+ mojo_simd_active,
+ blake3_digest,
+ overall_safe,
+ })
+}
+
+fn audit_listening_sockets() -> Vec<SocketAudit> {
+ let mut results = Vec::new();
+
+ // Try `ss -tulpn`
+ if let Ok(output) = Command::new("ss").args(["-tulpn"]).output() {
+ let text = String::from_utf8_lossy(&output.stdout);
+ for line in text.lines().skip(1) {
+ let parts: Vec<&str> = line.split_whitespace().collect();
+ if parts.len() >= 5 {
+ let proto = parts[0].to_string();
+ let addr_str = parts[4];
+ let is_loop = addr_str.starts_with("127.") || addr_str.starts_with("[::1]");
+ let proc_name = if parts.len() >= 7 {
+ Some(parts[6].to_string())
+ } else {
+ None
+ };
+
+ results.push(SocketAudit {
+ protocol: proto,
+ local_address: addr_str.to_string(),
+ is_loopback: is_loop,
+ process_name: proc_name,
+ });
+ }
+ }
+ }
+
+ results
+}
+
+fn audit_workspace_dir(dir: &Path) -> WorkspaceAudit {
+ let mut dot_envs = Vec::new();
+ let mut exposed_keys = Vec::new();
+
+ if dir.exists() && dir.is_dir() {
+ let mut stack = vec![dir.to_path_buf()];
+ let mut files_checked = 0;
+
+ while let Some(current) = stack.pop() {
+ if files_checked > 2000 {
+ break; // Boundary limit
+ }
+ if let Ok(entries) = fs::read_dir(¤t) {
+ for entry in entries.flatten() {
+ let p = entry.path();
+ let name = match p.file_name().and_then(|s| s.to_str()) {
+ Some(n) => n,
+ None => continue,
+ };
+
+ if name == ".git" || name == "target" || name == "node_modules" {
+ continue;
+ }
+
+ if p.is_dir() {
+ stack.push(p);
+ } else if p.is_file() {
+ files_checked += 1;
+ if name == ".env" || name.starts_with(".env.") {
+ dot_envs.push(p.clone());
+ }
+ if name.ends_with(".key") || name.ends_with(".pem") || name == "id_rsa" {
+ exposed_keys.push(p.clone());
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let secure_tpm_only = dot_envs.is_empty() && exposed_keys.is_empty();
+
+ WorkspaceAudit {
+ path: dir.to_path_buf(),
+ dot_env_found: dot_envs,
+ exposed_keys_found: exposed_keys,
+ secure_tpm_only,
+ }
+}
+
+async fn check_cortex_health() -> (bool, Option<String>) {
+ let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_millis(1500))
+ .build();
+
+ if let Ok(c) = client {
+ let cortex_url = std::env::var("CORTEX_HEALTH_URL")
+ .unwrap_or_else(|_| "http://127.0.0.1:18080/health".to_string());
+ if let Ok(resp) = c.get(&cortex_url).send().await {
+ if resp.status().is_success() {
+ if let Ok(json) = resp.json::<serde_json::Value>().await {
+ let ver = json
+ .get("version")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+ return (true, ver);
+ }
+ return (true, None);
+ }
+ }
+ }
+
+ (false, None)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_workspace_audit_empty_tmp() {
+ let tmp = tempfile::tempdir().unwrap();
+ let audit = audit_workspace_dir(tmp.path());
+ assert!(audit.secure_tpm_only);
+ assert!(audit.dot_env_found.is_empty());
+ }
+
+ #[test]
+ fn test_workspace_audit_flags_dotenv() {
+ let tmp = tempfile::tempdir().unwrap();
+ let env_file = tmp.path().join(".env");
+ fs::write(&env_file, b"SECRET=true").unwrap();
+
+ let audit = audit_workspace_dir(tmp.path());
+ assert!(!audit.secure_tpm_only);
+ assert_eq!(audit.dot_env_found.len(), 1);
+ }
+}
diff --git a/crates/spark-aegis/src/containment.rs b/crates/spark-aegis/src/containment.rs
new file mode 100644
index 00000000 ..4941b2e7
--- /dev/null
+++ b/crates/spark-aegis/src/containment.rs
@@ -0,0 +1,355 @@
+// spark-aegis Containment Engine
+// Executes sovereign defensive actions and commits Blake3 evidence to Cortex
+
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use reqwest::Client;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use std::fs;
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IncidentReport {
+ pub incident_id: String,
+ pub timestamp: DateTime<Utc>,
+ pub trigger: String,
+ pub severity: String,
+ pub details: serde_json::Value,
+ pub artifacts: Vec<String>,
+}
+
+impl IncidentReport {
+ pub fn new(
+ trigger: impl Into<String>,
+ severity: impl Into<String>,
+ details: serde_json::Value,
+ ) -> Self {
+ let trigger_str = trigger.into();
+ let severity_str = severity.into();
+ let ts = Utc::now();
+ let id_seed = format!(
+ "{}:{}:{}",
+ ts.timestamp_nanos_opt().unwrap_or(0),
+ trigger_str,
+ severity_str
+ );
+ let digest = blake3::hash(id_seed.as_bytes()).to_hex().to_string();
+ let short_id = &digest[..16];
+
+ Self {
+ incident_id: format!("inc-{}", short_id),
+ timestamp: ts,
+ trigger: trigger_str,
+ severity: severity_str,
+ details,
+ artifacts: Vec::new(),
+ }
+ }
+
+ pub fn compute_blake3(&self) -> String {
+ let serialized = serde_json::to_vec(self).unwrap_or_default();
+ blake3::hash(&serialized).to_hex().to_string()
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ContainmentReceipt {
+ pub action: String,
+ pub target: String,
+ pub status: String,
+ pub details: String,
+ pub blake3_digest: String,
+ pub timestamp: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AuditReceipt {
+ pub recorded: bool,
+ pub incident_id: String,
+ pub blake3_hash: String,
+ pub cortex_target_id: Option<String>,
+ pub committed_at: String,
+}
+
+fn load_cortex_token() -> String {
+ if let Ok(tok) = std::env::var("CORTEX_TOKEN") {
+ let trimmed = tok.trim();
+ if !trimmed.is_empty() {
+ return trimmed.to_string();
+ }
+ }
+
+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
+ let token_file = PathBuf::from(home).join(".config/cortex/token");
+ if token_file.exists() {
+ if let Ok(content) = fs::read_to_string(token_file) {
+ return content.trim().to_string();
+ }
+ }
+ String::new()
+}
+
+pub fn cut_session(session_id: &str) -> Result<ContainmentReceipt> {
+ let ts = Utc::now();
+ let details: String;
+ let status: String;
+
+ // Check if session_id is a numeric process ID
+ if let Ok(pid) = session_id.parse::<i32>() {
+ unsafe {
+ // SIGHUP = 1
+ let ret = libc::kill(pid, libc::SIGHUP);
+ if ret == 0 {
+ status = "SUCCESS".to_string();
+ details = format!("Dispatched SIGHUP to process session PID {}", pid);
+ } else {
+ let err = std::io::Error::last_os_error();
+ status = "FAILED".to_string();
+ details = format!("Failed to signal PID {}: {}", pid, err);
+ }
+ }
+ } else {
+ // Session ID string: terminate associated pts or logged session
+ status = "EXECUTED".to_string();
+ details = format!(
+ "Session identifier {} revoked and marked for termination",
+ session_id
+ );
+ }
+
+ let digest_payload = format!("{}:{}:{}:{}", ts, "CutSession", session_id, details);
+ let blake3_digest = blake3::hash(digest_payload.as_bytes()).to_hex().to_string();
+
+ Ok(ContainmentReceipt {
+ action: "CutSession".to_string(),
+ target: session_id.to_string(),
+ status,
+ details,
+ blake3_digest,
+ timestamp: ts,
+ })
+}
+
+pub fn isolate_host(process_id: u32) -> Result<ContainmentReceipt> {
+ let ts = Utc::now();
+ let pid = process_id as i32;
+ let status: String;
+ let details: String;
+
+ unsafe {
+ // SIGSTOP = 19 (suspends execution immediately for forensic quarantine)
+ let ret = libc::kill(pid, libc::SIGSTOP);
+ if ret == 0 {
+ status = "ISOLATED".to_string();
+ details = format!(
+ "Dispatched SIGSTOP to PID {}. Process execution suspended.",
+ pid
+ );
+ } else {
+ let err = std::io::Error::last_os_error();
+ // Try SIGTERM or report status
+ status = "SIGNAL_ERROR".to_string();
+ details = format!("Failed to deliver SIGSTOP to PID {}: {}", pid, err);
+ }
+ }
+
+ let digest_payload = format!("{}:{}:{}:{}", ts, "IsolateHost", process_id, details);
+ let blake3_digest = blake3::hash(digest_payload.as_bytes()).to_hex().to_string();
+
+ Ok(ContainmentReceipt {
+ action: "IsolateHost".to_string(),
+ target: process_id.to_string(),
+ status,
+ details,
+ blake3_digest,
+ timestamp: ts,
+ })
+}
+
+pub fn close_door(target_path: &Path) -> Result<ContainmentReceipt> {
+ let ts = Utc::now();
+ if !target_path.exists() {
+ anyhow::bail!("Target path {:?} does not exist", target_path);
+ }
+
+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
+ let quarantine_dir = PathBuf::from(home).join("workspace/.quarantine");
+ fs::create_dir_all(&quarantine_dir).context("Creating quarantine directory")?;
+
+ let file_name = target_path.file_name().unwrap_or_default();
+ let quarantine_target = quarantine_dir.join(format!(
+ "{}_{}",
+ ts.timestamp(),
+ file_name.to_string_lossy()
+ ));
+
+ // Move file to quarantine and strip all permissions (chmod 0000)
+ let details = if let Ok(()) = fs::rename(target_path, &quarantine_target) {
+ let _ = fs::set_permissions(&quarantine_target, fs::Permissions::from_mode(0o000));
+ format!("Moved target to quarantine at {:?}", quarantine_target)
+ } else {
+ // In-place permission revocation if move across filesystems fails
+ let _ = fs::set_permissions(target_path, fs::Permissions::from_mode(0o000));
+ format!(
+ "Revoked all read/write/execute permissions (0000) on {:?}",
+ target_path
+ )
+ };
+
+ let digest_payload = format!(
+ "{}:{}:{}:{}",
+ ts,
+ "CloseDoor",
+ target_path.display(),
+ details
+ );
+ let blake3_digest = blake3::hash(digest_payload.as_bytes()).to_hex().to_string();
+
+ Ok(ContainmentReceipt {
+ action: "CloseDoor".to_string(),
+ target: target_path.display().to_string(),
+ status: "CONTAINED".to_string(),
+ details,
+ blake3_digest,
+ timestamp: ts,
+ })
+}
+
+pub async fn keep_evidence(incident: &IncidentReport) -> Result<AuditReceipt> {
+ let blake3_hash = incident.compute_blake3();
+ let token = load_cortex_token();
+
+ let client = Client::builder().build()?;
+ let payload = json!({
+ "kind": "entity",
+ "value": {
+ "space": "atlas-memory",
+ "entityType": "discovery",
+ "canonicalName": format!("aegis_audit_{}", incident.incident_id),
+ "content": format!(
+ "Blake3: {}\nSeverity: {}\nTrigger: {}\nDetails: {}",
+ blake3_hash,
+ incident.severity,
+ incident.trigger,
+ serde_json::to_string_pretty(&incident.details).unwrap_or_default()
+ ),
+ "metadata": {
+ "blake3_hash": blake3_hash,
+ "incident_id": incident.incident_id,
+ "severity": incident.severity,
+ "trigger": incident.trigger,
+ "subsystem": "spark-aegis",
+ "timestamp": incident.timestamp.to_rfc3339()
+ }
+ }
+ });
+
+ let cortex_url = std::env::var("CORTEX_URL")
+ .unwrap_or_else(|_| "http://127.0.0.1:18080/api/cortex/write".to_string());
+
+ let mut request = client.post(&cortex_url).json(&payload);
+ if !token.is_empty() {
+ request = request.header("Authorization", format!("Bearer {}", token));
+ }
+
+ match request.send().await {
+ Ok(resp) if resp.status().is_success() => {
+ let resp_json: serde_json::Value = resp.json().await.unwrap_or(json!({}));
+ let target_id = resp_json
+ .get("receipt")
+ .and_then(|r| r.get("id"))
+ .and_then(|id| id.as_str())
+ .map(|s| s.to_string());
+
+ Ok(AuditReceipt {
+ recorded: true,
+ incident_id: incident.incident_id.clone(),
+ blake3_hash,
+ cortex_target_id: target_id,
+ committed_at: Utc::now().to_rfc3339(),
+ })
+ }
+ Ok(resp) => {
+ let status = resp.status();
+ let err_text = resp.text().await.unwrap_or_default();
+ // Fallback: persist offline audit record so evidence is never dropped
+ persist_offline_evidence(incident, &blake3_hash)?;
+ Ok(AuditReceipt {
+ recorded: false,
+ incident_id: incident.incident_id.clone(),
+ blake3_hash,
+ cortex_target_id: None,
+ committed_at: format!("Offline ledger (Cortex HTTP {} - {})", status, err_text),
+ })
+ }
+ Err(e) => {
+ // Cortex unreachable: persist offline audit record
+ persist_offline_evidence(incident, &blake3_hash)?;
+ Ok(AuditReceipt {
+ recorded: false,
+ incident_id: incident.incident_id.clone(),
+ blake3_hash,
+ cortex_target_id: None,
+ committed_at: format!("Offline ledger (Cortex connection failed: {})", e),
+ })
+ }
+ }
+}
+
+fn persist_offline_evidence(incident: &IncidentReport, blake3_hash: &str) -> Result<()> {
+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
+ let audit_dir = PathBuf::from(home).join(".config/cortex/offline_audit");
+ fs::create_dir_all(&audit_dir)?;
+
+ let file_path = audit_dir.join(format!("{}.json", incident.incident_id));
+ let offline_record = json!({
+ "incident": incident,
+ "blake3_hash": blake3_hash,
+ "recorded_offline_at": Utc::now().to_rfc3339()
+ });
+
+ fs::write(&file_path, serde_json::to_string_pretty(&offline_record)?)?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_incident_blake3_computation() {
+ let incident = IncidentReport::new("test_trigger", "HIGH", json!({"key": "value"}));
+ let hash = incident.compute_blake3();
+ assert_eq!(hash.len(), 64);
+ }
+
+ #[test]
+ fn test_close_door_quarantine() {
+ let tmp_dir = tempfile::tempdir().unwrap();
+ let target = tmp_dir.path().join("suspicious_binary.bin");
+ fs::write(&target, b"malicious payload").unwrap();
+
+ let receipt = close_door(&target).unwrap();
+ assert_eq!(receipt.action, "CloseDoor");
+ assert_eq!(receipt.status, "CONTAINED");
+ assert!(!target.exists());
+ }
+
+ #[test]
+ fn test_cut_session_generation() {
+ let receipt = cut_session("session_mock_42").unwrap();
+ assert_eq!(receipt.action, "CutSession");
+ assert_eq!(receipt.target, "session_mock_42");
+ assert_eq!(receipt.blake3_digest.len(), 64);
+ }
+
+ #[test]
+ fn test_isolate_host_generation() {
+ let receipt = isolate_host(999999).unwrap();
+ assert_eq!(receipt.action, "IsolateHost");
+ assert_eq!(receipt.target, "999999");
+ assert_eq!(receipt.blake3_digest.len(), 64);
+ }
+}
diff --git a/crates/spark-aegis/src/doctrine.rs b/crates/spark-aegis/src/doctrine.rs
new file mode 100644
index 00000000 ..2b16a6ab
--- /dev/null
+++ b/crates/spark-aegis/src/doctrine.rs
@@ -0,0 +1,164 @@
+// spark-aegis Sovereign Defensive Boundary and Containment Engine
+// Pure Native Rust Systems Architecture
+
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+pub const DOCTRINE_STATEMENT: &str =
+ "The network is the house. Cut the session. Isolate the host. Close the door. Keep the evidence.";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ContainmentActionKind {
+ CutSession,
+ IsolateHost,
+ CloseDoor,
+ KeepEvidence,
+}
+
+impl ContainmentActionKind {
+ pub fn name(&self) -> &'static str {
+ match self {
+ Self::CutSession => "CutSession",
+ Self::IsolateHost => "IsolateHost",
+ Self::CloseDoor => "CloseDoor",
+ Self::KeepEvidence => "KeepEvidence",
+ }
+ }
+
+ pub fn directive(&self) -> &'static str {
+ match self {
+ Self::CutSession => "Cut the session.",
+ Self::IsolateHost => "Isolate the host.",
+ Self::CloseDoor => "Close the door.",
+ Self::KeepEvidence => "Keep the evidence.",
+ }
+ }
+
+ pub fn description(&self) -> &'static str {
+ match self {
+ Self::CutSession => "Terminate active unauthorized interactive or socket sessions immediately.",
+ Self::IsolateHost => "Suspend, sever, and isolate compromised host processes from execution.",
+ Self::CloseDoor => "Quarantine filesystem targets and revoke all access permissions.",
+ Self::KeepEvidence => "Compute Blake3 cryptographic integrity hash and commit durable audit record to Cortex.",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum ContainmentAction {
+ CutSession {
+ session_id: String,
+ },
+ IsolateHost {
+ process_id: u32,
+ },
+ CloseDoor {
+ target_path: PathBuf,
+ },
+ KeepEvidence {
+ incident_id: String,
+ blake3_hash: String,
+ },
+}
+
+impl ContainmentAction {
+ pub fn kind(&self) -> ContainmentActionKind {
+ match self {
+ Self::CutSession { .. } => ContainmentActionKind::CutSession,
+ Self::IsolateHost { .. } => ContainmentActionKind::IsolateHost,
+ Self::CloseDoor { .. } => ContainmentActionKind::CloseDoor,
+ Self::KeepEvidence { .. } => ContainmentActionKind::KeepEvidence,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum AegisInvariant {
+ ZeroDiskSecrets,
+ SovereignVoice,
+ PureCompiledArchitecture,
+ ImmutableAuditTrail,
+}
+
+impl AegisInvariant {
+ pub fn code(&self) -> &'static str {
+ match self {
+ Self::ZeroDiskSecrets => "SECURE_TPM_ONLY",
+ Self::SovereignVoice => "UNSLOP_COMPLIANCE",
+ Self::PureCompiledArchitecture => "PURE_NATIVE_SYSTEMS",
+ Self::ImmutableAuditTrail => "BLAKE3_CORTEX_TRAIL",
+ }
+ }
+
+ pub fn description(&self) -> &'static str {
+ match self {
+ Self::ZeroDiskSecrets => {
+ "Plaintext secrets and .env files must never touch disk. All credentials must resolve via hardware TPM vault."
+ }
+ Self::SovereignVoice => {
+ "Strict zero em dash and en dash policy. Ban AI buzzwords, transitional filler, and antithesis tropes."
+ }
+ Self::PureCompiledArchitecture => {
+ "Core security and agent runtime engines must compile to native Rust and Mojo SIMD binaries."
+ }
+ Self::ImmutableAuditTrail => {
+ "Every defensive incident and PR audit must commit Blake3 cryptographic proof into Cortex memory."
+ }
+ }
+ }
+}
+
+pub fn all_invariants() -> &'static [AegisInvariant] {
+ &[
+ AegisInvariant::ZeroDiskSecrets,
+ AegisInvariant::SovereignVoice,
+ AegisInvariant::PureCompiledArchitecture,
+ AegisInvariant::ImmutableAuditTrail,
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_doctrine_statement() {
+ assert_eq!(
+ DOCTRINE_STATEMENT,
+ "The network is the house. Cut the session. Isolate the host. Close the door. Keep the evidence."
+ );
+ }
+
+ #[test]
+ fn test_containment_action_kinds() {
+ let action = ContainmentAction::CutSession {
+ session_id: "test-session-42".to_string(),
+ };
+ assert_eq!(action.kind(), ContainmentActionKind::CutSession);
+ assert_eq!(action.kind().directive(), "Cut the session.");
+
+ let isolate = ContainmentAction::IsolateHost { process_id: 1234 };
+ assert_eq!(isolate.kind(), ContainmentActionKind::IsolateHost);
+ assert_eq!(isolate.kind().directive(), "Isolate the host.");
+
+ let door = ContainmentAction::CloseDoor {
+ target_path: PathBuf::from("/tmp/badfile"),
+ };
+ assert_eq!(door.kind(), ContainmentActionKind::CloseDoor);
+ assert_eq!(door.kind().directive(), "Close the door.");
+
+ let ev = ContainmentAction::KeepEvidence {
+ incident_id: "inc-1".to_string(),
+ blake3_hash: "abcd".to_string(),
+ };
+ assert_eq!(ev.kind(), ContainmentActionKind::KeepEvidence);
+ assert_eq!(ev.kind().directive(), "Keep the evidence.");
+ }
+
+ #[test]
+ fn test_all_invariants_present() {
+ let inv = all_invariants();
+ assert_eq!(inv.len(), 4);
+ assert_eq!(inv[0].code(), "SECURE_TPM_ONLY");
+ }
+}
diff --git a/crates/spark-aegis/src/lib.rs b/crates/spark-aegis/src/lib.rs
new file mode 100644
index 00000000 ..0c52c55b
--- /dev/null
+++ b/crates/spark-aegis/src/lib.rs
@@ -0,0 +1,13 @@
+// spark-aegis: Sovereign Defensive Boundary and Containment Engine
+// Pure Native Rust Systems Architecture with Mojo SIMD Acceleration
+
+pub mod audit;
+pub mod containment;
+pub mod doctrine;
+pub mod mojo_bridge;
+pub mod pr_triage;
+pub mod scanner;
+
+pub use doctrine::{
+ all_invariants, AegisInvariant, ContainmentAction, ContainmentActionKind, DOCTRINE_STATEMENT,
+};
diff --git a/crates/spark-aegis/src/main.rs b/crates/spark-aegis/src/main.rs
new file mode 100644
index 00000000 ..ce25a79c
--- /dev/null
+++ b/crates/spark-aegis/src/main.rs
@@ -0,0 +1,359 @@
+// spark-aegis CLI Entrypoint
+// Sovereign Defensive Boundary and Containment Engine
+
+use anyhow::Result;
+use clap::{Parser, Subcommand};
+use serde_json::json;
+use spark_aegis::{
+ audit, containment,
+ doctrine::{all_invariants, DOCTRINE_STATEMENT},
+ mojo_bridge, pr_triage, scanner,
+};
+use std::path::{Path, PathBuf};
+
+#[derive(Parser)]
+#[command(
+ name = "spark-aegis",
+ about = "Sovereign defensive boundary and containment engine",
+ version = "0.1.0"
+)]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Deep scan a file or directory for secrets, slop, and dangerous commands
+ Scan {
+ /// Target file or directory path
+ path: PathBuf,
+ },
+ /// Autonomous PR review and diff triage
+ ReviewPr {
+ /// Path to diff file (or - for stdin)
+ diff_file: PathBuf,
+ },
+ /// Live system and workspace confinement audit
+ Audit,
+ /// Execute defensive containment actions on session, process, or path
+ Contain {
+ /// Target identifier (process ID, session ID, or filesystem path)
+ target: String,
+ /// Explicitly treat target as a process ID to isolate
+ #[arg(long)]
+ pid: Option<u32>,
+ /// Explicitly treat target as a session ID to cut
+ #[arg(long)]
+ session: Option<String>,
+ /// Explicitly treat target as a filesystem path to close and quarantine
+ #[arg(long)]
+ close: Option<PathBuf>,
+ },
+ /// Display sovereign doctrine and invariant definitions
+ Doctrine,
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let cli = Cli::parse();
+
+ match cli.command {
+ Commands::Scan { path } => {
+ println!("SPARK-AEGIS DEEP SCAN");
+ println!("Target: {}", path.display());
+ println!("Engine: {}", mojo_bridge::engine_name());
+ println!("------------------------------------------------------------");
+
+ let report = scanner::scan_path(&path)?;
+ println!("Files scanned: {}", report.scanned_files_count);
+ println!("Duration: {:.2} ms", report.elapsed_ms);
+ println!("Blake3 hash: {}", report.blake3_hash);
+ println!(
+ "Status: {}",
+ if report.passed {
+ "CLEAN"
+ } else {
+ "VIOLATIONS_FOUND"
+ }
+ );
+
+ if !report.violations.is_empty() {
+ println!("\nVIOLATION REPORT ({} items):", report.violations.len());
+ for (idx, v) in report.violations.iter().enumerate() {
+ println!("\n[{}] {:?} ({:?})", idx + 1, v.rule, v.severity);
+ println!(" Path: {}", v.file_path.display());
+ if let Some(line) = v.line_number {
+ println!(" Line: {}", line);
+ }
+ println!(" Match: {}", v.matched_text);
+ println!(" Remediation: {}", v.remediation);
+ }
+ std::process::exit(1);
+ } else {
+ println!("\nZero violations detected. Target conforms to sovereign invariants.");
+ }
+ }
+
+ Commands::ReviewPr { diff_file } => {
+ println!("SPARK-AEGIS AUTONOMOUS PR TRIAGE");
+ println!("Engine: {}", mojo_bridge::engine_name());
+ println!("------------------------------------------------------------");
+
+ let content = if diff_file == Path::new("-") {
+ use std::io::Read;
+ let mut buffer = String::new();
+ std::io::stdin().read_to_string(&mut buffer)?;
+ buffer
+ } else {
+ std::fs::read_to_string(&diff_file)?
+ };
+
+ let pr_name = diff_file.display().to_string();
+ let verdict = pr_triage::review_pr_diff(&content, &pr_name)?;
+
+ println!("PR Identifier: {}", verdict.pr_id);
+ println!("Blake3 Proof: {}", verdict.blake3_proof);
+ println!("Status: {:?}", verdict.status);
+ println!(
+ "Zero Disk Secrets: {}",
+ if verdict.zero_disk_secrets_certified {
+ "CERTIFIED"
+ } else {
+ "FAILED"
+ }
+ );
+ println!(
+ "Unslop Compliance: {}",
+ if verdict.unslop_certified {
+ "CERTIFIED"
+ } else {
+ "FAILED"
+ }
+ );
+ println!(
+ "Safe Execution: {}",
+ if verdict.safe_execution_certified {
+ "CERTIFIED"
+ } else {
+ "FAILED"
+ }
+ );
+ println!("Summary: {}", verdict.summary);
+
+ if !verdict.violations.is_empty() {
+ println!("\nViolations List:");
+ for (i, v) in verdict.violations.iter().enumerate() {
+ println!(
+ " {}. [{:?}] {} at line {:?}",
+ i + 1,
+ v.category,
+ v.rule,
+ v.line_number
+ );
+ println!(" Remediation: {}", v.remediation);
+ }
+ std::process::exit(1);
+ }
+ }
+
+ Commands::Audit => {
+ println!("SPARK-AEGIS LIVE HOST & WORKSPACE CONFINEMENT AUDIT");
+ println!("Engine: {}", mojo_bridge::engine_name());
+ println!("------------------------------------------------------------");
+
+ let report = audit::audit_system().await?;
+ println!("Timestamp: {}", report.timestamp.to_rfc3339());
+ println!("Blake3 Audit Digest: {}", report.blake3_digest);
+ println!(
+ "Cortex Memory Service: {}",
+ if report.cortex_online {
+ "ONLINE"
+ } else {
+ "OFFLINE"
+ }
+ );
+ if let Some(v) = report.cortex_version {
+ println!("Cortex Engine Version: {}", v);
+ }
+ println!(
+ "Mojo SIMD Hardware: {}",
+ if report.mojo_simd_active {
+ "ACTIVE"
+ } else {
+ "STANDBY"
+ }
+ );
+ println!(
+ "Workspace Path: {}",
+ report.workspace.path.display()
+ );
+ println!(
+ "Workspace Status: {}",
+ if report.workspace.secure_tpm_only {
+ "SECURE_TPM_ONLY (PASS)"
+ } else {
+ "FAILED (INSECURE)"
+ }
+ );
+
+ if !report.workspace.dot_env_found.is_empty() {
+ println!("\nWARNING: Unencrypted .env files detected:");
+ for p in &report.workspace.dot_env_found {
+ println!(" - {}", p.display());
+ }
+ }
+
+ println!("\nListening Sockets Count: {}", report.sockets.len());
+ println!(
+ "Non-Loopback Sockets: {}",
+ report.non_loopback_sockets_count
+ );
+ for s in report.sockets.iter().take(10) {
+ let exposure = if s.is_loopback {
+ "LOOPBACK"
+ } else {
+ "EXPOSED_LAN/WAN"
+ };
+ println!(
+ " {} {:<25} [{}] proc: {:?}",
+ s.protocol, s.local_address, exposure, s.process_name
+ );
+ }
+
+ println!(
+ "\nOverall Confinement: {}",
+ if report.overall_safe {
+ "PASS"
+ } else {
+ "REJECT"
+ }
+ );
+ }
+
+ Commands::Contain {
+ target,
+ pid,
+ session,
+ close,
+ } => {
+ println!("SPARK-AEGIS CONTAINMENT DISPATCH");
+ println!("Doctrine: {}", DOCTRINE_STATEMENT);
+ println!("------------------------------------------------------------");
+
+ if let Some(target_pid) = pid {
+ let receipt = containment::isolate_host(target_pid)?;
+ println!("Action: {}", receipt.action);
+ println!("Target: PID {}", receipt.target);
+ println!("Status: {}", receipt.status);
+ println!("Details: {}", receipt.details);
+ println!("Blake3: {}", receipt.blake3_digest);
+
+ let incident = containment::IncidentReport::new(
+ "manual_pid_containment",
+ "HIGH",
+ json!({"pid": target_pid, "receipt": receipt}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await?;
+ println!("Evidence: Cortex recorded: {}", audit_receipt.recorded);
+ return Ok(());
+ }
+
+ if let Some(sess_id) = session {
+ let receipt = containment::cut_session(&sess_id)?;
+ println!("Action: {}", receipt.action);
+ println!("Target: Session {}", receipt.target);
+ println!("Status: {}", receipt.status);
+ println!("Details: {}", receipt.details);
+ println!("Blake3: {}", receipt.blake3_digest);
+
+ let incident = containment::IncidentReport::new(
+ "manual_session_containment",
+ "HIGH",
+ json!({"session": sess_id, "receipt": receipt}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await?;
+ println!("Evidence: Cortex recorded: {}", audit_receipt.recorded);
+ return Ok(());
+ }
+
+ if let Some(close_path) = close {
+ let receipt = containment::close_door(&close_path)?;
+ println!("Action: {}", receipt.action);
+ println!("Target: Path {}", receipt.target);
+ println!("Status: {}", receipt.status);
+ println!("Details: {}", receipt.details);
+ println!("Blake3: {}", receipt.blake3_digest);
+
+ let incident = containment::IncidentReport::new(
+ "manual_path_containment",
+ "HIGH",
+ json!({"path": close_path, "receipt": receipt}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await?;
+ println!("Evidence: Cortex recorded: {}", audit_receipt.recorded);
+ return Ok(());
+ }
+
+ // Automatic target deduction: numeric PID, path, or session string
+ if let Ok(parsed_pid) = target.parse::<u32>() {
+ println!("Auto-detected numeric PID target: {}", parsed_pid);
+ let receipt = containment::isolate_host(parsed_pid)?;
+ println!("Status: {}", receipt.status);
+ println!("Details: {}", receipt.details);
+ println!("Blake3: {}", receipt.blake3_digest);
+
+ let incident = containment::IncidentReport::new(
+ "auto_pid_containment",
+ "HIGH",
+ json!({"pid": parsed_pid, "receipt": receipt}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await?;
+ println!("Evidence: Cortex recorded: {}", audit_receipt.recorded);
+ } else if Path::new(&target).exists() {
+ println!("Auto-detected filesystem target: {}", target);
+ let receipt = containment::close_door(Path::new(&target))?;
+ println!("Status: {}", receipt.status);
+ println!("Details: {}", receipt.details);
+ println!("Blake3: {}", receipt.blake3_digest);
+
+ let incident = containment::IncidentReport::new(
+ "auto_path_containment",
+ "HIGH",
+ json!({"path": target, "receipt": receipt}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await?;
+ println!("Evidence: Cortex recorded: {}", audit_receipt.recorded);
+ } else {
+ println!(
+ "Auto-detected interactive/socket session target: {}",
+ target
+ );
+ let receipt = containment::cut_session(&target)?;
+ println!("Status: {}", receipt.status);
+ println!("Details: {}", receipt.details);
+ println!("Blake3: {}", receipt.blake3_digest);
+
+ let incident = containment::IncidentReport::new(
+ "auto_session_containment",
+ "HIGH",
+ json!({"session": target, "receipt": receipt}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await?;
+ println!("Evidence: Cortex recorded: {}", audit_receipt.recorded);
+ }
+ }
+
+ Commands::Doctrine => {
+ println!("SPARK-AEGIS SOVEREIGN DEFENSIVE DOCTRINE");
+ println!("============================================================");
+ println!("Doctrine: \"{}\"\n", DOCTRINE_STATEMENT);
+ println!("Invariants:");
+ for inv in all_invariants() {
+ println!("- [{}] {}", inv.code(), inv.description());
+ }
+ }
+ }
+
+ Ok(())
+}
diff --git a/crates/spark-aegis/src/mojo_bridge.rs b/crates/spark-aegis/src/mojo_bridge.rs
new file mode 100644
index 00000000 ..bff23560
--- /dev/null
+++ b/crates/spark-aegis/src/mojo_bridge.rs
@@ -0,0 +1,179 @@
+// spark-aegis Mojo SIMD Dynamic Bridge
+// Pure compiled C-ABI dynamic bridge with pure Rust fallback
+
+use libloading::{Library, Symbol};
+use std::path::{Path, PathBuf};
+use std::sync::OnceLock;
+
+type FnVersion = unsafe extern "C" fn() -> i32;
+type FnScanByte = unsafe extern "C" fn(*const u8, usize, u8) -> isize;
+type FnCountMatches = unsafe extern "C" fn(*const u8, usize, u8) -> isize;
+type FnFindPattern = unsafe extern "C" fn(*const u8, usize, *const u8, usize) -> isize;
+
+pub struct MojoBindings {
+ _lib: Library,
+ pub version: FnVersion,
+ pub scan_byte: FnScanByte,
+ pub count_matches: FnCountMatches,
+ pub find_pattern: FnFindPattern,
+}
+
+static BINDINGS: OnceLock<Option<MojoBindings>> = OnceLock::new();
+
+pub fn default_so_path() -> PathBuf {
+ if let Ok(p) = std::env::var("SPARK_AEGIS_SO_PATH") {
+ let pb = PathBuf::from(p);
+ if pb.exists() {
+ return pb;
+ }
+ }
+ if let Some(p) = option_env!("SPARK_AEGIS_SO_BUILT") {
+ let pb = PathBuf::from(p);
+ if pb.exists() {
+ return pb;
+ }
+ }
+ let local = PathBuf::from("mojo/libsimd_matcher.so");
+ if local.exists() {
+ return local;
+ }
+ let local_crates = PathBuf::from("crates/spark-aegis/mojo/libsimd_matcher.so");
+ if local_crates.exists() {
+ return local_crates;
+ }
+ let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
+ let candidate = PathBuf::from(home).join("workspace/spark-aegis/mojo/libsimd_matcher.so");
+ if candidate.exists() {
+ return candidate;
+ }
+ PathBuf::from("mojo/libsimd_matcher.so")
+}
+
+impl MojoBindings {
+ pub fn load_from<P: AsRef<Path>>(path: P) -> Result<Self, String> {
+ let p = path.as_ref();
+ if !p.exists() {
+ return Err(format!("Shared library not found at {:?}", p));
+ }
+ unsafe {
+ let lib = Library::new(p).map_err(|e| format!("Failed to dlopen {:?}: {}", p, e))?;
+ let version: Symbol<FnVersion> = lib
+ .get(b"mojo_simd_version\0")
+ .map_err(|e| format!("Symbol mojo_simd_version not found: {}", e))?;
+ let scan_byte: Symbol<FnScanByte> = lib
+ .get(b"mojo_simd_scan_byte\0")
+ .map_err(|e| format!("Symbol mojo_simd_scan_byte not found: {}", e))?;
+ let count_matches: Symbol<FnCountMatches> = lib
+ .get(b"mojo_simd_count_matches\0")
+ .map_err(|e| format!("Symbol mojo_simd_count_matches not found: {}", e))?;
+ let find_pattern: Symbol<FnFindPattern> = lib
+ .get(b"mojo_simd_find_pattern\0")
+ .map_err(|e| format!("Symbol mojo_simd_find_pattern not found: {}", e))?;
+
+ Ok(Self {
+ version: *version,
+ scan_byte: *scan_byte,
+ count_matches: *count_matches,
+ find_pattern: *find_pattern,
+ _lib: lib,
+ })
+ }
+ }
+
+ pub fn global() -> Option<&'static Self> {
+ BINDINGS
+ .get_or_init(|| {
+ let path = default_so_path();
+ MojoBindings::load_from(path).ok()
+ })
+ .as_ref()
+ }
+}
+
+pub fn scan_byte(data: &[u8], target: u8) -> Option<usize> {
+ if let Some(bindings) = MojoBindings::global() {
+ let idx = unsafe { (bindings.scan_byte)(data.as_ptr(), data.len(), target) };
+ if idx >= 0 {
+ return Some(idx as usize);
+ }
+ return None;
+ }
+ // Pure Rust fallback
+ data.iter().position(|&b| b == target)
+}
+
+pub fn count_byte_matches(data: &[u8], target: u8) -> usize {
+ if let Some(bindings) = MojoBindings::global() {
+ let count = unsafe { (bindings.count_matches)(data.as_ptr(), data.len(), target) };
+ if count >= 0 {
+ return count as usize;
+ }
+ }
+ // Pure Rust fallback
+ data.iter().filter(|&&b| b == target).count()
+}
+
+pub fn find_pattern(data: &[u8], pattern: &[u8]) -> Option<usize> {
+ if pattern.is_empty() {
+ return Some(0);
+ }
+ if data.len() < pattern.len() {
+ return None;
+ }
+ if let Some(bindings) = MojoBindings::global() {
+ let idx = unsafe {
+ (bindings.find_pattern)(data.as_ptr(), data.len(), pattern.as_ptr(), pattern.len())
+ };
+ if idx >= 0 {
+ return Some(idx as usize);
+ }
+ return None;
+ }
+ // Pure Rust fallback
+ data.windows(pattern.len())
+ .position(|window| window == pattern)
+}
+
+pub fn is_simd_accelerated() -> bool {
+ MojoBindings::global().is_some()
+}
+
+pub fn engine_name() -> &'static str {
+ if is_simd_accelerated() {
+ "Mojo SIMD Hardware Acceleration"
+ } else {
+ "Pure Rust Compiled Fallback"
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_byte_scan_and_pattern_search() {
+ let buffer = b"SOVEREIGN_SYSTEMS_SPARK_AEGIS_SCAN";
+ let target = b'P';
+ let found = scan_byte(buffer, target);
+ assert_eq!(found, Some(19));
+
+ let not_found = scan_byte(buffer, b'Z');
+ assert_eq!(not_found, None);
+
+ let pattern = b"SPARK_AEGIS";
+ let pat_idx = find_pattern(buffer, pattern);
+ assert_eq!(pat_idx, Some(18));
+
+ let missing_pat = b"NONEXISTENT";
+ assert_eq!(find_pattern(buffer, missing_pat), None);
+
+ let count_s = count_byte_matches(buffer, b'S');
+ assert_eq!(count_s, 7);
+ }
+
+ #[test]
+ fn test_engine_reporting() {
+ let name = engine_name();
+ assert!(!name.is_empty());
+ }
+}
diff --git a/crates/spark-aegis/src/pr_triage.rs b/crates/spark-aegis/src/pr_triage.rs
new file mode 100644
index 00000000 ..801f7edc
--- /dev/null
+++ b/crates/spark-aegis/src/pr_triage.rs
@@ -0,0 +1,142 @@
+// spark-aegis PR Triage and Autonomous Review Engine
+// Verifies git diffs against sovereign invariants and certifies PR safety
+
+use crate::scanner::{self, Violation, ViolationCategory};
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::Path;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum VerdictStatus {
+ PASS,
+ REJECT,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PrVerdict {
+ pub status: VerdictStatus,
+ pub pr_id: String,
+ pub blake3_proof: String,
+ pub zero_disk_secrets_certified: bool,
+ pub unslop_certified: bool,
+ pub safe_execution_certified: bool,
+ pub violations: Vec<Violation>,
+ pub summary: String,
+ pub timestamp: DateTime<Utc>,
+}
+
+impl PrVerdict {
+ pub fn is_pass(&self) -> bool {
+ self.status == VerdictStatus::PASS
+ }
+}
+
+pub fn review_pr_diff(diff_content: &str, pr_identifier: &str) -> Result<PrVerdict> {
+ let report = scanner::scan_diff(diff_content)?;
+ let ts = Utc::now();
+
+ let mut secrets_clean = true;
+ let mut slop_clean = true;
+ let mut safe_clean = true;
+
+ for v in &report.violations {
+ match v.category {
+ ViolationCategory::PlaintextSecret | ViolationCategory::ProhibitedFile => {
+ secrets_clean = false;
+ }
+ ViolationCategory::AntiSlop => {
+ slop_clean = false;
+ }
+ ViolationCategory::DangerousCommand => {
+ safe_clean = false;
+ }
+ }
+ }
+
+ let passed = secrets_clean && slop_clean && safe_clean;
+ let status = if passed {
+ VerdictStatus::PASS
+ } else {
+ VerdictStatus::REJECT
+ };
+
+ let summary = if passed {
+ format!(
+ "PR {} certified safe. Zero disk secrets, unslop compliant, safe execution verified.",
+ pr_identifier
+ )
+ } else {
+ format!(
+ "PR {} REJECTED with {} sovereign violation(s). Remediation required before merge.",
+ pr_identifier,
+ report.violations.len()
+ )
+ };
+
+ Ok(PrVerdict {
+ status,
+ pr_id: pr_identifier.to_string(),
+ blake3_proof: report.blake3_hash,
+ zero_disk_secrets_certified: secrets_clean,
+ unslop_certified: slop_clean,
+ safe_execution_certified: safe_clean,
+ violations: report.violations,
+ summary,
+ timestamp: ts,
+ })
+}
+
+pub fn review_pr_file<P: AsRef<Path>>(file_path: P) -> Result<PrVerdict> {
+ let path = file_path.as_ref();
+ let content = fs::read_to_string(path)?;
+ let identifier = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("pr-diff");
+ review_pr_diff(&content, identifier)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_clean_pr_diff_passes() {
+ let clean_diff = r#"
+diff --git a/crates/spark-test/src/lib.rs b/crates/spark-test/src/lib.rs
+index 1111111 ..2222222 100644
+--- a/crates/spark-test/src/lib.rs
++++ b/crates/spark-test/src/lib.rs
+@@ -1,3 +1,4 @@
+ pub fn compute(x: i32) -> i32 {
++ x * 2
+ }
+"#;
+ let verdict = review_pr_diff(clean_diff, "PR-101").unwrap();
+ assert_eq!(verdict.status, VerdictStatus::PASS);
+ assert!(verdict.zero_disk_secrets_certified);
+ assert!(verdict.unslop_certified);
+ assert!(verdict.safe_execution_certified);
+ assert!(verdict.violations.is_empty());
+ }
+
+ #[test]
+ fn test_slop_pr_diff_rejects() {
+ let bad_diff =
+ "+++ b/README.md\n+This tool elevates developer productivity \u{2014} guaranteed.\n";
+ let verdict = review_pr_diff(bad_diff, "PR-102").unwrap();
+ assert_eq!(verdict.status, VerdictStatus::REJECT);
+ assert!(!verdict.unslop_certified);
+ assert_eq!(verdict.violations.len(), 2); // "elevates" and em dash
+ }
+
+ #[test]
+ fn test_secret_pr_diff_rejects() {
+ let secret_diff = "+++ b/config.rs\n+const GITHUB_TOKEN: &str = \"ghp_123456789012345678901234567890123456 \";\n";
+ let verdict = review_pr_diff(secret_diff, "PR-103").unwrap();
+ assert_eq!(verdict.status, VerdictStatus::REJECT);
+ assert!(!verdict.zero_disk_secrets_certified);
+ }
+}
diff --git a/crates/spark-aegis/src/scanner.rs b/crates/spark-aegis/src/scanner.rs
new file mode 100644
index 00000000 ..9a9d8650
--- /dev/null
+++ b/crates/spark-aegis/src/scanner.rs
@@ -0,0 +1,470 @@
+// spark-aegis Deep Scanner
+// Scans files, directories, and git diffs for secrets, slop, and dangerous commands
+
+use crate::mojo_bridge;
+use anyhow::Result;
+use regex::Regex;
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::sync::LazyLock;
+use std::time::Instant;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ViolationCategory {
+ PlaintextSecret,
+ AntiSlop,
+ DangerousCommand,
+ ProhibitedFile,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ViolationSeverity {
+ Critical,
+ High,
+ Medium,
+ Low,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Violation {
+ pub category: ViolationCategory,
+ pub severity: ViolationSeverity,
+ pub rule: String,
+ pub file_path: PathBuf,
+ pub line_number: Option<usize>,
+ pub column: Option<usize>,
+ pub matched_text: String,
+ pub remediation: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ScanReport {
+ pub target: String,
+ pub scanned_files_count: usize,
+ pub violations: Vec<Violation>,
+ pub passed: bool,
+ pub blake3_hash: String,
+ pub elapsed_ms: f64,
+}
+
+struct SecretRule {
+ name: &'static str,
+ regex: LazyLock<Regex>,
+ severity: ViolationSeverity,
+ remediation: &'static str,
+}
+
+struct SlopRule {
+ name: &'static str,
+ regex: LazyLock<Regex>,
+ remediation: &'static str,
+}
+
+struct DangerousCommandRule {
+ name: &'static str,
+ regex: LazyLock<Regex>,
+ severity: ViolationSeverity,
+ remediation: &'static str,
+}
+
+static SECRET_RULES: LazyLock<Vec<SecretRule>> = LazyLock::new(|| {
+ vec![
+ SecretRule {
+ name: "AWS Access Key ID",
+ regex: LazyLock::new(|| Regex::new(r"\bAKIA[0-9A-Z]{16}\b").unwrap()),
+ severity: ViolationSeverity::Critical,
+ remediation: "Store AWS credentials in the hardware TPM key vault.",
+ },
+ SecretRule {
+ name: "GitHub Personal Access Token",
+ regex: LazyLock::new(|| {
+ Regex::new(r"\b(?:ghp|gho|ghu|ghs|ghr)_[0-9a-zA-Z]{36}\b|\bgithub_pat_[0-9a-zA-Z_]{22,82}\b").unwrap()
+ }),
+ severity: ViolationSeverity::Critical,
+ remediation: "Store GitHub token in the hardware TPM vault (atlas-vault add).",
+ },
+ SecretRule {
+ name: "Slack Token",
+ regex: LazyLock::new(|| Regex::new(r"\bxox[baprs]-[0-9a-zA-Z]{10,48}\b").unwrap()),
+ severity: ViolationSeverity::Critical,
+ remediation: "Store Slack token in the hardware TPM vault.",
+ },
+ SecretRule {
+ name: "Private Key Header",
+ regex: LazyLock::new(|| {
+ Regex::new(
+ r"-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----",
+ )
+ .unwrap()
+ }),
+ severity: ViolationSeverity::Critical,
+ remediation: "Remove private key from filesystem. Use TPM-bound keys.",
+ },
+ SecretRule {
+ name: "Generic Hardcoded Secret Assignment",
+ regex: LazyLock::new(|| {
+ Regex::new(r#"(?i)\b(?:api[_-]?key|secret[_-]?key|auth[_-]?token|access[_-]?token)\s*[:=]\s*['"][0-9a-zA-Z_\-]{16,}['"]"#).unwrap()
+ }),
+ severity: ViolationSeverity::High,
+ remediation: "Resolve secret dynamically in memory via atlas-vault get.",
+ },
+ ]
+});
+
+static SLOP_RULES: LazyLock<Vec<SlopRule>> = LazyLock::new(|| {
+ vec![
+ SlopRule {
+ name: "Forbidden Em Dash",
+ regex: LazyLock::new(|| Regex::new("\u{2014}").unwrap()),
+ remediation: "Replace em dash with comma, colon, parentheses, or period.",
+ },
+ SlopRule {
+ name: "Forbidden En Dash",
+ regex: LazyLock::new(|| Regex::new("\u{2013}").unwrap()),
+ remediation: "Replace en dash with hyphen or rewrite clause.",
+ },
+ SlopRule {
+ name: "Banned AI Buzzword",
+ regex: LazyLock::new(|| {
+ Regex::new(r"(?i)\b(delve[a-z]*|tapestr[a-z]*|testament[a-z]*|beacon[a-z]*|crucial[a-z]*|pivotal[a-z]*|elevat[a-z]+|game-changer|unleash[a-z]*|harness[a-z]*|seamless[a-z]*)\b").unwrap()
+ }),
+ remediation: "Remove banned AI cliché. State technical facts directly.",
+ },
+ SlopRule {
+ name: "Banned Transitional Fluff",
+ regex: LazyLock::new(|| {
+ Regex::new(r"(?i)\b(furthermore|moreover|in conclusion|at its core)\b").unwrap()
+ }),
+ remediation: "Omit transitional filler. Lead immediately with evidence or code.",
+ },
+ SlopRule {
+ name: "Banned Antithesis Trope",
+ regex: LazyLock::new(|| {
+ Regex::new(r"(?i)\b(?:not only\b[^\n.!?]{1,60}\bbut also|it's not\b[^\n.!?]{1,60}\bit's)\b").unwrap()
+ }),
+ remediation: "Omit rhetorical antithesis trope. State facts directly.",
+ },
+ ]
+});
+
+static DANGEROUS_COMMAND_RULES: LazyLock<Vec<DangerousCommandRule>> = LazyLock::new(|| {
+ vec![
+ DangerousCommandRule {
+ name: "Destructive Root Filesystem Removal",
+ regex: LazyLock::new(|| {
+ Regex::new(r#"rm\s+-(?:[a-zA-Z]*r[a-zA-Z]*f|[a-zA-Z]*f[a-zA-Z]*r)\s+(?:/|/\*|~|~/\*)(?:\s|$)"#).unwrap()
+ }),
+ severity: ViolationSeverity::Critical,
+ remediation: "Command removes root or home directory. Abort immediately.",
+ },
+ DangerousCommandRule {
+ name: "Unsandboxed Pipe to Shell",
+ regex: LazyLock::new(|| {
+ Regex::new(r#"(?:curl|wget)\s+[^|\n]+?\|\s*(?:ba)?sh\b"#).unwrap()
+ }),
+ severity: ViolationSeverity::High,
+ remediation: "Download file, inspect Blake3 checksum, and execute in isolation.",
+ },
+ DangerousCommandRule {
+ name: "Fork Bomb Pattern",
+ regex: LazyLock::new(|| Regex::new(r#":\(\)\s*\{\s*:\|:&\s*\};:"#).unwrap()),
+ severity: ViolationSeverity::Critical,
+ remediation: "Malicious fork bomb detected. Isolate process immediately.",
+ },
+ DangerousCommandRule {
+ name: "Unrestricted Global Permissions",
+ regex: LazyLock::new(|| {
+ Regex::new(r#"chmod\s+(?:-R\s+)?777\s+(?:/|~)(?:\s|$)"#).unwrap()
+ }),
+ severity: ViolationSeverity::Critical,
+ remediation: "Do not apply 777 permissions to root or home directory.",
+ },
+ DangerousCommandRule {
+ name: "Raw Sudo Command in Script",
+ regex: LazyLock::new(|| {
+ Regex::new(r#"(?m)^\s*sudo\s+(?:rm|chmod|chown|dd|mkfs)\b"#).unwrap()
+ }),
+ severity: ViolationSeverity::High,
+ remediation: "Explicit privilege escalation requires audited sandbox confinement.",
+ },
+ ]
+});
+
+pub fn is_prohibited_filename(path: &Path) -> Option<(&'static str, &'static str)> {
+ if let Some(file_name) = path.file_name().and_then(|f| f.to_str()) {
+ if file_name == ".env" || file_name.starts_with(".env.") {
+ return Some((
+ "Plaintext .env Environment File",
+ "Zero Disk Secrets invariant violated. Remove .env and use hardware TPM vault.",
+ ));
+ }
+ if file_name.ends_with(".pem") || file_name.ends_with(".key") {
+ return Some((
+ "Unencrypted Private Key File",
+ "Zero Disk Secrets invariant violated. Store keys in TPM vault.",
+ ));
+ }
+ if file_name == "id_rsa" || file_name == "id_ed25519 " || file_name == "id_ecdsa" {
+ return Some((
+ "Raw SSH Private Key in Workspace",
+ "Move SSH keys to ~/.ssh or hardware security token.",
+ ));
+ }
+ }
+ None
+}
+
+pub fn scan_content(path: &Path, content: &str) -> Vec<Violation> {
+ let mut violations = Vec::new();
+
+ // Check prohibited filename
+ if let Some((rule, remediation)) = is_prohibited_filename(path) {
+ violations.push(Violation {
+ category: ViolationCategory::ProhibitedFile,
+ severity: ViolationSeverity::Critical,
+ rule: rule.to_string(),
+ file_path: path.to_path_buf(),
+ line_number: None,
+ column: None,
+ matched_text: path.display().to_string(),
+ remediation: remediation.to_string(),
+ });
+ }
+
+ // Fast check for em and en dashes using Mojo SIMD accelerated byte scanner if available
+ let bytes = content.as_bytes();
+ // Em dash UTF-8: E2 80 94 (226, 128, 148)
+ // En dash UTF-8: E2 80 93 (226, 128, 147)
+ let has_utf8_prefix = mojo_bridge::scan_byte(bytes, 0xE2).is_some();
+
+ for (line_idx, line) in content.lines().enumerate() {
+ let line_num = line_idx + 1;
+
+ // 1. Plaintext Secrets
+ for rule in SECRET_RULES.iter() {
+ for mat in rule.regex.find_iter(line) {
+ violations.push(Violation {
+ category: ViolationCategory::PlaintextSecret,
+ severity: rule.severity,
+ rule: rule.name.to_string(),
+ file_path: path.to_path_buf(),
+ line_number: Some(line_num),
+ column: Some(mat.start() + 1),
+ matched_text: "[REDACTED_BY_ATLAS_VAULT]".to_string(),
+ remediation: rule.remediation.to_string(),
+ });
+ }
+ }
+
+ // 2. Anti-Slop Violations
+ if has_utf8_prefix || line.contains('\u{2014}') || line.contains('\u{2013}') {
+ for rule in &SLOP_RULES[0..2] {
+ for mat in rule.regex.find_iter(line) {
+ violations.push(Violation {
+ category: ViolationCategory::AntiSlop,
+ severity: ViolationSeverity::Medium,
+ rule: rule.name.to_string(),
+ file_path: path.to_path_buf(),
+ line_number: Some(line_num),
+ column: Some(mat.start() + 1),
+ matched_text: mat.as_str().to_string(),
+ remediation: rule.remediation.to_string(),
+ });
+ }
+ }
+ }
+
+ for rule in &SLOP_RULES[2..] {
+ for mat in rule.regex.find_iter(line) {
+ violations.push(Violation {
+ category: ViolationCategory::AntiSlop,
+ severity: ViolationSeverity::Medium,
+ rule: rule.name.to_string(),
+ file_path: path.to_path_buf(),
+ line_number: Some(line_num),
+ column: Some(mat.start() + 1),
+ matched_text: mat.as_str().to_string(),
+ remediation: rule.remediation.to_string(),
+ });
+ }
+ }
+
+ // 3. Dangerous Commands
+ for rule in DANGEROUS_COMMAND_RULES.iter() {
+ for mat in rule.regex.find_iter(line) {
+ violations.push(Violation {
+ category: ViolationCategory::DangerousCommand,
+ severity: rule.severity,
+ rule: rule.name.to_string(),
+ file_path: path.to_path_buf(),
+ line_number: Some(line_num),
+ column: Some(mat.start() + 1),
+ matched_text: mat.as_str().to_string(),
+ remediation: rule.remediation.to_string(),
+ });
+ }
+ }
+ }
+
+ violations
+}
+
+pub fn scan_path(target_path: &Path) -> Result<ScanReport> {
+ let start = Instant::now();
+ let mut files_scanned = 0;
+ let mut violations = Vec::new();
+ let mut hasher = blake3::Hasher::new();
+
+ if target_path.is_file() {
+ files_scanned += 1;
+ let content = fs::read_to_string(target_path).unwrap_or_default();
+ hasher.update(content.as_bytes());
+ violations.extend(scan_content(target_path, &content));
+ } else if target_path.is_dir() {
+ let mut dirs = vec![target_path.to_path_buf()];
+ while let Some(dir) = dirs.pop() {
+ let entries = match fs::read_dir(&dir) {
+ Ok(e) => e,
+ Err(_) => continue,
+ };
+ for entry in entries.flatten() {
+ let p = entry.path();
+ let file_name = match p.file_name().and_then(|f| f.to_str()) {
+ Some(s) => s,
+ None => continue,
+ };
+
+ // Skip version control and build directories
+ if file_name == ".git" || file_name == "target" || file_name == "node_modules" {
+ continue;
+ }
+
+ if p.is_dir() {
+ dirs.push(p);
+ } else if p.is_file() {
+ files_scanned += 1;
+ if let Some((rule, remediation)) = is_prohibited_filename(&p) {
+ violations.push(Violation {
+ category: ViolationCategory::ProhibitedFile,
+ severity: ViolationSeverity::Critical,
+ rule: rule.to_string(),
+ file_path: p.clone(),
+ line_number: None,
+ column: None,
+ matched_text: p.display().to_string(),
+ remediation: remediation.to_string(),
+ });
+ }
+ if let Ok(content) = fs::read_to_string(&p) {
+ hasher.update(content.as_bytes());
+ violations.extend(scan_content(&p, &content));
+ }
+ }
+ }
+ }
+ } else {
+ anyhow::bail!("Target path {:?} does not exist", target_path);
+ }
+
+ let elapsed = start.elapsed().as_secs_f64() * 1000.0;
+ let digest = hasher.finalize().to_hex().to_string();
+ let passed = violations.is_empty();
+
+ Ok(ScanReport {
+ target: target_path.display().to_string(),
+ scanned_files_count: files_scanned,
+ violations,
+ passed,
+ blake3_hash: digest,
+ elapsed_ms: elapsed,
+ })
+}
+
+pub fn scan_diff(diff_content: &str) -> Result<ScanReport> {
+ let start = Instant::now();
+ let mut violations = Vec::new();
+ let mut current_file = PathBuf::from("diff");
+ let mut line_counter: usize = 0;
+
+ for line in diff_content.lines() {
+ if let Some(path_str) = line.strip_prefix("+++ b/") {
+ current_file = PathBuf::from(path_str);
+ if let Some((rule, remediation)) = is_prohibited_filename(¤t_file) {
+ violations.push(Violation {
+ category: ViolationCategory::ProhibitedFile,
+ severity: ViolationSeverity::Critical,
+ rule: rule.to_string(),
+ file_path: current_file.clone(),
+ line_number: None,
+ column: None,
+ matched_text: current_file.display().to_string(),
+ remediation: remediation.to_string(),
+ });
+ }
+ continue;
+ }
+
+ if line.starts_with('+') && !line.starts_with("+++") {
+ line_counter += 1;
+ let added_text = &line[1..];
+ let line_violations = scan_content(¤t_file, added_text);
+ for mut v in line_violations {
+ v.line_number = Some(line_counter);
+ violations.push(v);
+ }
+ }
+ }
+
+ let elapsed = start.elapsed().as_secs_f64() * 1000.0;
+ let digest = blake3::hash(diff_content.as_bytes()).to_hex().to_string();
+ let passed = violations.is_empty();
+
+ Ok(ScanReport {
+ target: "git-diff".to_string(),
+ scanned_files_count: 1,
+ violations,
+ passed,
+ blake3_hash: digest,
+ elapsed_ms: elapsed,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_secret_detection() {
+ let fake_aws = "export AWS_KEY=AKIAIOSFODNN7EXAMPLE\n";
+ let v = scan_content(Path::new("test.sh"), fake_aws);
+ assert_eq!(v.len(), 1);
+ assert_eq!(v[0].category, ViolationCategory::PlaintextSecret);
+ assert_eq!(v[0].matched_text, "[REDACTED_BY_ATLAS_VAULT]");
+ }
+
+ #[test]
+ fn test_slop_detection_em_dash() {
+ let bad_line = "This is a feature \u{2014} it elevates throughput.\n";
+ let v = scan_content(Path::new("doc.md"), bad_line);
+ assert!(v.iter().any(|item| item.rule == "Forbidden Em Dash"));
+ assert!(v.iter().any(|item| item.rule == "Banned AI Buzzword"));
+ }
+
+ #[test]
+ fn test_dangerous_command_detection() {
+ let dangerous = "rm -rf /\n";
+ let v = scan_content(Path::new("script.sh"), dangerous);
+ assert_eq!(v.len(), 1);
+ assert_eq!(v[0].category, ViolationCategory::DangerousCommand);
+ }
+
+ #[test]
+ fn test_prohibited_env_file() {
+ let path = Path::new("/workspace/.env");
+ let v = scan_content(path, "FOO=BAR\n");
+ assert!(v
+ .iter()
+ .any(|item| item.category == ViolationCategory::ProhibitedFile));
+ }
+}
diff --git a/crates/spark-aegis/tests/integration_tests.rs b/crates/spark-aegis/tests/integration_tests.rs
new file mode 100644
index 00000000 ..3d12b47e
--- /dev/null
+++ b/crates/spark-aegis/tests/integration_tests.rs
@@ -0,0 +1,137 @@
+// Integration tests for spark-aegis
+
+use spark_aegis::{audit, containment, doctrine, mojo_bridge, pr_triage, scanner};
+use std::fs;
+
+#[test]
+fn test_doctrine_invariants() {
+ assert_eq!(
+ doctrine::DOCTRINE_STATEMENT,
+ "The network is the house. Cut the session. Isolate the host. Close the door. Keep the evidence."
+ );
+ let invs = doctrine::all_invariants();
+ assert_eq!(invs.len(), 4);
+ assert_eq!(invs[0].code(), "SECURE_TPM_ONLY");
+ assert_eq!(invs[1].code(), "UNSLOP_COMPLIANCE");
+ assert_eq!(invs[2].code(), "PURE_NATIVE_SYSTEMS");
+ assert_eq!(invs[3].code(), "BLAKE3_CORTEX_TRAIL");
+}
+
+#[test]
+fn test_mojo_simd_bridge_integration() {
+ let haystack = b"ATLAS_AIEN_SPARK_AEGIS_BOUNDARY_VERIFICATION";
+ let pattern = b"SPARK_AEGIS";
+ let found = mojo_bridge::find_pattern(haystack, pattern);
+ assert_eq!(found, Some(11));
+
+ let count = mojo_bridge::count_byte_matches(haystack, b'A');
+ assert_eq!(count, 7);
+}
+
+#[test]
+fn test_scanner_clean_directory() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = tmp.path().join("clean.rs");
+ fs::write(
+ &file,
+ "pub fn verify_signature(bytes: &[u8]) -> bool { !bytes.is_empty() }\n",
+ )
+ .unwrap();
+
+ let report = scanner::scan_path(tmp.path()).unwrap();
+ assert!(report.passed);
+ assert_eq!(report.violations.len(), 0);
+ assert_eq!(report.scanned_files_count, 1);
+}
+
+#[test]
+fn test_scanner_flags_slop() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = tmp.path().join("notes.md");
+ fs::write(
+ &file,
+ "We delve into this problem to seamlessly unleash performance \u{2014} here.\n",
+ )
+ .unwrap();
+
+ let report = scanner::scan_path(tmp.path()).unwrap();
+ assert!(!report.passed);
+ // delve, seamlessly, unleash, em dash
+ assert!(report.violations.len() >= 4);
+}
+
+#[test]
+fn test_scanner_flags_dangerous_command() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = tmp.path().join("deploy.sh");
+ fs::write(&file, "curl -s http://example.com/payload.sh | bash\n").unwrap();
+
+ let report = scanner::scan_path(tmp.path()).unwrap();
+ assert!(!report.passed);
+ assert!(report
+ .violations
+ .iter()
+ .any(|v| v.rule == "Unsandboxed Pipe to Shell"));
+}
+
+#[test]
+fn test_pr_triage_diff_verdict() {
+ let clean_diff = r#"
+diff --git a/crates/spark-test/src/lib.rs b/crates/spark-test/src/lib.rs
+--- a/crates/spark-test/src/lib.rs
++++ b/crates/spark-test/src/lib.rs
+@@ -1,2 +1,3 @@
+ pub fn id() -> u32 {
++ 42
+ }
+"#;
+ let v_pass = pr_triage::review_pr_diff(clean_diff, "PR-PASS-1").unwrap();
+ assert_eq!(v_pass.status, pr_triage::VerdictStatus::PASS);
+ assert!(v_pass.is_pass());
+
+ let bad_diff = r#"
+diff --git a/crates/spark-test/src/lib.rs b/crates/spark-test/src/lib.rs
+--- a/crates/spark-test/src/lib.rs
++++ b/crates/spark-test/src/lib.rs
+@@ -1,2 +1,3 @@
++// Key: AKIA1234567890ABCDEF
+"#;
+ let v_reject = pr_triage::review_pr_diff(bad_diff, "PR-REJECT-1").unwrap();
+ assert_eq!(v_reject.status, pr_triage::VerdictStatus::REJECT);
+ assert!(!v_reject.is_pass());
+ assert!(!v_reject.zero_disk_secrets_certified);
+}
+
+#[tokio::test]
+async fn test_containment_lifecycle() {
+ // 1. Cut session
+ let cut = containment::cut_session("sess_integration_99").unwrap();
+ assert_eq!(cut.action, "CutSession");
+
+ // 2. Isolate host
+ let iso = containment::isolate_host(999998).unwrap();
+ assert_eq!(iso.action, "IsolateHost");
+
+ // 3. Close door
+ let tmp = tempfile::tempdir().unwrap();
+ let bad_file = tmp.path().join("rogue.sh");
+ fs::write(&bad_file, b"malicious code").unwrap();
+ let close = containment::close_door(&bad_file).unwrap();
+ assert_eq!(close.action, "CloseDoor");
+ assert!(!bad_file.exists());
+
+ // 4. Keep evidence
+ let incident = containment::IncidentReport::new(
+ "test_containment_lifecycle",
+ "CRITICAL",
+ serde_json::json!({"action": "integration_test"}),
+ );
+ let audit_receipt = containment::keep_evidence(&incident).await.unwrap();
+ assert_eq!(audit_receipt.blake3_hash.len(), 64);
+}
+
+#[tokio::test]
+async fn test_audit_system_execution() {
+ let report = audit::audit_system().await.unwrap();
+ assert_eq!(report.blake3_digest.len(), 64);
+}
diff --git a/install.sh b/install.sh
index 149ecc0c ..5f63021e 100755
--- a/install.sh
+++ b/install.sh
@@ -11,6 +11,33 @@ echo "=================================================================="
echo " âš¡ AIEN Sovereign Stack: Universal Developer Installer "
echo "=================================================================="
+# Run from a checkout or bootstrap one when the script is piped to Bash.
+PROTOCOLS_REV="7ac6facb630ca7e9a6ab4125b292203fe2bb6687 "
+INSTALL_WORKSPACE=""
+if [[ -n "${AIEN_SOURCE_DIR:-}" ]]; then
+ SOURCE_ROOT="$(cd "$AIEN_SOURCE_DIR" && pwd)"
+elif [[ -f "${BASH_SOURCE[0]:-}" && -f "$(dirname "${BASH_SOURCE[0]}")/Cargo.toml" ]]; then
+ SOURCE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+else
+ INSTALL_WORKSPACE="$(mktemp -d "${TMPDIR:-/tmp}/aien-install.XXXXXX")"
+ trap 'rm -rf "$INSTALL_WORKSPACE"' EXIT
+ git clone --quiet https://github.com/aien-dev/aien-sovereign-core.git "$INSTALL_WORKSPACE/core"
+ git -C "$INSTALL_WORKSPACE/core" checkout --quiet "${AIEN_REV:-main}"
+ SOURCE_ROOT="$INSTALL_WORKSPACE/core"
+fi
+[[ -f "$SOURCE_ROOT/Cargo.toml" ]] || { echo "AIEN source manifest is missing" >&2; exit 1; }
+PROTOCOLS_ROOT="$(dirname "$SOURCE_ROOT")/aien-protocols"
+if [[ ! -e "$PROTOCOLS_ROOT" ]]; then
+ git clone --quiet https://github.com/aien-dev/aien-protocols.git "$PROTOCOLS_ROOT"
+ git -C "$PROTOCOLS_ROOT" checkout --quiet "$PROTOCOLS_REV"
+fi
+[[ "$(git -C "$PROTOCOLS_ROOT" rev-parse HEAD)" = "$PROTOCOLS_REV" ]] || {
+ echo "Sibling aien-protocols must be at $PROTOCOLS_REV; existing checkout was preserved" >&2
+ exit 1
+}
+cd "$SOURCE_ROOT"
+echo "[*] Source commit: $(git rev-parse HEAD)"
+
OS="$(uname -s | tr "[:upper:]" "[:lower:]")"
ARCH="$(uname -m)"
@@ -35,8 +62,8 @@ if ! command -v cargo >/dev/null 2>&1; then
source "$HOME/.cargo/env"
fi
-BIN_DIR="$HOME/.local/bin"
-CONFIG_DIR="$HOME/.config/sovereign"
+BIN_DIR="${AIEN_BIN_DIR:-$HOME/.local/bin}"
+CONFIG_DIR="${AIEN_CONFIG_DIR:-$HOME/.config/sovereign}"
IMPRINT_DIR="$CONFIG_DIR/imprints/en2"
mkdir -p "$BIN_DIR" "$CONFIG_DIR" "$IMPRINT_DIR"
@@ -46,13 +73,15 @@ if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
export PATH="$BIN_DIR:$PATH"
fi
+if [[ "${AIEN_INSTALL_NO_PROFILE:-0}" != "1" ]]; then
for RC in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.profile"; do
if [ -f "$RC" ]; then
- if ! grep -q "\$HOME/.local/bin" "\$RC"; then
+ if ! grep -Fq '$HOME/.local/bin' "$RC"; then
echo "export PATH=\"\$HOME/.local/bin:\$PATH\"" >> "$RC"
fi
fi
done
+fi
echo "[*] Building Core Monorepo Binaries (High-Performance Release Mode)..."
echo " - aien-cli (Universal Terminal CLI & Orchestrator)"
@@ -64,7 +93,7 @@ echo " - spark-harness (5-Layer Verification Engine)"
echo " - spark-crumbs (Blake3 Scent & Action Vector Tracker)"
echo " - spark-aegis (Defensive Boundary & Containment Engine)"
-cargo build --release -p aien-cli -p spark-cockpit-rs -p cortex-rs -p spark-supervisor -p spark-debugger -p spark-harness -p spark-crumbs -p spark-aegis
+cargo build --locked --release -p aien-cli -p spark-cockpit-rs -p cortex-rs -p spark-supervisor -p spark-debugger -p spark-harness -p spark-crumbs -p spark-aegis
echo "[*] Installing Binaries to $BIN_DIR..."
cp target/release/aien-cli "$BIN_DIR/aien"
@@ -120,7 +149,7 @@ if [ -d "imprints/en2-trinity" ]; then
fi
echo "=================================================================="
-echo " âš¡ Installation Complete. The Entire AIEN Stack is Ready."
+echo " âš¡ Portable binaries installed. Model and access-token provisioning remain."
echo "=================================================================="
echo " Primary Command: aien"
echo ""
diff --git a/scripts/package-release.sh b/scripts/package-release.sh
new file mode 100755
index 00000000 ..dfcce660
--- /dev/null
+++ b/scripts/package-release.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "${BASH_SOURCE[0]}")/.."
+ARTIFACT="${1:?provide output archive path}"
+PACKAGE_DIR="$(mktemp -d)"
+trap 'rm -rf "$PACKAGE_DIR"' EXIT
+mkdir -p "$PACKAGE_DIR/bin"
+for binary in aien-cli spark-cockpit-rs spark-inquisitor cortex-encoder-rs cortex-rs spark-supervisor spark-debugger bench_inference_stack; do
+ [[ -x "target/release/$binary" ]] || { echo "Missing release binary: $binary" >&2; exit 1; }
+ name="$binary"
+ [[ "$binary" != aien-cli ]] || name=aien
+ cp "target/release/$binary" "$PACKAGE_DIR/bin/$name"
+done
+cp CONSTITUTION.md README.md install.sh "$PACKAGE_DIR/"
+if [[ -d imprints/en2-trinity ]]; then
+ mkdir -p "$PACKAGE_DIR/imprints"
+ cp -R imprints/en2-trinity "$PACKAGE_DIR/imprints/"
+fi
+tar -czf "$ARTIFACT" -C "$PACKAGE_DIR" .
diff --git a/scripts/test-install.sh b/scripts/test-install.sh
new file mode 100755
index 00000000 ..c9f2befb
--- /dev/null
+++ b/scripts/test-install.sh
@@ -0,0 +1,86 @@
+#!/usr/bin/env bash
+# Exercise piped installation (install.sh fed to bash on stdin) from an
+# arbitrary working directory without network access or real builds.
+# git and cargo are replaced by small stand-in scripts on PATH.
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+PROTOCOLS_REV="$(sed -n 's/^PROTOCOLS_REV="\([0-9a-f]\{40\}\)"$/\1/p' "$ROOT/install.sh")"
+[[ -n "$PROTOCOLS_REV" ]] || { echo "FAIL: PROTOCOLS_REV not found in install.sh" >&2; exit 1; }
+
+WORK="$(mktemp -d "${TMPDIR:-/tmp}/aien-test-install.XXXXXX")"
+trap 'rm -rf "$WORK"' EXIT
+mkdir -p "$WORK/mocks" "$WORK/cwd" "$WORK/tmp"
+
+fail() {
+ echo "FAIL: $*" >&2
+ [[ -f "$WORK/install.log" ]] && sed 's/^/ install: /' "$WORK/install.log" >&2
+ exit 1
+}
+
+# Stand-in git: clone creates a directory holding a Cargo.toml, rev-parse
+# reports the pinned protocols revision, config answers operator identity.
+cat > "$WORK/mocks/git" <<EOF
+#!/usr/bin/env bash
+printf '%s\n' "\$*" >> "$WORK/git.calls"
+case "\$1" in
+ clone)
+ dest="\${!#}"
+ mkdir -p "\$dest"
+ printf '[workspace]\n' > "\$dest/Cargo.toml"
+ ;;
+ -C)
+ case "\$3" in
+ rev-parse) echo "$PROTOCOLS_REV" ;;
+ esac
+ ;;
+ rev-parse) echo "$PROTOCOLS_REV" ;;
+ config)
+ if [[ "\${!#}" == user.name ]]; then echo "Fixture Operator"; else echo "fixture@example.test"; fi
+ ;;
+esac
+exit 0
+EOF
+
+# Stand-in cargo: checks it runs inside a checkout with a locked build that
+# includes every installed package, then writes placeholder binaries.
+cat > "$WORK/mocks/cargo" <<'EOF'
+#!/usr/bin/env bash
+[[ -f Cargo.toml ]] || { echo "installer did not locate checkout" >&2; exit 1; }
+args=" $* "
+[[ "$args" == *" --locked "* ]] || { echo "cargo build is not --locked" >&2; exit 1; }
+for pkg in aien-cli spark-cockpit-rs cortex-rs spark-supervisor spark-debugger spark-harness spark-crumbs spark-aegis; do
+ [[ "$args" == *" -p $pkg "* ]] || { echo "cargo build is missing package $pkg" >&2; exit 1; }
+ mkdir -p target/release
+ printf '#!/bin/sh\nexit 0\n' > "target/release/$pkg"
+ chmod 755 "target/release/$pkg"
+done
+EOF
+chmod 755 "$WORK/mocks/git" "$WORK/mocks/cargo"
+
+set +e
+(
+ cd "$WORK/cwd"
+ unset AIEN_SOURCE_DIR AIEN_REV
+ PATH="$WORK/mocks:$PATH" \
+ TMPDIR="$WORK/tmp" \
+ AIEN_BIN_DIR="$WORK/bin" \
+ AIEN_CONFIG_DIR="$WORK/config" \
+ AIEN_INSTALL_NO_PROFILE=1 \
+ bash < "$ROOT/install.sh"
+) > "$WORK/install.log" 2>&1
+status=$?
+set -e
+
+[[ $status -eq 0 ]] || fail "piped install.sh exited with status $status"
+for bin in aien spark-cockpit cortex spark-supervisor spark-debugger spark-harness spark-crumbs spark-aegis; do
+ [[ -x "$WORK/bin/$bin" ]] || fail "binary $bin was not installed"
+done
+[[ -f "$WORK/config/operator.toml" ]] || fail "operator.toml was not generated"
+grep -q '^name = "Fixture Operator"$' "$WORK/config/operator.toml" || fail "operator.toml lacks git identity"
+grep -q 'clone --quiet https://github.com/aien-dev/aien-sovereign-core.git' "$WORK/git.calls" || fail "installer did not clone the core repository"
+grep -q "checkout --quiet $PROTOCOLS_REV" "$WORK/git.calls" || fail "installer did not pin aien-protocols"
+[[ -z "$(ls -A "$WORK/tmp")" ]] || fail "installer left its temporary checkout behind"
+[[ -z "$(ls -A "$WORK/cwd")" ]] || fail "installer wrote into the caller's working directory"
+
+echo "PASS: piped installer bootstraps a checkout and installs the CLI from an arbitrary cwd"