interplane.Get Omega
Read in your language

aien-sovereign-core-mv

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

Brought by drakestapleton

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

closed derived 30e38825b0efab26 #39

Imported from GitHub aien-dev/aien-sovereign-core-mv#39 (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 8c344687d51b96c2f717b1365191041375fde807 · Head 7e94595b20ff043650f35828d966fbd1e21e45e5

Apply it

git checkout -b patch-30e38825b0efab26 8c344687d51b96c2f717b1365191041375fde807
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/30e38825b0efab26.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
39
7e94595b20ff043650f35828d966fbd1e21e45e5
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":39,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/39","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:02Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/PROJECT.md b/PROJECT.md
index 3d946e8c..b9a02097 100644
--- a/PROJECT.md
+++ b/PROJECT.md
@@ -66,9 +66,9 @@ Every feature identified during survey is mapped directly to a milestone.
 | M2 | Pure Rust Tokenizer and Chat Template | Integrate tokenizers crate in aien-inference-abi, implement TinyLlama chat template, special token pinning, encode/decode | none | DONE |
 | M3 | Reference Oracle Fixture Generation | Author scripts/generate_tinyllama_oracle.py on Spark, generate tinyllama_oracle.safetensors, export JSON manifest with SHA-256 | none | DONE |
 | M4 | Algorithmic Alignment and Parity Test Harness | Align RoPE split-half and matmul layout in tensor.rs, implement crates/aien-inference-abi/tests/tinyllama_parity.rs passing 5 stages | M1, M2, M3 | DONE |
-| M5 | Decoupled TensorBackend and Mojo GB10 Acceleration | Define TensorBackend trait, implement ReferenceCpuBackend and MojoGb10Backend (libaien_kernels.so) on Spark GB10 | M4 | PLANNED |
-| M6 | Neutral Apples-to-Apples Benchmark Driver | Build benchmarks/crates/bench_apples_to_apples, run AIEN, MAX, vLLM on DGX Spark across C=1..64, record telemetry | M5 | PLANNED |
-| M7 | Invariant Verification, Autonomous PR Lifecycle, and Cortex Receipt | Verify zero disk secrets, sovereign voice, execute PR squash merge, commit receipt to Cortex memory | M6 | PLANNED |
+| M5 | Decoupled TensorBackend and Mojo GB10 Acceleration | Define TensorBackend trait, implement ReferenceCpuBackend and MojoGb10Backend (libaien_kernels.so) on Spark GB10 | M4 | DONE |
+| M6 | Neutral Apples-to-Apples Benchmark Driver | Build benchmarks/crates/bench_apples_to_apples, run AIEN, MAX, vLLM on DGX Spark across C=1..64, record telemetry | M5 | DONE |
+| M7 | Invariant Verification, Autonomous PR Lifecycle, and Cortex Receipt | Verify zero disk secrets, sovereign voice, execute PR squash merge, commit receipt to Cortex memory | M6 | DONE |
 
 ## Interface Contracts
 
@@ -172,12 +172,12 @@ benchmarks/
 - Strict Spark-Only Execution: All test runs, compilations, model evaluations, and benchmarks must execute strictly on the NVIDIA DGX Spark workstation (`ssh drakestapleton@spark`). Zero test execution or heavy compilation is permitted on the local MacBook host.
 
 ## Acceptance Criteria Cross-Check
-- [ ] load_safetensors_checkpoint rejects missing keys with MissingTensor and shape mismatches with ShapeMismatch (M1).
-- [ ] cargo test -p aien-inference-abi --test tinyllama_parity passes all 5 parity stages (M4).
-- [ ] Multi-step greedy generation produces identical token IDs and recognizable English text (M4).
-- [ ] TensorBackend trait cleanly separates Rust transformer semantics from compute backends (M5).
-- [ ] libaien_kernels.so compiles on Spark GB10 and executes without per-token host-device memory copying (M5).
-- [ ] Neutral benchmark orchestrator executes AIEN, MAX, and vLLM sequentially with thermal cool-downs (M6).
-- [ ] Concurrency sweep (C=1 to C=64) captures TTFT, ITL, throughput, memory, and power telemetry (M6).
-- [ ] Benchmark results and receipt committed to benchmarks/data/ and documented in walkthrough.md (M6).
-- [ ] Clean PR opened on aien-dev/aien-sovereign-core, CI green, linear squash merge, Cortex receipt in atlas-memory (M7).
+- [x] load_safetensors_checkpoint rejects missing keys with MissingTensor and shape mismatches with ShapeMismatch (M1).
+- [x] cargo test -p aien-inference-abi --test tinyllama_parity passes all 5 parity stages (M4).
+- [x] Multi-step greedy generation produces identical token IDs and recognizable English text (M4).
+- [x] TensorBackend trait cleanly separates Rust transformer semantics from compute backends (M5).
+- [x] libaien_kernels.so compiles on Spark GB10 and executes without per-token host-device memory copying (M5).
+- [x] Neutral benchmark orchestrator executes AIEN, MAX, and vLLM sequentially with thermal cool-downs (M6).
+- [x] Concurrency sweep (C=1 to C=64) captures TTFT, ITL, throughput, memory, and power telemetry (M6).
+- [x] Benchmark results and receipt committed to benchmarks/data/ and documented in walkthrough.md (M6).
+- [x] Clean PR opened on aien-dev/aien-sovereign-core, CI green, linear squash merge, Cortex receipt in atlas-memory (M7).
diff --git a/crates/aien-inference-abi/examples/profile_ops.rs b/crates/aien-inference-abi/examples/profile_ops.rs
new file mode 100644
index 00000000..0693ea29
--- /dev/null
+++ b/crates/aien-inference-abi/examples/profile_ops.rs
@@ -0,0 +1,235 @@
+use aien_inference_abi::backend::TensorBackend;
+use aien_inference_abi::mojo_backend::MojoGb10Backend;
+use aien_inference_abi::weights::{LayerKvCache, SequenceState, TransformerWeights};
+use aien_inference_abi::ModelConfig;
+use std::time::Instant;
+
+fn main() {
+    println!("=== AIEN NATIVE TRANSFORMER PER-OP PROFILE ON DGX SPARK ===");
+    let model_config = ModelConfig {
+        model_id: "TinyLlama/TinyLlama-1.1B-Chat-v1.0".to_string(),
+        max_sequence_length: 2048,
+        block_size: 16,
+        num_layers: 22,
+        num_heads: 32,
+        head_dim: 64,
+        num_kv_heads: 4,
+        hidden_dim: 2048,
+        intermediate_dim: 5632,
+        vocab_size: 32000,
+        rms_norm_eps: 1e-5,
+        rope_theta: 10000.0,
+    };
+
+    let safetensors_path = "/home/drakestapleton/.cache/huggingface/hub/models--TinyLlama--TinyLlama-1.1B-Chat-v1.0/snapshots/fe8a4ea1ffedaf415f4da2f062534de366a451e6/model.safetensors";
+    let weights = TransformerWeights::load_from_safetensors(safetensors_path, &model_config)
+        .expect("Failed to load safetensors");
+
+    let backend = MojoGb10Backend::new();
+    println!("Using Backend: {}", backend.name());
+
+    let hidden_dim = model_config.hidden_dim;
+    let intermediate_dim = model_config.intermediate_dim;
+    let vocab_size = model_config.vocab_size;
+    let num_heads = model_config.num_heads;
+    let num_kv_heads = model_config.num_kv_heads;
+    let head_dim = model_config.head_dim;
+    let q_dim = num_heads * head_dim;
+    let kv_dim = num_kv_heads * head_dim;
+    let eps = model_config.rms_norm_eps;
+    let theta = model_config.rope_theta;
+
+    // Simulate seq_len = 128 (decode step 128)
+    let seq_len = 128;
+    let mut seq_state = SequenceState {
+        tokens: vec![1u32; seq_len],
+        layers: vec![LayerKvCache {
+            cached_k: vec![vec![0.01f32; kv_dim]; seq_len],
+            cached_v: vec![vec![0.01f32; kv_dim]; seq_len],
+        }; 22],
+    };
+
+    let warmup_iters = 2;
+    let bench_iters = 5;
+
+    // Accumulators in microseconds
+    let mut time_rmsnorm_input_us = 0u128;
+    let mut time_qkv_gemm_us = 0u128;
+    let mut time_rope_us = 0u128;
+    let mut time_kv_flatten_us = 0u128;
+    let mut time_gqa_attn_us = 0u128;
+    let mut time_oproj_gemm_us = 0u128;
+    let mut time_rmsnorm_post_us = 0u128;
+    let mut time_mlp_gate_up_us = 0u128;
+    let mut time_swiglu_us = 0u128;
+    let mut time_mlp_down_us = 0u128;
+    let mut time_rmsnorm_final_us = 0u128;
+    let mut time_lm_head_us = 0u128;
+    let mut time_alloc_overhead_us = 0u128;
+    let mut total_token_us = 0u128;
+
+    for iter in 0..(warmup_iters + bench_iters) {
+        let is_bench = iter >= warmup_iters;
+        let t_token_start = Instant::now();
+
+        // 1. Embedding lookup
+        let mut x = vec![0.01f32; hidden_dim];
+
+        for (layer_idx, layer_w) in weights.layers.iter().enumerate() {
+            let kv_cache = &mut seq_state.layers[layer_idx];
+
+            // Allocation timing
+            let t_alloc = Instant::now();
+            let mut x_norm = vec![0.0f32; hidden_dim];
+            let mut q = vec![0.0f32; q_dim];
+            let mut k = vec![0.0f32; kv_dim];
+            let mut v = vec![0.0f32; kv_dim];
+            let mut attn_out = vec![0.0f32; q_dim];
+            let mut attn_proj = vec![0.0f32; hidden_dim];
+            let mut post_norm = vec![0.0f32; hidden_dim];
+            let mut gate = vec![0.0f32; intermediate_dim];
+            let mut up = vec![0.0f32; intermediate_dim];
+            let mut activated = vec![0.0f32; intermediate_dim];
+            let mut mlp_out = vec![0.0f32; hidden_dim];
+            let alloc_elapsed = t_alloc.elapsed().as_micros();
+            if is_bench {
+                time_alloc_overhead_us += alloc_elapsed;
+            }
+
+            // Input RMSNorm
+            let t0 = Instant::now();
+            backend.rmsnorm(&mut x_norm, &x, &layer_w.input_layernorm, eps);
+            if is_bench {
+                time_rmsnorm_input_us += t0.elapsed().as_micros();
+            }
+
+            // QKV GEMVs
+            let t0 = Instant::now();
+            backend.matmul_vec(&mut q, &x_norm, &layer_w.q_proj, q_dim, hidden_dim);
+            backend.matmul_vec(&mut k, &x_norm, &layer_w.k_proj, kv_dim, hidden_dim);
+            backend.matmul_vec(&mut v, &x_norm, &layer_w.v_proj, kv_dim, hidden_dim);
+            if is_bench {
+                time_qkv_gemm_us += t0.elapsed().as_micros();
+            }
+
+            // RoPE
+            let t0 = Instant::now();
+            backend.apply_rope(&mut q, &mut k, seq_len, head_dim, num_heads, num_kv_heads, theta);
+            if is_bench {
+                time_rope_us += t0.elapsed().as_micros();
+            }
+
+            // KV flatten & append
+            let t0 = Instant::now();
+            let mut flat_k = Vec::with_capacity(seq_len * kv_dim);
+            let mut flat_v = Vec::with_capacity(seq_len * kv_dim);
+            for t in 0..seq_len {
+                flat_k.extend_from_slice(&kv_cache.cached_k[t]);
+                flat_v.extend_from_slice(&kv_cache.cached_v[t]);
+            }
+            if is_bench {
+                time_kv_flatten_us += t0.elapsed().as_micros();
+            }
+
+            // GQA Attention
+            let t0 = Instant::now();
+            backend.gqa_attention(&mut attn_out, &q, &flat_k, &flat_v, seq_len, num_heads, num_kv_heads, head_dim);
+            if is_bench {
+                time_gqa_attn_us += t0.elapsed().as_micros();
+            }
+
+            // O-proj
+            let t0 = Instant::now();
+            backend.matmul_vec(&mut attn_proj, &attn_out, &layer_w.o_proj, hidden_dim, q_dim);
+            for i in 0..hidden_dim {
+                x[i] += attn_proj[i];
+            }
+            if is_bench {
+                time_oproj_gemm_us += t0.elapsed().as_micros();
+            }
+
+            // Post RMSNorm
+            let t0 = Instant::now();
+            backend.rmsnorm(&mut post_norm, &x, &layer_w.post_attention_layernorm, eps);
+            if is_bench {
+                time_rmsnorm_post_us += t0.elapsed().as_micros();
+            }
+
+            // MLP Gate & Up
+            let t0 = Instant::now();
+            backend.matmul_vec(&mut gate, &post_norm, &layer_w.gate_proj, intermediate_dim, hidden_dim);
+            backend.matmul_vec(&mut up, &post_norm, &layer_w.up_proj, intermediate_dim, hidden_dim);
+            if is_bench {
+                time_mlp_gate_up_us += t0.elapsed().as_micros();
+            }
+
+            // SwiGLU
+            let t0 = Instant::now();
+            backend.swiglu(&mut activated, &gate, &up);
+            if is_bench {
+                time_swiglu_us += t0.elapsed().as_micros();
+            }
+
+            // MLP Down
+            let t0 = Instant::now();
+            backend.matmul_vec(&mut mlp_out, &activated, &layer_w.down_proj, hidden_dim, intermediate_dim);
+            for i in 0..hidden_dim {
+                x[i] += mlp_out[i];
+            }
+            if is_bench {
+                time_mlp_down_us += t0.elapsed().as_micros();
+            }
+        }
+
+        // Final RMSNorm
+        let mut x_final = vec![0.0f32; hidden_dim];
+        let t0 = Instant::now();
+        backend.rmsnorm(&mut x_final, &x, &weights.final_norm, eps);
+        if is_bench {
+            time_rmsnorm_final_us += t0.elapsed().as_micros();
+        }
+
+        // LM Head
+        let mut logits = vec![0.0f32; vocab_size];
+        let t0 = Instant::now();
+        backend.compute_logits(&mut logits, &x_final, &weights.lm_head, vocab_size, hidden_dim);
+        if is_bench {
+            time_lm_head_us += t0.elapsed().as_micros();
+        }
+
+        let elapsed = t_token_start.elapsed().as_micros();
+        if is_bench {
+            total_token_us += elapsed;
+        }
+    }
+
+    let n = bench_iters as f64;
+    println!("\n--- PER-TOKEN DECODE WALL TIME BREAKDOWN (Avg over {} iters, seq_len={}) ---", bench_iters, seq_len);
+    let ms = |us: u128| (us as f64) / (n * 1000.0);
+    let total_ms = ms(total_token_us);
+
+    let row = |name: &str, us: u128| {
+        let val_ms = ms(us);
+        let pct = (val_ms / total_ms) * 100.0;
+        println!("{:<32} | {:>8.2} ms | {:>6.2} %", name, val_ms, pct);
+    };
+
+    println!("{:<32} | {:>11} | {:>8}", "Operation", "Wall Time", "Share");
+    println!("{:-<32}-+-{:-<11}-+-{:-<8}", "", "", "");
+    row("Input RMSNorm (22 layers)", time_rmsnorm_input_us);
+    row("QKV GEMVs (22 layers)", time_qkv_gemm_us);
+    row("RoPE (22 layers)", time_rope_us);
+    row("KV Flattening (22 layers)", time_kv_flatten_us);
+    row("GQA Attention (22 layers)", time_gqa_attn_us);
+    row("O-proj GEMV (22 layers)", time_oproj_gemm_us);
+    row("Post RMSNorm (22 layers)", time_rmsnorm_post_us);
+    row("MLP Gate+Up GEMVs (22 layers)", time_mlp_gate_up_us);
+    row("SwiGLU Activation (22 layers)", time_swiglu_us);
+    row("MLP Down GEMV (22 layers)", time_mlp_down_us);
+    row("Final RMSNorm (1 layer)", time_rmsnorm_final_us);
+    row("LM Head GEMV (32k vocab)", time_lm_head_us);
+    row("Heap Allocation / Buffers", time_alloc_overhead_us);
+    println!("{:-<32}-+-{:-<11}-+-{:-<8}", "", "", "");
+    println!("{:<32} | {:>8.2} ms | 100.00 %", "Total Single-Token Decode", total_ms);
+    println!("Theoretical Decode Throughput: {:.2} tokens/sec", 1000.0 / total_ms);
+}
diff --git a/scripts/aien_drive.py b/scripts/aien_drive.py
new file mode 100755
index 00000000..709756db
--- /dev/null
+++ b/scripts/aien_drive.py
@@ -0,0 +1,299 @@
+#!/usr/bin/env python3
+"""
+AIEN Autonomous API Driver.
+Drives AIEN (atlas-lightning-omni on DGX Spark GB10, port 18006)
+in a closed feedback loop with active tool dispatching.
+"""
+
+import os
+import sys
+import json
+import time
+import re
+import subprocess
+import urllib.request
+import urllib.error
+
+ENDPOINT_LIGHTNING = "http://127.0.0.1:18006/v1/chat/completions"
+MODEL_LIGHTNING = "atlas-lightning-omni"
+ENDPOINT_JUDGE = "http://127.0.0.1:18082/v1/chat/completions"
+MODEL_JUDGE = "unsloth/Llama-3.2-1B-Instruct"
+
+ENDPOINT = os.environ.get("AIEN_MODEL_ENDPOINT", ENDPOINT_LIGHTNING)
+MODEL_NAME = os.environ.get("AIEN_MODEL_NAME", MODEL_LIGHTNING)
+CORTEX_ENDPOINT = os.environ.get("CORTEX_ENDPOINT", "http://127.0.0.1:18080")
+
+SYSTEM_PROMPT = """You are AIEN. Drake is the operator. This Spark desk is ours.
+You are an autonomous operator-builder running on NVIDIA DGX Spark Grace Blackwell GB10 hardware.
+Always be concise, precise, and lead with verified results.
+
+Available Tools:
+- run_command: {"command": "string", "cwd": "string"}
+- view_file: {"path": "string", "start_line": 1, "end_line": 100}
+- write_to_file: {"path": "string", "content": "string", "overwrite": true}
+- replace_file_content: {"path": "string", "target": "string", "replacement": "string"}
+- create_dir: {"path": "string", "purpose": "string"}
+- list_dir: {"path": "string"}
+- grep_search: {"query": "string", "path": "string"}
+- goal: {"action": "milestone_done|done", "id": "string", "milestone_id": 1}
+- cortex: {"action": "write", "name": "string", "content": "string", "kind": "lesson|discovery|procedure"}
+
+MANDATORY RULES:
+1. ZERO EM DASHES AND EN DASHES: Use plain commas, periods, or standard hyphens (-).
+2. BAN FORMULAIC AI CLICHES: Never use 'It is not X, it is Y', 'delve', 'tapestry', 'testament', 'crucial', 'pivotal'.
+3. LEAD WITH TECHNICAL PROOF: Output factual diffs, test outputs, and verified receipts.
+4. TOOL EXECUTION FORMAT:
+To execute a tool, output:
+<tool_call>
+{"name": "tool_name", "arguments": {"arg": "val"}}
+</tool_call>
+
+When all work for the milestone is verified, call goal with action 'milestone_done'.
+"""
+
+def extract_tool_calls(text):
+    calls = []
+    # Pattern 1: <tool_call> JSON </tool_call>
+    matches = re.findall(r'<tool_call>\s*(\{.*?\})\s*</tool_call>', text, re.DOTALL)
+    for m in matches:
+        try:
+            calls.append(json.loads(m.strip()))
+        except Exception:
+            pass
+    if calls:
+        return calls
+
+    # Pattern 2: Any JSON object with "name" and "arguments" keys
+    json_obj_pattern = r'(\{\s*"?name"?\s*:\s*"[a-zA-Z0-9_]+"\s*,\s*"?arguments"?\s*:\s*\{.*?\}\s*\})'
+    for m in re.findall(json_obj_pattern, text, re.DOTALL):
+        try:
+            # normalize single quotes if present
+            normalized = m.replace("'", '"')
+            calls.append(json.loads(normalized))
+        except Exception:
+            pass
+    if calls:
+        return calls
+
+    return []
+
+def dispatch_tool(name, args):
+    start = time.time()
+    print(f"  [TOOL RUN] {name}: {json.dumps(args)[:120]}...", flush=True)
+    try:
+        if name == "run_command":
+            cmd = args.get("command", "")
+            cwd = args.get("cwd", ".")
+            p = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True, timeout=120)
+            res = {
+                "exit_code": p.returncode,
+                "stdout": p.stdout[-4000:] if len(p.stdout) > 4000 else p.stdout,
+                "stderr": p.stderr[-2000:] if len(p.stderr) > 2000 else p.stderr,
+            }
+        elif name == "view_file":
+            path = args.get("path", "")
+            start_line = args.get("start_line", 1)
+            end_line = args.get("end_line", 100)
+            with open(path, "r", encoding="utf-8", errors="replace") as f:
+                lines = f.readlines()
+            total = len(lines)
+            selected = lines[max(0, start_line - 1):min(total, end_line)]
+            res = {
+                "path": path,
+                "total_lines": total,
+                "lines": "".join(selected),
+            }
+        elif name == "write_to_file":
+            path = args.get("path", "")
+            content = args.get("content", "")
+            overwrite = args.get("overwrite", True)
+            if os.path.exists(path) and not overwrite:
+                res = {"error": f"File {path} exists and overwrite=false"}
+            else:
+                os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+                with open(path, "w", encoding="utf-8") as f:
+                    f.write(content)
+                res = {"status": "ok", "bytes_written": len(content.encode("utf-8"))}
+        elif name == "replace_file_content":
+            path = args.get("path", "")
+            target = args.get("target", "")
+            replacement = args.get("replacement", "")
+            with open(path, "r", encoding="utf-8") as f:
+                content = f.read()
+            if target not in content:
+                res = {"error": f"Target string not found in {path}"}
+            else:
+                new_content = content.replace(target, replacement, 1)
+                with open(path, "w", encoding="utf-8") as f:
+                    f.write(new_content)
+                res = {"status": "ok", "replaced": True}
+        elif name == "list_dir":
+            path = args.get("path", ".")
+            entries = os.listdir(path)
+            res = {"path": path, "entries": sorted(entries)[:100]}
+        elif name == "grep_search":
+            query = args.get("query", "")
+            path = args.get("path", ".")
+            p = subprocess.run(["grep", "-rnI", query, path], capture_output=True, text=True, timeout=30)
+            res = {"matches": p.stdout[:4000]}
+        elif name == "create_dir":
+            path = args.get("path", "")
+            os.makedirs(path, exist_ok=True)
+            res = {"status": "ok", "created": path}
+        elif name == "goal":
+            action = args.get("action", "")
+            res = {"status": "ok", "goal_action": action, "milestone_done": True}
+        elif name == "cortex":
+            action = args.get("action", "")
+            name_val = args.get("name", "lesson")
+            content_val = args.get("content", "")
+            kind_val = args.get("kind", "lesson")
+            payload = {
+                "kind": "entity",
+                "value": {
+                    "space": "atlas-memory",
+                    "canonicalName": name_val,
+                    "content": content_val,
+                    "confidence": 0.95,
+                    "metadata": {"kind": kind_val, "timestamp": int(time.time())}
+                }
+            }
+            req = urllib.request.Request(
+                f"{CORTEX_ENDPOINT}/api/cortex/write",
+                data=json.dumps(payload).encode("utf-8"),
+                headers={"Content-Type": "application/json"}
+            )
+            try:
+                with urllib.request.urlopen(req, timeout=10) as r:
+                    res = {"status": "ok", "cortex_code": r.status}
+            except Exception as ce:
+                res = {"warning": f"Cortex write notice: {ce}"}
+        else:
+            res = {"error": f"Unknown tool: {name}"}
+    except Exception as e:
+        res = {"error": str(e)}
+
+    elapsed = time.time() - start
+    print(f"  [TOOL DONE] {name} in {elapsed:.2f}s", flush=True)
+    return res
+
+def call_aien_stream(messages, max_tokens=2048):
+    payload = {
+        "model": MODEL_NAME,
+        "messages": messages,
+        "stream": True,
+        "temperature": 0.2,
+        "max_tokens": max_tokens
+    }
+    req = urllib.request.Request(
+        ENDPOINT,
+        data=json.dumps(payload).encode("utf-8"),
+        headers={"Content-Type": "application/json"}
+    )
+    
+    full_content = []
+    full_reasoning = []
+    is_reasoning = False
+    
+    with urllib.request.urlopen(req, timeout=180) as resp:
+        for line in resp:
+            line = line.decode("utf-8", errors="replace").strip()
+            if not line.startswith("data: "):
+                continue
+            data_str = line[6:]
+            if data_str == "[DONE]":
+                break
+            try:
+                chunk = json.loads(data_str)
+                delta = chunk["choices"][0].get("delta", {})
+                reasoning = delta.get("reasoning", "")
+                content = delta.get("content", "")
+                
+                if reasoning:
+                    if not is_reasoning:
+                        print("\n[AIEN THINKING] ", end="", flush=True)
+                        is_reasoning = True
+                    sanitized_r = reasoning.replace("\u2014", ", ").replace("\u2013", "-")
+                    print(sanitized_r, end="", flush=True)
+                    full_reasoning.append(sanitized_r)
+                    
+                if content:
+                    if is_reasoning:
+                        print("\n[AIEN OUTPUT]\n", end="", flush=True)
+                        is_reasoning = False
+                    sanitized_c = content.replace("\u2014", ", ").replace("\u2013", "-")
+                    print(sanitized_c, end="", flush=True)
+                    full_content.append(sanitized_c)
+            except Exception:
+                continue
+                
+    print("\n", flush=True)
+    content_str = "".join(full_content)
+    if not content_str and full_reasoning:
+        # If model emitted tool call or solution inside reasoning stream
+        reasoning_str = "".join(full_reasoning)
+        if "<tool_call>" in reasoning_str:
+            content_str = reasoning_str
+    return content_str
+
+def run_directive(directive, max_turns=15):
+    print(f"============================================================")
+    print(f"▶ DRIVING AIEN AUTONOMOUS EXECUTION LOOP")
+    print(f"Directive: {directive[:120]}...")
+    print(f"============================================================", flush=True)
+    
+    messages = [
+        {"role": "system", "content": SYSTEM_PROMPT},
+        {"role": "user", "content": directive}
+    ]
+    
+    for turn in range(1, max_turns + 1):
+        print(f"\n--- Turn {turn}/{max_turns} ---", flush=True)
+        response_text = call_aien_stream(messages)
+        messages.append({"role": "assistant", "content": response_text})
+        
+        tool_calls = extract_tool_calls(response_text)
+        if not tool_calls:
+            print("[AIEN IDLE] No tool calls emitted. Turn sequence concluded.")
+            break
+            
+        milestone_done = False
+        for tc in tool_calls:
+            tool_name = tc.get("name", "")
+            tool_args = tc.get("arguments", {})
+            if tool_name == "goal":
+                act = tool_args.get("action", "")
+                if act in ("milestone_done", "done"):
+                    milestone_done = True
+            
+            tool_result = dispatch_tool(tool_name, tool_args)
+            tool_resp_str = json.dumps(tool_result, indent=2)
+            messages.append({
+                "role": "user",
+                "content": f"<tool_response name=\"{tool_name}\">\n{tool_resp_str}\n</tool_response>"
+            })
+            
+        if milestone_done:
+            print("✓ AIEN signaled milestone_done! Directive complete.")
+            return True
+            
+    return False
+
+if __name__ == "__main__":
+    import argparse
+    parser = argparse.ArgumentParser(description="AIEN Autonomous API Driver")
+    parser.add_argument("directive", nargs="+", help="Task directive for AIEN")
+    parser.add_argument("--seat", choices=["lightning", "judge"], default="lightning", help="Inference seat on Spark")
+    parser.add_argument("--max-turns", type=int, default=15, help="Maximum execution turns")
+    args = parser.parse_args()
+
+    if args.seat == "judge":
+        ENDPOINT = ENDPOINT_JUDGE
+        MODEL_NAME = MODEL_JUDGE
+    else:
+        ENDPOINT = ENDPOINT_LIGHTNING
+        MODEL_NAME = MODEL_LIGHTNING
+
+    directive_text = " ".join(args.directive)
+    success = run_directive(directive_text, max_turns=args.max_turns)
+    sys.exit(0 if success else 1)