interplane.Get Omega
Read in your language

aien-sovereign-core

Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core / crates / aien-cli / src / tools.rs

706 lines · 31567 bytes Raw Blame History
1use colored::*;
2use std::fs;
3use std::path::Path;
4use std::process::Command;
5use std::time::Instant;
6use serde_json::{json, Value};
7
8use chrono::Utc;
9use crate::crumbs::{
10 format_dir_crumb_tui, leave_dir_whisper, load_or_init_dir_crumb, record_directory_crumb,
11 save_dir_crumb, sniff_dir_crumb, CrumbPurpose,
12};
13use crate::safety::{contains_unmasked_secret, is_high_risk_command, is_high_risk_path, is_secret_leak_path};
14use crate::ui::{print_safety_prompt, print_tool_done, print_tool_start};
15use crate::vault::{redact_secrets, vault_dispatch_tool};
16
17pub fn dispatch_tool(name: &str, args: &Value) -> Value {
18 let start = Instant::now();
19 let summary = match name {
20 "run_command" => args.get("command").and_then(Value::as_str).unwrap_or(""),
21 "view_file" => args.get("path").and_then(Value::as_str).unwrap_or(""),
22 "write_to_file" => args.get("path").and_then(Value::as_str).unwrap_or(""),
23 "replace_file_content" => args.get("path").and_then(Value::as_str).unwrap_or(""),
24 "list_dir" => args.get("path").and_then(Value::as_str).unwrap_or(""),
25 "grep_search" => args.get("query").and_then(Value::as_str).unwrap_or(""),
26 "create_dir" => args.get("path").and_then(Value::as_str).unwrap_or(""),
27 "crumb" => args.get("action").and_then(Value::as_str).unwrap_or("survey"),
28 "vault" => args.get("action").and_then(Value::as_str).unwrap_or("list"),
29 "goal" => args.get("action").and_then(Value::as_str).unwrap_or("list"),
30 "skill" | "skills" => args.get("action").and_then(Value::as_str).unwrap_or("list"),
31 "cortex" => args.get("action").and_then(Value::as_str).unwrap_or("search"),
32 "sandbox" => args.get("action").and_then(Value::as_str).unwrap_or("status"),
33 "browser" => args.get("action").and_then(Value::as_str).unwrap_or("test"),
34 "invoke_subagent" => args.get("role").and_then(Value::as_str).unwrap_or(""),
35 "subagent" | "subagents" => args.get("action").and_then(Value::as_str).unwrap_or("list"),
36 "socratic" | "socratic_inquiry" => args.get("question").or_else(|| args.get("inquiry")).and_then(Value::as_str).unwrap_or(""),
37 "adapter" | "model_adapter" | "model_adapters" => args.get("action").and_then(Value::as_str).unwrap_or("list"),
38 _ => "",
39 };
40
41 // 1. Antigravity-style 9-tier Safety Engine Evaluation
42 let safety_engine = crate::safety::SafetyEngine::default_sovereign_engine();
43 match safety_engine.evaluate(name, args) {
44 crate::safety::SafetyDecision::Deny(reason) => {
45 let res = serde_json::json!({"error": format!("SECURITY DENIAL [SafetyEngine]: {}", reason)});
46 print_tool_start(name, summary);
47 print_tool_done(name, start.elapsed().as_millis(), false);
48 return res;
49 }
50 crate::safety::SafetyDecision::AskUser(reason) => {
51 println!("{}", format!("⚠️ SAFETY GATE: {}", reason).yellow().bold());
52 if !print_safety_prompt(&format!("Tool: '{}' with summary: '{}'", name, summary)) {
53 let res = serde_json::json!({"error": "Operation aborted by operator safety gate"});
54 print_tool_start(name, summary);
55 print_tool_done(name, start.elapsed().as_millis(), false);
56 return res;
57 }
58 }
59 crate::safety::SafetyDecision::Allow => {}
60 }
61
62 print_tool_start(name, summary);
63
64 // 2. Lifecycle Pre-tool Hook
65 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry();
66 let mut mutable_args = args.clone();
67 let short_circuit = tokio::task::block_in_place(|| {
68 tokio::runtime::Handle::current().block_on(hook_registry.run_pre_tool(name, &mut mutable_args))
69 });
70 if let Ok(Some(sc_result)) = short_circuit {
71 print_tool_done(name, start.elapsed().as_millis(), true);
72 return sc_result;
73 }
74
75 let (res, success) = match name {
76 "run_command" => {
77 let cmd = args.get("command").and_then(Value::as_str).unwrap_or("");
78 let cwd = args.get("cwd").and_then(Value::as_str).unwrap_or(".");
79
80 if is_high_risk_command(cmd) {
81 if !print_safety_prompt(cmd) {
82 (json!({"error": "Operation aborted by user safety gate"}), false)
83 } else {
84 exec_command(cmd, cwd)
85 }
86 } else {
87 exec_command(cmd, cwd)
88 }
89 },
90 "view_file" => {
91 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
92 let start_line = args.get("start_line").and_then(Value::as_u64).unwrap_or(1) as usize;
93 let end_line = args.get("end_line").and_then(Value::as_u64).unwrap_or(500) as usize;
94 exec_view_file(path, start_line, end_line)
95 },
96 "write_to_file" => {
97 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
98 let content = args.get("content").and_then(Value::as_str).unwrap_or("");
99 let overwrite = args.get("overwrite").and_then(Value::as_bool).unwrap_or(false);
100 let intent = args.get("intent").and_then(Value::as_str).unwrap_or("Writing file");
101 let vector = args.get("vector").and_then(Value::as_str).unwrap_or("Next action");
102
103 if is_secret_leak_path(path) {
104 (json!({"error": "REJECTED BY SOVEREIGN VAULT POLICY: Storing secrets or API keys in .env or plaintext credential files is strictly forbidden. Use 'atlas-vault add <KEY>' to store keys in the TPM-bound hardware vault, and retrieve them dynamically in memory via 'atlas-vault get <KEY>'."}), false)
105 } else if let Some(reason) = contains_unmasked_secret(content) {
106 (json!({"error": format!("REJECTED BY SOVEREIGN VAULT POLICY: {}. Never commit or write plaintext keys into files. Use 'atlas-vault add <KEY>'.", reason)}), false)
107 } else if is_high_risk_path(path) {
108 if !print_safety_prompt(path) {
109 (json!({"error": "Write to system path aborted by user safety gate"}), false)
110 } else {
111 exec_write_file(path, content, overwrite, intent, vector)
112 }
113 } else {
114 exec_write_file(path, content, overwrite, intent, vector)
115 }
116 },
117 "replace_file_content" => {
118 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
119 let target = args.get("target").and_then(Value::as_str).unwrap_or("");
120 let replacement = args.get("replacement").and_then(Value::as_str).unwrap_or("");
121 let intent = args.get("intent").and_then(Value::as_str).unwrap_or("Editing file content");
122 let vector = args.get("vector").and_then(Value::as_str).unwrap_or("Next action");
123
124 if is_secret_leak_path(path) {
125 (json!({"error": "REJECTED BY SOVEREIGN VAULT POLICY: Modifying .env or secret files on disk is strictly forbidden. Use atlas-vault."}), false)
126 } else if let Some(reason) = contains_unmasked_secret(replacement) {
127 (json!({"error": format!("REJECTED BY SOVEREIGN VAULT POLICY: {}. Never commit or write plaintext keys into files. Use 'atlas-vault add <KEY>'.", reason)}), false)
128 } else {
129 exec_replace_file(path, target, replacement, intent, vector)
130 }
131 },
132 "list_dir" => {
133 let path = args.get("path").and_then(Value::as_str).unwrap_or(".");
134 exec_list_dir(path)
135 },
136 "grep_search" => {
137 let query = args.get("query").and_then(Value::as_str).unwrap_or("");
138 let path = args.get("path").and_then(Value::as_str).unwrap_or(".");
139 exec_grep_search(query, path)
140 },
141 "create_dir" => {
142 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
143 let purpose = args.get("purpose").and_then(Value::as_str).unwrap_or("Workspace directory");
144 let lifecycle = args.get("lifecycle").and_then(Value::as_str);
145 exec_create_dir(path, purpose, lifecycle)
146 },
147 "crumb" => {
148 exec_crumb_tool(args)
149 },
150 "skill" | "skills" => {
151 (crate::skills::skills_dispatch_tool(args), true)
152 },
153 "goal" => {
154 (crate::goals::goals_dispatch_tool(args), true)
155 },
156 "cortex" => {
157 let res = tokio::task::block_in_place(|| {
158 tokio::runtime::Handle::current().block_on(crate::cortex::cortex_dispatch_tool(args))
159 });
160 (res, true)
161 },
162 "vault" => {
163 (vault_dispatch_tool(args), true)
164 },
165 "walkthrough" => {
166 let action = args.get("action").and_then(Value::as_str).unwrap_or("render");
167 if action == "save" {
168 let dest = Path::new("/home/drakestapleton/basecamp/WALKTHROUGH.md");
169 match crate::walkthrough::generate_and_save_walkthrough_md(dest) {
170 Ok(msg) => (json!({"status": "ok", "message": msg, "path": "/home/drakestapleton/basecamp/WALKTHROUGH.md"}), true),
171 Err(e) => (json!({"error": e}), false),
172 }
173 } else {
174 let card = crate::walkthrough::render_walkthrough_tui();
175 (json!({"status": "ok", "walkthrough": card}), true)
176 }
177 },
178 "hive" => {
179 (crate::hive::hive_dispatch_tool(args), true)
180 },
181 "socratic" | "socratic_inquiry" => {
182 let question = args.get("question").or_else(|| args.get("inquiry")).and_then(Value::as_str).unwrap_or("");
183 let parent_id = args.get("parent_id").and_then(Value::as_str);
184 if question.is_empty() {
185 (json!({"error": "Socratic question cannot be empty"}), false)
186 } else {
187 match spark_hive::CombStore::open_default() {
188 Ok(store) => {
189 match spark_hive::emit_socratic_comb(&store, question, parent_id) {
190 Ok(comb) => (json!({
191 "status": "emitted",
192 "comb_id": comb.id,
193 "q": comb.q,
194 "r": comb.r,
195 "role": "socratic",
196 "intent": "branch",
197 "question": question,
198 "message": "Socratic comb placed on hexagonal honeycomb lattice"
199 }), true),
200 Err(e) => (json!({"error": e.to_string()}), false),
201 }
202 }
203 Err(e) => (json!({"error": format!("Failed to open hive database: {}", e)}), false),
204 }
205 }
206 },
207 "adapter" | "model_adapter" | "model_adapters" => {
208 (adapter_dispatch_tool(args), true)
209 },
210 "sandbox" => {
211 (crate::sandbox::sandbox_dispatch_tool(args), true)
212 },
213 "browser" => {
214 let action = args.get("action").and_then(Value::as_str).unwrap_or("test");
215 let prompt = args.get("prompt").and_then(Value::as_str);
216 (crate::sandbox::browser_dispatch_tool(action, prompt), true)
217 },
218 "invoke_subagent" => {
219 let role = args.get("role").and_then(Value::as_str).unwrap_or("Subagent");
220 let prompt = args.get("prompt").and_then(Value::as_str).unwrap_or("");
221 let res = tokio::task::block_in_place(|| {
222 tokio::runtime::Handle::current().block_on(crate::subagents::invoke_subagent_from_root(role, prompt))
223 });
224 (res, true)
225 },
226 "subagent" | "subagents" => {
227 let action = args.get("action").and_then(Value::as_str).unwrap_or("list");
228 match action {
229 "list" => (crate::subagents::list_subagents(), true),
230 "view" => {
231 let id = args.get("id").and_then(Value::as_str).unwrap_or("");
232 (crate::subagents::view_subagent(id), true)
233 },
234 _ => (json!({"error": format!("Unknown subagent action: {}", action)}), false),
235 }
236 },
237 other => (json!({"error": format!("Unknown tool: {}", other)}), false),
238 };
239
240 // 3. Lifecycle Post-tool Hook
241 let mut final_res = res;
242 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry();
243 tokio::task::block_in_place(|| {
244 tokio::runtime::Handle::current().block_on(hook_registry.run_post_tool(name, args, &mut final_res))
245 });
246
247 // 4. Lifecycle On-tool-error Hook
248 if !success {
249 if let Some(err_str) = final_res.get("error").and_then(Value::as_str) {
250 let recovery = tokio::task::block_in_place(|| {
251 tokio::runtime::Handle::current().block_on(hook_registry.run_on_tool_error(name, args, err_str))
252 });
253 if let Some(rec) = recovery {
254 final_res = rec;
255 }
256 }
257 }
258
259 let elapsed = start.elapsed().as_millis();
260 print_tool_done(name, elapsed, success);
261 final_res
262}
263
264fn exec_command(cmd: &str, cwd: &str) -> (Value, bool) {
265 let out = Command::new("bash")
266 .args(["-c", cmd])
267 .current_dir(cwd)
268 .output();
269
270 match out {
271 Ok(output) => {
272 let raw_stdout = String::from_utf8_lossy(&output.stdout).to_string();
273 let raw_stderr = String::from_utf8_lossy(&output.stderr).to_string();
274 let stdout = redact_secrets(&raw_stdout);
275 let stderr = redact_secrets(&raw_stderr);
276 let code = output.status.code().unwrap_or(-1);
277 let success = output.status.success();
278 (json!({
279 "exit_code": code,
280 "stdout": stdout,
281 "stderr": stderr
282 }), success)
283 },
284 Err(e) => (json!({"error": e.to_string()}), false),
285 }
286}
287
288fn exec_view_file(path: &str, start_line: usize, end_line: usize) -> (Value, bool) {
289 let p = Path::new(path);
290 // Sniff directory breadcrumbs on this file
291 let crumb_notice = sniff_dir_crumb(p, "AIEN");
292
293 // Record view in directory crumb
294 record_directory_crumb("AIEN", "active-session", p, "view", "Inspected file lines", "");
295
296 match fs::read_to_string(path) {
297 Ok(content) => {
298 let lines: Vec<&str> = content.lines().collect();
299 let total_lines = lines.len();
300 let start = if start_line > 0 { start_line - 1 } else { 0 };
301 let end = std::cmp::min(end_line, total_lines);
302
303 if start >= total_lines && total_lines > 0 {
304 return (json!({"error": "start_line exceeds file length", "total_lines": total_lines}), false);
305 }
306
307 let slice = &lines[start..end];
308 let numbered: Vec<String> = slice
309 .iter()
310 .enumerate()
311 .map(|(idx, line)| {
312 let redacted = redact_secrets(line);
313 format!("{}: {}", start + idx + 1, redacted)
314 })
315 .collect();
316
317 let mut resp = json!({
318 "path": path,
319 "lines": numbered.join("\n"),
320 "total_lines": total_lines
321 });
322
323 if let Some(notice) = crumb_notice {
324 resp["peer_breadcrumb_notice"] = json!(notice);
325 }
326
327 (resp, true)
328 },
329 Err(e) => (json!({"error": e.to_string()}), false),
330 }
331}
332
333fn exec_write_file(path: &str, content: &str, overwrite: bool, intent: &str, vector: &str) -> (Value, bool) {
334 let p = Path::new(path);
335 if p.exists() && !overwrite {
336 return (json!({"error": format!("File already exists: {}. Pass overwrite: true to replace.", path)}), false);
337 }
338
339 if let Some(parent) = p.parent() {
340 if !parent.exists() {
341 let _ = fs::create_dir_all(parent);
342 let file_name = p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
343 let parent_purpose = CrumbPurpose {
344 statement: format!("Auto-created to house file: {}", file_name),
345 created_by: "AIEN".to_string(),
346 session_id: "active-session".to_string(),
347 created_at: Utc::now().to_rfc3339(),
348 lifecycle: "permanent".to_string(),
349 };
350 let crumb = load_or_init_dir_crumb(parent, Some(parent_purpose));
351 save_dir_crumb(&crumb);
352 }
353 }
354
355 let crumb_notice = sniff_dir_crumb(p, "AIEN");
356
357 match fs::write(path, content) {
358 Ok(()) => {
359 // Drop directory breadcrumb
360 record_directory_crumb("AIEN", "active-session", p, "write", intent, vector);
361
362 let mut resp = json!({
363 "status": "ok",
364 "path": path,
365 "bytes": content.len()
366 });
367 if let Some(notice) = crumb_notice {
368 resp["peer_breadcrumb_notice"] = json!(notice);
369 }
370 (resp, true)
371 },
372 Err(e) => (json!({"error": e.to_string()}), false),
373 }
374}
375
376fn exec_replace_file(path: &str, target: &str, replacement: &str, intent: &str, vector: &str) -> (Value, bool) {
377 let p = Path::new(path);
378 let crumb_notice = sniff_dir_crumb(p, "AIEN");
379
380 match fs::read_to_string(path) {
381 Ok(content) => {
382 if !content.contains(target) {
383 return (json!({"error": "target string not found in file"}), false);
384 }
385 let count = content.matches(target).count();
386 if count > 1 {
387 return (json!({"error": format!("target string occurred {} times, must be unique", count)}), false);
388 }
389 let updated = content.replace(target, replacement);
390 match fs::write(path, updated) {
391 Ok(()) => {
392 // Record edit in directory crumb
393 record_directory_crumb("AIEN", "active-session", p, "edit", intent, vector);
394
395 let mut resp = json!({
396 "status": "ok",
397 "path": path,
398 "replaced": true
399 });
400 if let Some(notice) = crumb_notice {
401 resp["peer_breadcrumb_notice"] = json!(notice);
402 }
403 (resp, true)
404 },
405 Err(e) => (json!({"error": e.to_string()}), false),
406 }
407 },
408 Err(e) => (json!({"error": e.to_string()}), false),
409 }
410}
411
412fn exec_list_dir(path: &str) -> (Value, bool) {
413 let p = Path::new(path);
414 let crumb_overview = format_dir_crumb_tui(p);
415
416 match fs::read_dir(path) {
417 Ok(entries) => {
418 let mut list = Vec::new();
419 for entry in entries.flatten() {
420 let name = entry.file_name().to_string_lossy().to_string();
421 let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
422 let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
423 list.push(json!({
424 "name": name,
425 "is_dir": is_dir,
426 "size_bytes": size
427 }));
428 }
429 (json!({
430 "path": path,
431 "entries": list,
432 "directory_crumb": crumb_overview
433 }), true)
434 },
435 Err(e) => (json!({"error": e.to_string()}), false),
436 }
437}
438
439fn exec_grep_search(query: &str, path: &str) -> (Value, bool) {
440 let out = Command::new("grep")
441 .args(["-rnI", query, path])
442 .output();
443
444 match out {
445 Ok(output) => {
446 let raw_stdout = String::from_utf8_lossy(&output.stdout).to_string();
447 let redacted_stdout = redact_secrets(&raw_stdout);
448 let matches: Vec<String> = redacted_stdout.lines().take(50).map(|s| s.to_string()).collect();
449 (json!({
450 "query": query,
451 "matches": matches,
452 "count": matches.len()
453 }), true)
454 },
455 Err(e) => (json!({"error": e.to_string()}), false),
456 }
457}
458
459fn exec_crumb_tool(args: &Value) -> (Value, bool) {
460 let action = args.get("action").and_then(Value::as_str).unwrap_or("survey");
461 let path_str = args.get("path").and_then(Value::as_str).unwrap_or(".");
462 let p = Path::new(path_str);
463
464 match action {
465 "survey" => {
466 let view = format_dir_crumb_tui(p);
467 (json!({"status": "ok", "crumb_view": view}), true)
468 },
469 "whisper" => {
470 let msg = args.get("message").and_then(Value::as_str).unwrap_or("");
471 let target_file = args.get("target_file").and_then(Value::as_str);
472 let dir = if p.is_dir() { p } else { p.parent().unwrap_or(p) };
473 leave_dir_whisper("AIEN", dir, target_file, msg);
474 (json!({"status": "ok", "message": "Whisper recorded to directory .crumb"}), true)
475 },
476 "init" => {
477 let purpose_str = args.get("purpose").and_then(Value::as_str).unwrap_or("Workspace directory");
478 let lifecycle = args.get("lifecycle").and_then(Value::as_str).unwrap_or("permanent");
479 let p_dir = if p.is_dir() { p } else { p.parent().unwrap_or(p) };
480 let _ = fs::create_dir_all(p_dir);
481 let purpose_obj = CrumbPurpose {
482 statement: purpose_str.to_string(),
483 created_by: "AIEN".to_string(),
484 session_id: "active-session".to_string(),
485 created_at: Utc::now().to_rfc3339(),
486 lifecycle: lifecycle.to_string(),
487 };
488 let mut crumb = load_or_init_dir_crumb(p_dir, Some(purpose_obj));
489 crumb.description = purpose_str.to_string();
490 save_dir_crumb(&crumb);
491 (json!({"status": "ok", "message": format!("Initialized .crumb with purpose for {}", p_dir.display())}), true)
492 },
493 "record" => {
494 let intent = args.get("intent").and_then(Value::as_str).unwrap_or("Working in directory");
495 let vector = args.get("vector").and_then(Value::as_str).unwrap_or("Next milestone");
496 record_directory_crumb("AIEN", "tool-call", p, "record", intent, vector);
497 (json!({"status": "ok", "message": "Directory crumb recorded"}), true)
498 },
499 other => (json!({"error": format!("Unknown crumb action: {}", other)}), false),
500 }
501}
502
503fn exec_create_dir(path: &str, purpose: &str, lifecycle: Option<&str>) -> (Value, bool) {
504 let p = Path::new(path);
505 if path.is_empty() {
506 return (json!({"error": "Path cannot be empty"}), false);
507 }
508
509 if let Err(e) = fs::create_dir_all(p) {
510 return (json!({"error": format!("Failed to create directory {}: {}", path, e)}), false);
511 }
512
513 let purpose_obj = CrumbPurpose {
514 statement: purpose.to_string(),
515 created_by: "AIEN".to_string(),
516 session_id: "active-session".to_string(),
517 created_at: Utc::now().to_rfc3339(),
518 lifecycle: lifecycle.unwrap_or("permanent").to_string(),
519 };
520
521 let mut crumb = load_or_init_dir_crumb(p, Some(purpose_obj));
522 crumb.description = purpose.to_string();
523 save_dir_crumb(&crumb);
524
525 // Record scent mark into crumb
526 record_directory_crumb("AIEN", "active-session", p, "create_dir", purpose, "Directory initialized with purpose");
527
528 let crumb_overview = format_dir_crumb_tui(p);
529
530 (json!({
531 "status": "ok",
532 "path": path,
533 "purpose": purpose,
534 "crumb_created": true,
535 "directory_crumb": crumb_overview
536 }), true)
537}
538
539
540pub fn adapter_dispatch_tool(args: &Value) -> Value {
541 let action = args.get("action").and_then(Value::as_str).unwrap_or("list");
542 let target = args.get("target")
543 .or_else(|| args.get("model"))
544 .or_else(|| args.get("id"))
545 .and_then(Value::as_str)
546 .unwrap_or("");
547 let engine_str = args.get("engine").and_then(Value::as_str);
548 let engine_override = engine_str.and_then(spark_hive::UpstreamEngine::from_name);
549
550 match action {
551 "list" | "catalog" => {
552 let adapters = spark_hive::get_catalog_adapters();
553 let models = spark_hive::ConsumerModel::all();
554 let engines = spark_hive::UpstreamEngine::all();
555 json!({
556 "status": "ok",
557 "total_adapters": adapters.len(),
558 "adapters": adapters,
559 "models": models.iter().map(|m| json!({
560 "slug": m.slug(),
561 "name": m.display_name(),
562 "params_b": m.param_count_billions(),
563 "hardware": m.hardware_profile().description(),
564 "quantization": m.recommended_quantization(),
565 })).collect::<Vec<_>>(),
566 "engines": engines.iter().map(|e| json!({
567 "repo": e.repo(),
568 "language": e.primary_language(),
569 "description": e.description(),
570 })).collect::<Vec<_>>()
571 })
572 }
573 "evaluate" | "socratic" => {
574 if target.is_empty() {
575 return json!({"error": "Target model or adapter id must be provided for evaluate"});
576 }
577 let spec = spark_hive::find_or_create_adapter(target, engine_override);
578 let Some(spec) = spec else {
579 return json!({"error": format!("Model or adapter {} not found", target)});
580 };
581 let eval = spark_hive::evaluate_socratic_reflex(&spec.model, &spec.engine);
582 json!({
583 "status": "ok",
584 "target": spec.id,
585 "model": spec.model.slug(),
586 "engine": spec.engine.repo(),
587 "evaluation": eval
588 })
589 }
590 "plan" | "pr" => {
591 if target.is_empty() {
592 return json!({"error": "Target model or adapter id must be provided for plan"});
593 }
594 let spec = spark_hive::find_or_create_adapter(target, engine_override);
595 let Some(spec) = spec else {
596 return json!({"error": format!("Model or adapter {} not found", target)});
597 };
598 let socratic = spark_hive::evaluate_socratic_reflex(&spec.model, &spec.engine);
599 let sandbox_path = args.get("sandbox_path").and_then(Value::as_str).unwrap_or("/home/drakestapleton/workspace/aien-sandbox");
600 let telem = spark_hive::BenchmarkTelemetry::estimate_for_model(
601 &spec.model,
602 &spec.engine,
603 sandbox_path,
604 None,
605 );
606 let plan = spark_hive::generate_pr_plan(&spec, telem, socratic);
607 json!({
608 "status": "ok",
609 "plan": plan
610 })
611 }
612 "emit" => {
613 if target.is_empty() {
614 return json!({"error": "Target model or adapter id must be provided for emit"});
615 }
616 let spec = spark_hive::find_or_create_adapter(target, engine_override);
617 let Some(spec) = spec else {
618 return json!({"error": format!("Model or adapter {} not found", target)});
619 };
620 let socratic = spark_hive::evaluate_socratic_reflex(&spec.model, &spec.engine);
621 let sandbox_path = args.get("sandbox_path").and_then(Value::as_str).unwrap_or("/home/drakestapleton/workspace/aien-sandbox");
622 let telem = spark_hive::BenchmarkTelemetry::estimate_for_model(
623 &spec.model,
624 &spec.engine,
625 sandbox_path,
626 None,
627 );
628 let plan = spark_hive::generate_pr_plan(&spec, telem, socratic);
629 let parent_id = args.get("parent_id").and_then(Value::as_str);
630 match spark_hive::CombStore::open_default() {
631 Ok(store) => match spark_hive::emit_adapter_pipeline_combs(&store, &plan, parent_id) {
632 Ok(receipt) => json!({
633 "status": "emitted",
634 "receipt": receipt,
635 "plan": {
636 "adapter_id": plan.adapter_id,
637 "target_repo": plan.target_repo,
638 "branch": plan.branch,
639 "commit_message": plan.commit_message,
640 "pr_title": plan.pr_title,
641 }
642 }),
643 Err(e) => json!({"error": format!("Failed to emit combs: {}", e)}),
644 },
645 Err(e) => json!({"error": format!("Failed to open hive database: {}", e)}),
646 }
647 }
648 "chains" | "lattice" => {
649 match spark_hive::CombStore::open_default() {
650 Ok(store) => match spark_hive::list_adapter_pipeline_chains(&store) {
651 Ok(chains) => json!({
652 "status": "ok",
653 "total_chains": chains.len(),
654 "chains": chains
655 }),
656 Err(e) => json!({"error": format!("Failed to query chains: {}", e)}),
657 },
658 Err(e) => json!({"error": format!("Failed to open hive database: {}", e)}),
659 }
660 }
661 _ => json!({"error": format!("Unknown adapter action {}. Valid actions: list, evaluate, plan, emit, chains", action)}),
662 }
663}
664
665#[cfg(test)]
666mod tests {
667 use super::*;
668
669 #[test]
670 fn test_adapter_tool_dispatch_list() {
671 let args = json!({"action": "list"});
672 let res = adapter_dispatch_tool(&args);
673 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "ok");
674 assert!(res.get("adapters").unwrap().as_array().unwrap().len() >= 10);
675 assert_eq!(res.get("models").unwrap().as_array().unwrap().len(), 9);
676 }
677
678 #[test]
679 fn test_adapter_tool_dispatch_evaluate() {
680 let args = json!({"action": "evaluate", "target": "deepseek-r1-distill-qwen-7b"});
681 let res = adapter_dispatch_tool(&args);
682 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "ok");
683 let eval = res.get("evaluation").unwrap();
684 assert!(eval.get("approved").unwrap().as_bool().unwrap());
685 }
686
687 #[test]
688 fn test_adapter_tool_dispatch_plan() {
689 let args = json!({"action": "plan", "target": "qwen2.5-coder-7b", "engine": "vllm"});
690 let res = adapter_dispatch_tool(&args);
691 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "ok");
692 let plan = res.get("plan").unwrap();
693 assert_eq!(plan.get("target_repo").unwrap().as_str().unwrap(), "vllm-project/vllm");
694 assert!(plan.get("pr_script").unwrap().as_str().unwrap().contains("gh repo fork"));
695 }
696
697 #[test]
698 fn test_safety_engine_allows_adapter_and_socratic() {
699 let safety = crate::safety::SafetyEngine::default_sovereign_engine();
700 let adapter_args = json!({"action": "list"});
701 let socratic_args = json!({"question": "Is local offline execution sovereign?"});
702
703 assert_eq!(safety.evaluate("adapter", &adapter_args), crate::safety::SafetyDecision::Allow);
704 assert_eq!(safety.evaluate("socratic", &socratic_args), crate::safety::SafetyDecision::Allow);
705 }
706}