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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-drive / tests / loop_stub.rs

170 lines · 6732 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! One full tool-dispatch round trip against stub HTTP servers (issue #179
17//! acceptance test), plus the cortex write payload and the failure paths.
18
19use aien_drive::{run_directive, CommandPolicy, Config};
20use serde_json::Value;
21use std::io::{BufRead, BufReader, Read, Write};
22use std::net::TcpListener;
23use std::sync::{Arc, Mutex};
24use std::time::Duration;
25
26/// Serve `replies.len()` requests; each gets the next canned (status, body).
27/// Returns the bound URL base and the captured request bodies.
28fn stub(replies: Vec<(u16, String)>) -> (String, Arc<Mutex<Vec<String>>>) {
29 let l = TcpListener::bind("127.0.0.1:0").unwrap();
30 let base = format!("http://{}", l.local_addr().unwrap());
31 let seen = Arc::new(Mutex::new(vec![]));
32 let s2 = seen.clone();
33 std::thread::spawn(move || {
34 for (status, body) in replies {
35 let (mut sock, _) = l.accept().unwrap();
36 let mut r = BufReader::new(sock.try_clone().unwrap());
37 let mut len = 0usize;
38 loop {
39 let mut h = String::new();
40 r.read_line(&mut h).unwrap();
41 if h.trim().is_empty() {
42 break;
43 }
44 if let Some(v) = h.to_ascii_lowercase().strip_prefix("content-length:") {
45 len = v.trim().parse().unwrap();
46 }
47 }
48 let mut b = vec![0u8; len];
49 r.read_exact(&mut b).unwrap();
50 s2.lock().unwrap().push(String::from_utf8(b).unwrap());
51 let _ = write!(
52 sock,
53 "HTTP/1.0 {status} X\r\nContent-Type: text/event-stream\r\n\r\n{body}"
54 );
55 }
56 });
57 (base, seen)
58}
59
60fn sse(text: &str) -> String {
61 let chunk = serde_json::json!({"choices": [{"delta": {"content": text}}]});
62 format!("data: {chunk}\n\ndata: [DONE]\n\n")
63}
64
65fn cfg(endpoint: String, cortex: String) -> Config {
66 Config {
67 endpoint,
68 model: "m".into(),
69 cortex_endpoint: cortex,
70 cortex_space: "aien-sources".into(),
71 request_timeout: Duration::from_secs(10),
72 command: CommandPolicy {
73 root: std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("/tmp")),
74 ..CommandPolicy::default()
75 },
76 cortex_token: None,
77 }
78}
79
80#[test]
81fn tool_round_trip_then_done() {
82 let t1 = "<tool_call>\n{\"name\": \"run_command\", \"arguments\": {\"command\": \"echo ROUNDTRIP_OK\"}}\n</tool_call>";
83 let t2 = "<tool_call>{\"name\": \"goal\", \"arguments\": {\"action\": \"milestone_done\"}}</tool_call>";
84 let (base, seen) = stub(vec![(200, sse(t1)), (200, sse(t2))]);
85 let ok = run_directive(
86 &cfg(format!("{base}/v1/chat/completions"), String::new()),
87 "do it",
88 5,
89 )
90 .unwrap();
91 assert!(ok);
92 let reqs = seen.lock().unwrap();
93 assert_eq!(reqs.len(), 2);
94 let second: Value = serde_json::from_str(&reqs[1]).unwrap();
95 let last = second["messages"].as_array().unwrap().last().unwrap()["content"]
96 .as_str()
97 .unwrap()
98 .to_string();
99 assert!(
100 last.contains("<tool_response name=\"run_command\">"),
101 "{last}"
102 );
103 assert!(last.contains("ROUNDTRIP_OK"), "{last}");
104 assert_eq!(second["stream"], true);
105}
106
107#[test]
108fn idle_reply_is_not_done() {
109 let (base, _) = stub(vec![(200, sse("just prose, no tools"))]);
110 assert!(!run_directive(&cfg(format!("{base}/x"), String::new()), "d", 5).unwrap());
111}
112
113#[test]
114fn max_turns_without_done_is_not_done() {
115 let t = "<tool_call>{\"name\": \"list_dir\", \"arguments\": {\"path\": \".\"}}</tool_call>";
116 let (base, seen) = stub(vec![(200, sse(t)), (200, sse(t))]);
117 assert!(!run_directive(&cfg(format!("{base}/x"), String::new()), "d", 2).unwrap());
118 assert_eq!(seen.lock().unwrap().len(), 2);
119}
120
121#[test]
122fn http_error_and_dead_endpoint_are_errors() {
123 let (base, _) = stub(vec![(500, "boom".into())]);
124 assert!(run_directive(&cfg(format!("{base}/x"), String::new()), "d", 2).is_err());
125 assert!(run_directive(&cfg("http://127.0.0.1:1/x".into(), String::new()), "d", 2).is_err());
126}
127
128#[test]
129fn reasoning_text_tool_call_is_not_executed() {
130 let chunk = serde_json::json!({"choices": [{"delta": {"reasoning": "a\u{2014}b <tool_call>{\"name\":\"goal\",\"arguments\":{\"action\":\"done\"}}</tool_call>"}}]});
131 let (base, seen) = stub(vec![(200, format!("data: {chunk}\n\ndata: [DONE]\n"))]);
132 assert!(!run_directive(&cfg(format!("{base}/x"), String::new()), "d", 3).unwrap());
133 assert_eq!(seen.lock().unwrap().len(), 1);
134}
135
136#[test]
137fn cortex_without_operator_token_does_not_post() {
138 let (cortex, seen) = stub(vec![(200, "{}".into())]);
139 let a = serde_json::json!({"action":"write","name":"n1","content":"c1","kind":"procedure"});
140 let r = aien_drive::dispatch_tool(&cfg(String::new(), cortex), "cortex", &a);
141 assert!(r.get("error").is_some(), "{r}");
142 assert!(
143 seen.lock().unwrap().is_empty(),
144 "unauthenticated cortex posted"
145 );
146}
147
148#[test]
149fn cortex_tool_posts_payload() {
150 let (cortex, seen) = stub(vec![(200, "{}".into())]);
151 let a = serde_json::json!({"action":"write","name":"n1","content":"c1","kind":"procedure"});
152 let mut c = cfg(String::new(), cortex);
153 c.cortex_token = Some("operator-token".into());
154 let r = aien_drive::dispatch_tool(&c, "cortex", &a);
155 assert_eq!(r["status"], "ok");
156 assert_eq!(r["cortex_code"], 200);
157 let p: Value = serde_json::from_str(&seen.lock().unwrap()[0]).unwrap();
158 assert_eq!(p["kind"], "entity");
159 assert_eq!(p["value"]["canonicalName"], "n1");
160 assert_eq!(p["value"]["space"], "aien-sources");
161 assert_eq!(p["value"]["metadata"]["kind"], "procedure");
162}
163
164#[test]
165fn run_command_bad_cwd_is_an_error_value() {
166 // An unknown cwd must come back as an error value, not a panic.
167 let a = serde_json::json!({"command": "true", "cwd": "/definitely/not/here"});
168 let r = aien_drive::dispatch_tool(&cfg(String::new(), String::new()), "run_command", &a);
169 assert!(r.get("error").is_some(), "{r}");
170}