Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-cli/src/tools.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-cli / src / tools.rs` 1988 lines · 76509 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 use colored::*; 17 use serde_json::{json, Value}; 18 use sha2::{Digest, Sha256}; 19 use std::io::Write; 20 use std::os::fd::AsRawFd; 21 use std::os::unix::process::CommandExt; 22 use std::path::Path; 23 use std::process::{Command, Stdio}; 24 use std::sync::atomic::{AtomicBool, Ordering}; 25 use std::sync::Arc; 26 use std::time::{Duration, Instant}; 27 28 use crate::crumbs::{ 29 format_dir_crumb_tui, load_or_init_dir_crumb, purpose_author, record_as_self, save_dir_crumb, 30 sniff_as_self, whisper_as_self, CrumbPurpose, 31 }; 32 use crate::safety::{contains_unmasked_secret, is_secret_leak_path}; 33 use crate::ui::{print_safety_prompt, print_tool_done, print_tool_start}; 34 use crate::vault::{redact_secrets, vault_dispatch_tool}; 35 use chrono::Utc; 36 37 /// Advisory `.crumb.local` notes for one file tool call (core#924). It is 38 /// optional: a failed note never blocks the file effect, and it is never 39 /// reported as success either. Every failure lands in 40 /// `crumb_local_errors` of the tool result. 41 #[derive(Default)] 42 struct CrumbNotes { 43 notice: Option, 44 errors: Vec, 45 } 46 47 impl CrumbNotes { 48 fn sniff(&mut self, p: &Path) { 49 match sniff_as_self(p) { 50 Ok(notice) => self.notice = notice, 51 Err(e) => self.errors.push(format!("sniff: {e}")), 52 } 53 } 54 55 fn record(&mut self, p: &Path, action: &str, intent: &str, vector: &str) { 56 if let Err(e) = record_as_self(p, action, intent, vector) { 57 self.errors.push(format!("record {action}: {e}")); 58 } 59 } 60 61 fn apply(self, resp: &mut Value) { 62 if let Some(notice) = self.notice { 63 resp["peer_breadcrumb_notice"] = json!(notice); 64 } 65 if !self.errors.is_empty() { 66 resp["crumb_local_errors"] = json!(self.errors); 67 } 68 } 69 } 70 71 pub fn dispatch_tool(name: &str, args: &Value) -> Value { 72 dispatch_tool_with(name, args, &crate::approval::GateContext::from_env()) 73 } 74 75 pub fn dispatch_tool_with(name: &str, args: &Value, ctx: &crate::approval::GateContext) -> Value { 76 let start = Instant::now(); 77 let summary = match name { 78 "run_command" => args.get("command").and_then(Value::as_str).unwrap_or(""), 79 "view_file" => args.get("path").and_then(Value::as_str).unwrap_or(""), 80 "write_to_file" => args.get("path").and_then(Value::as_str).unwrap_or(""), 81 "replace_file_content" => args.get("path").and_then(Value::as_str).unwrap_or(""), 82 "list_dir" => args.get("path").and_then(Value::as_str).unwrap_or(""), 83 "grep_search" | "search_directory" => args 84 .get("query") 85 .or_else(|| args.get("Query")) 86 .and_then(Value::as_str) 87 .unwrap_or(""), 88 "find_by_name" | "find_file" => args 89 .get("pattern") 90 .or_else(|| args.get("name")) 91 .or_else(|| args.get("Pattern")) 92 .and_then(Value::as_str) 93 .unwrap_or(""), 94 "ask_question" => args.get("question").and_then(Value::as_str).unwrap_or(""), 95 "create_dir" => args.get("path").and_then(Value::as_str).unwrap_or(""), 96 "crumb" => args 97 .get("action") 98 .and_then(Value::as_str) 99 .unwrap_or("survey"), 100 "vault" => args.get("action").and_then(Value::as_str).unwrap_or("list"), 101 "goal" => args.get("action").and_then(Value::as_str).unwrap_or("list"), 102 "skill" | "skills" => args.get("action").and_then(Value::as_str).unwrap_or("list"), 103 "context7" => args 104 .get("action") 105 .and_then(Value::as_str) 106 .unwrap_or("resolve"), 107 "cortex" => args 108 .get("action") 109 .and_then(Value::as_str) 110 .unwrap_or("search"), 111 "sandbox" => args 112 .get("action") 113 .and_then(Value::as_str) 114 .unwrap_or("status"), 115 "browser" => args.get("action").and_then(Value::as_str).unwrap_or("test"), 116 "invoke_subagent" => args.get("role").and_then(Value::as_str).unwrap_or(""), 117 "subagent" | "subagents" => args.get("action").and_then(Value::as_str).unwrap_or("list"), 118 "socratic" | "socratic_inquiry" => args 119 .get("question") 120 .or_else(|| args.get("inquiry")) 121 .and_then(Value::as_str) 122 .unwrap_or(""), 123 "adapter" | "model_adapter" | "model_adapters" => { 124 args.get("action").and_then(Value::as_str).unwrap_or("list") 125 } 126 _ => "", 127 }; 128 129 // 1. The approval gate (sc#667): floors first in every mode, then the 130 // nine-tier SafetyEngine's denials, mode, allowlist, presence, danger, 131 // guardian and person. See approval.rs for the ordering rule. 132 if let Err(res) = gate_tool(name, args, summary, ctx) { 133 print_tool_start(name, summary); 134 print_tool_done(name, start.elapsed().as_millis(), false); 135 return res; 136 } 137 138 print_tool_start(name, summary); 139 140 // 2. Lifecycle Pre-tool Hook 141 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry(); 142 let mut mutable_args = args.clone(); 143 let short_circuit = tokio::task::block_in_place(|| { 144 tokio::runtime::Handle::current() 145 .block_on(hook_registry.run_pre_tool(name, &mut mutable_args)) 146 }); 147 if let Ok(Some(sc_result)) = short_circuit { 148 print_tool_done(name, start.elapsed().as_millis(), true); 149 return sc_result; 150 } 151 152 let (res, success) = match name { 153 "run_command" => { 154 let cmd = args 155 .get("command") 156 .or_else(|| args.get("CommandLine")) 157 .and_then(Value::as_str) 158 .unwrap_or(""); 159 let cwd = args 160 .get("cwd") 161 .or_else(|| args.get("Cwd")) 162 .and_then(Value::as_str) 163 .unwrap_or("."); 164 165 // The approval gate decided before this point (sc#667); a second 166 // prompt here would re-ask the person and override yolo/off. 167 exec_command(cmd, cwd) 168 } 169 "view_file" => { 170 let path = args 171 .get("path") 172 .or_else(|| args.get("AbsolutePath")) 173 .and_then(Value::as_str) 174 .unwrap_or(""); 175 let start_line = args 176 .get("start_line") 177 .or_else(|| args.get("StartLine")) 178 .and_then(Value::as_u64) 179 .unwrap_or(1) as usize; 180 let end_line = args 181 .get("end_line") 182 .or_else(|| args.get("EndLine")) 183 .and_then(Value::as_u64) 184 .unwrap_or(500) as usize; 185 exec_view_file(path, start_line, end_line) 186 } 187 "write_to_file" | "create_file" => { 188 let path = args 189 .get("path") 190 .or_else(|| args.get("target_file")) 191 .or_else(|| args.get("TargetFile")) 192 .and_then(Value::as_str) 193 .unwrap_or(""); 194 let content = args 195 .get("content") 196 .or_else(|| args.get("CodeContent")) 197 .and_then(Value::as_str) 198 .unwrap_or(""); 199 let overwrite = args 200 .get("overwrite") 201 .or_else(|| args.get("Overwrite")) 202 .and_then(Value::as_bool) 203 .unwrap_or(false); 204 let intent = args 205 .get("intent") 206 .and_then(Value::as_str) 207 .unwrap_or("Writing file"); 208 let vector = args 209 .get("vector") 210 .and_then(Value::as_str) 211 .unwrap_or("Next action"); 212 213 if is_secret_leak_path(path) { 214 ( 215 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 ' to store keys in the TPM-bound hardware vault, and retrieve them dynamically in memory via 'atlas-vault get '."}), 216 false, 217 ) 218 } else if let Some(reason) = contains_unmasked_secret(content) { 219 ( 220 json!({"error": format!("REJECTED BY SOVEREIGN VAULT POLICY: {}. Never commit or write plaintext keys into files. Use 'atlas-vault add '.", reason)}), 221 false, 222 ) 223 } else { 224 // System paths were already put to the person by the 225 // approval gate (sc#667); one decision, never two. 226 recorded_write("write_to_file", path, |held| { 227 exec_write_file(held, content, overwrite, intent, vector) 228 }) 229 } 230 } 231 "replace_file_content" | "edit_file" => { 232 let path = args 233 .get("path") 234 .or_else(|| args.get("target_file")) 235 .or_else(|| args.get("TargetFile")) 236 .and_then(Value::as_str) 237 .unwrap_or(""); 238 let target = args 239 .get("target") 240 .or_else(|| args.get("target_content")) 241 .or_else(|| args.get("TargetContent")) 242 .and_then(Value::as_str) 243 .unwrap_or(""); 244 let replacement = args 245 .get("replacement") 246 .or_else(|| args.get("replacement_content")) 247 .or_else(|| args.get("ReplacementContent")) 248 .and_then(Value::as_str) 249 .unwrap_or(""); 250 let intent = args 251 .get("intent") 252 .and_then(Value::as_str) 253 .unwrap_or("Editing file content"); 254 let vector = args 255 .get("vector") 256 .and_then(Value::as_str) 257 .unwrap_or("Next action"); 258 259 if is_secret_leak_path(path) { 260 ( 261 json!({"error": "REJECTED BY SOVEREIGN VAULT POLICY: Modifying .env or secret files on disk is strictly forbidden. Use atlas-vault."}), 262 false, 263 ) 264 } else if let Some(reason) = contains_unmasked_secret(replacement) { 265 ( 266 json!({"error": format!("REJECTED BY SOVEREIGN VAULT POLICY: {}. Never commit or write plaintext keys into files. Use 'atlas-vault add '.", reason)}), 267 false, 268 ) 269 } else { 270 recorded_write("replace_file_content", path, |held| { 271 exec_replace_file(held, target, replacement, intent, vector) 272 }) 273 } 274 } 275 "list_dir" | "list_directory" => { 276 let path = args 277 .get("path") 278 .or_else(|| args.get("directory_path")) 279 .or_else(|| args.get("DirectoryPath")) 280 .and_then(Value::as_str) 281 .unwrap_or("."); 282 exec_list_dir(path) 283 } 284 "grep_search" | "search_directory" => { 285 let query = args 286 .get("query") 287 .or_else(|| args.get("Query")) 288 .and_then(Value::as_str) 289 .unwrap_or(""); 290 let path = args 291 .get("path") 292 .or_else(|| args.get("search_path")) 293 .or_else(|| args.get("SearchPath")) 294 .and_then(Value::as_str) 295 .unwrap_or("."); 296 exec_grep_search(query, path) 297 } 298 "find_by_name" | "find_file" => { 299 let path = args 300 .get("path") 301 .or_else(|| args.get("search_directory")) 302 .or_else(|| args.get("SearchDirectory")) 303 .and_then(Value::as_str) 304 .unwrap_or("."); 305 let pattern = args 306 .get("pattern") 307 .or_else(|| args.get("name")) 308 .or_else(|| args.get("Pattern")) 309 .and_then(Value::as_str) 310 .unwrap_or("*"); 311 exec_find_by_name(path, pattern) 312 } 313 "ask_question" => { 314 let q = args.get("question").and_then(Value::as_str).unwrap_or(""); 315 let options = args.get("options").and_then(Value::as_array); 316 exec_ask_question(q, options) 317 } 318 "create_dir" => { 319 let path = args.get("path").and_then(Value::as_str).unwrap_or(""); 320 let purpose = args 321 .get("purpose") 322 .and_then(Value::as_str) 323 .unwrap_or("Workspace directory"); 324 let lifecycle = args.get("lifecycle").and_then(Value::as_str); 325 exec_create_dir(path, purpose, lifecycle) 326 } 327 "crumb" => exec_crumb_tool(args), 328 "skill" | "skills" => (crate::skills::skills_dispatch_tool(args), true), 329 "context7" => { 330 let res = crate::context7::context7_dispatch_tool(args); 331 let ok = res.get("status").and_then(Value::as_str) == Some("ok"); 332 (res, ok) 333 } 334 "goal" => goal_tool_result(crate::goals::goals_dispatch_tool(args)), 335 "cortex" => { 336 let res = tokio::task::block_in_place(|| { 337 tokio::runtime::Handle::current() 338 .block_on(crate::cortex::cortex_dispatch_tool(args)) 339 }); 340 (res, true) 341 } 342 "vault" => (vault_dispatch_tool(args), true), 343 "walkthrough" => { 344 let action = args 345 .get("action") 346 .and_then(Value::as_str) 347 .unwrap_or("render"); 348 if action == "save" { 349 let platform = crate::platform::PlatformContext::detect(); 350 let dest = platform.home_dir.join("basecamp/WALKTHROUGH.md"); 351 match crate::walkthrough::generate_and_save_walkthrough_md(&dest) { 352 Ok(msg) => ( 353 json!({"status": "ok", "message": msg, "path": &dest.display().to_string()}), 354 true, 355 ), 356 Err(e) => (json!({"error": e}), false), 357 } 358 } else { 359 let card = crate::walkthrough::render_walkthrough_tui(); 360 (json!({"status": "ok", "walkthrough": card}), true) 361 } 362 } 363 "hive" => (crate::hive::hive_dispatch_tool(args), true), 364 "socratic" | "socratic_inquiry" => { 365 let question = args 366 .get("question") 367 .or_else(|| args.get("inquiry")) 368 .and_then(Value::as_str) 369 .unwrap_or(""); 370 let parent_id = args.get("parent_id").and_then(Value::as_str); 371 if question.is_empty() { 372 (json!({"error": "Socratic question cannot be empty"}), false) 373 } else { 374 match spark_hive::CombStore::open_default() { 375 Ok(store) => { 376 match spark_hive::emit_socratic_comb(&store, question, parent_id) { 377 Ok(comb) => ( 378 json!({ 379 "status": "emitted", 380 "comb_id": comb.id, 381 "q": comb.q, 382 "r": comb.r, 383 "role": "socratic", 384 "intent": "branch", 385 "question": question, 386 "message": "Socratic comb placed on hexagonal honeycomb lattice" 387 }), 388 true, 389 ), 390 Err(e) => (json!({"error": e.to_string()}), false), 391 } 392 } 393 Err(e) => ( 394 json!({"error": format!("Failed to open hive database: {}", e)}), 395 false, 396 ), 397 } 398 } 399 } 400 "adapter" | "model_adapter" | "model_adapters" => (adapter_dispatch_tool(args), true), 401 "sandbox" => (crate::sandbox::sandbox_dispatch_tool(args), true), 402 "browser" => { 403 let action = args.get("action").and_then(Value::as_str).unwrap_or("test"); 404 let prompt = args.get("prompt").and_then(Value::as_str); 405 (crate::sandbox::browser_dispatch_tool(action, prompt), true) 406 } 407 "invoke_subagent" => { 408 let role = args 409 .get("role") 410 .and_then(Value::as_str) 411 .unwrap_or("Subagent"); 412 let prompt = args.get("prompt").and_then(Value::as_str).unwrap_or(""); 413 let res = tokio::task::block_in_place(|| { 414 tokio::runtime::Handle::current() 415 .block_on(crate::subagents::invoke_subagent_from_root(role, prompt)) 416 }); 417 subagent_tool_result(res) 418 } 419 "subagent" | "subagents" => { 420 let action = args.get("action").and_then(Value::as_str).unwrap_or("list"); 421 match action { 422 "list" => (crate::subagents::list_subagents(), true), 423 "view" => { 424 let id = args.get("id").and_then(Value::as_str).unwrap_or(""); 425 (crate::subagents::view_subagent(id), true) 426 } 427 _ => ( 428 json!({"error": format!("Unknown subagent action: {}", action)}), 429 false, 430 ), 431 } 432 } 433 other => (json!({"error": format!("Unknown tool: {}", other)}), false), 434 }; 435 436 // 3. Lifecycle Post-tool Hook 437 let mut final_res = res; 438 let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry(); 439 tokio::task::block_in_place(|| { 440 tokio::runtime::Handle::current().block_on(hook_registry.run_post_tool( 441 name, 442 args, 443 &mut final_res, 444 )) 445 }); 446 447 // 4. Lifecycle On-tool-error Hook 448 if !success { 449 if let Some(err_str) = final_res.get("error").and_then(Value::as_str) { 450 let recovery = tokio::task::block_in_place(|| { 451 tokio::runtime::Handle::current() 452 .block_on(hook_registry.run_on_tool_error(name, args, err_str)) 453 }); 454 if let Some(rec) = recovery { 455 final_res = rec; 456 } 457 } 458 } 459 460 let _ = record_effect_receipt(name, args, &final_res, success); 461 462 let elapsed = start.elapsed().as_millis(); 463 print_tool_done(name, elapsed, success); 464 final_res 465 } 466 467 fn goal_tool_result(result: Value) -> (Value, bool) { 468 let success = result["status"].as_str() == Some("ok"); 469 (result, success) 470 } 471 472 pub(crate) fn subagent_tool_result(res: Value) -> (Value, bool) { 473 let success = res.get("status").and_then(Value::as_str) == Some("completed"); 474 (res, success) 475 } 476 477 /// Persist a content-addressed, secret-free receipt for every tool effect. 478 /// Arguments and results are hashed, never copied into the receipt. 479 /// Writes one effect receipt under `$AIEN_PROVENANCE_DIR` and returns its path 480 /// (None when it could not be written). NEXT-PHASE-1 `aien compose` cites the 481 /// returned file by its sha256. 482 pub(crate) fn record_effect_receipt( 483 tool: &str, 484 args: &Value, 485 result: &Value, 486 success: bool, 487 ) -> Option { 488 let digest = |value: &Value| { 489 let bytes = serde_json::to_vec(value).unwrap_or_default(); 490 format!("sha256:{}", hex::encode(Sha256::digest(bytes))) 491 }; 492 let receipt = json!({ 493 "version": 1, 494 "tool": tool, 495 "success": success, 496 "arguments_digest": digest(args), 497 "result_digest": digest(result), 498 "policy": "default_sovereign_engine", 499 "timestamp": chrono::Utc::now().to_rfc3339(), 500 }); 501 let dir = aien_runtime::objective::provenance_root(); 502 if std::fs::create_dir_all(&dir).is_err() { 503 return None; 504 } 505 let id = format!( 506 "{}-{}", 507 chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(), 508 std::process::id() 509 ); 510 let path = dir.join(format!("{}.json", id)); 511 let bytes = serde_json::to_vec_pretty(&receipt).ok()?; 512 std::fs::write(&path, bytes).ok()?; 513 Some(path) 514 } 515 516 fn validate_tool_path(path: &str) -> Result { 517 crate::safety::validate_workspace_path(path, &crate::fs_bind::permitted_workspaces()) 518 } 519 520 fn bind_err(err: crate::fs_bind::BindError) -> (Value, bool) { 521 let denied = matches!(err, crate::fs_bind::BindError::Denied(_)); 522 let msg = err.message().to_string(); 523 if denied { 524 ( 525 json!({"error": format!("CONFINEMENT DENIAL: {msg}")}), 526 false, 527 ) 528 } else { 529 (json!({"error": msg}), false) 530 } 531 } 532 533 fn exec_command(cmd: &str, cwd: &str) -> (Value, bool) { 534 exec_command_in(cmd, cwd, Duration::from_secs(120)) 535 } 536 537 fn exec_command_in(cmd: &str, cwd: &str, timeout: Duration) -> (Value, bool) { 538 let canon = match validate_tool_path(cwd) { 539 Ok(path) => path, 540 Err(err) => { 541 return ( 542 json!({"error": format!("CONFINEMENT DENIAL: Invalid command working directory: {}", err)}), 543 false, 544 ); 545 } 546 }; 547 548 let mut command = Command::new("bash"); 549 command 550 .args(["-c", cmd]) 551 .current_dir(&canon) 552 .env_clear() 553 .stdin(Stdio::null()) 554 .stdout(Stdio::piped()) 555 .stderr(Stdio::piped()); 556 for key in ["PATH", "HOME", "LANG", "TERM"] { 557 if let Ok(value) = std::env::var(key) { 558 command.env(key, value); 559 } 560 } 561 // New session so the process group id is the child pid. A later 562 // `kill(-pid)` reaches grandchildren that stayed in that group. 563 unsafe { 564 command.pre_exec(|| { 565 if libc::setsid() == -1 { 566 Err(std::io::Error::last_os_error()) 567 } else { 568 Ok(()) 569 } 570 }); 571 } 572 let mut child = match command.spawn() { 573 Ok(child) => child, 574 Err(e) => return (json!({"error": e.to_string()}), false), 575 }; 576 let pgid = child.id(); 577 let deadline = Instant::now() + timeout; 578 let stop = Arc::new(AtomicBool::new(false)); 579 let out = child.stdout.take(); 580 let err = child.stderr.take(); 581 let out_stop = Arc::clone(&stop); 582 let stdout_thread = std::thread::spawn(move || match out { 583 Some(pipe) => read_until(pipe, deadline, &out_stop), 584 None => Vec::new(), 585 }); 586 let err_stop = Arc::clone(&stop); 587 let stderr_thread = std::thread::spawn(move || match err { 588 Some(pipe) => read_until(pipe, deadline, &err_stop), 589 None => Vec::new(), 590 }); 591 let status = loop { 592 match child.try_wait() { 593 Ok(Some(status)) => { 594 kill_command_group(pgid); 595 break Some(status); 596 } 597 Ok(None) if Instant::now() >= deadline => { 598 kill_command_group(pgid); 599 let _ = child.wait(); 600 stop.store(true, Ordering::Release); 601 let _ = stdout_thread.join(); 602 let _ = stderr_thread.join(); 603 return ( 604 json!({"error": format!("Command timed out after {:.3} seconds", timeout.as_secs_f64())}), 605 false, 606 ); 607 } 608 Ok(None) => std::thread::sleep(Duration::from_millis(20)), 609 Err(e) => { 610 kill_command_group(pgid); 611 let _ = child.wait(); 612 stop.store(true, Ordering::Release); 613 let _ = stdout_thread.join(); 614 let _ = stderr_thread.join(); 615 return (json!({"error": e.to_string()}), false); 616 } 617 } 618 }; 619 // A `setsid` grandchild is outside the killed group and can hold the 620 // pipes open. After a short grace the readers take only buffered output. 621 let grace = (Instant::now() + DRAIN_AFTER_EXIT).min(deadline); 622 while !(stdout_thread.is_finished() && stderr_thread.is_finished()) && Instant::now() < grace { 623 std::thread::sleep(Duration::from_millis(10)); 624 } 625 stop.store(true, Ordering::Release); 626 let stdout = String::from_utf8_lossy(&stdout_thread.join().unwrap_or_default()).into_owned(); 627 let stderr = String::from_utf8_lossy(&stderr_thread.join().unwrap_or_default()).into_owned(); 628 let code = status.map(|s| s.code().unwrap_or(-1)).unwrap_or(-1); 629 let success = status.map(|s| s.success()).unwrap_or(false); 630 ( 631 json!({ 632 "exit_code": code, 633 "stdout": redact_secrets(&stdout), 634 "stderr": redact_secrets(&stderr) 635 }), 636 success, 637 ) 638 } 639 640 /// How long the readers may wait for more output after the leader exited. 641 const DRAIN_AFTER_EXIT: Duration = Duration::from_millis(500); 642 643 /// Longest single poll, so a reader notices `stop` promptly. 644 const POLL_SLICE_MS: i32 = 50; 645 646 fn read_until( 647 mut reader: impl std::io::Read + AsRawFd, 648 deadline: Instant, 649 stop: &AtomicBool, 650 ) -> Vec { 651 let fd = reader.as_raw_fd(); 652 let flags = unsafe { libc::fcntl(fd, libc::F_GETFL, 0) }; 653 if flags >= 0 { 654 unsafe { 655 libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK); 656 } 657 } 658 let mut buf = Vec::new(); 659 let mut tmp = [0u8; 8192]; 660 loop { 661 match reader.read(&mut tmp) { 662 Ok(0) => return buf, 663 Ok(n) => buf.extend_from_slice(&tmp[..n]), 664 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, 665 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { 666 if !wait_fd(fd, deadline, stop) { 667 return buf; 668 } 669 } 670 Err(_) => return buf, 671 } 672 } 673 } 674 675 /// Wait for input in slices of at most [`POLL_SLICE_MS`]. Once `stop` is 676 /// set, one zero-timeout poll reports whether data is already buffered. 677 fn wait_fd(fd: i32, deadline: Instant, stop: &AtomicBool) -> bool { 678 loop { 679 let stopping = stop.load(Ordering::Acquire); 680 let now = Instant::now(); 681 if now >= deadline { 682 return false; 683 } 684 let wait_ms = if stopping { 685 0 686 } else { 687 deadline 688 .saturating_duration_since(now) 689 .as_millis() 690 .clamp(1, POLL_SLICE_MS as u128) as i32 691 }; 692 let mut pfd = libc::pollfd { 693 fd, 694 events: libc::POLLIN, 695 revents: 0, 696 }; 697 let rc = unsafe { libc::poll(&mut pfd, 1, wait_ms) }; 698 if rc > 0 { 699 return true; 700 } 701 if rc == 0 && stopping { 702 return false; 703 } 704 if rc < 0 && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted { 705 return false; 706 } 707 } 708 } 709 710 fn kill_command_group(pgid: u32) { 711 if pgid == 0 { 712 return; 713 } 714 unsafe { 715 libc::kill(-(pgid as i32), libc::SIGKILL); 716 } 717 } 718 719 fn exec_view_file(path: &str, start_line: usize, end_line: usize) -> (Value, bool) { 720 let (authorized, content) = match crate::fs_bind::read_text(path) { 721 Ok(v) => v, 722 Err(err) => return bind_err(err), 723 }; 724 let p = authorized.as_path(); 725 // Sniff directory breadcrumbs on the authorized file, after the read. 726 let mut notes = CrumbNotes::default(); 727 notes.sniff(p); 728 729 // Record view in directory crumb 730 notes.record(p, "view", "Inspected file lines", ""); 731 732 let finish = |content: String| { 733 let lines: Vec<&str> = content.lines().collect(); 734 let total_lines = lines.len(); 735 let start = if start_line > 0 { start_line - 1 } else { 0 }; 736 let end = std::cmp::min(end_line, total_lines); 737 738 if start >= total_lines && total_lines > 0 { 739 return ( 740 json!({"error": "start_line exceeds file length", "total_lines": total_lines}), 741 false, 742 ); 743 } 744 745 let slice = &lines[start..end]; 746 let numbered: Vec = slice 747 .iter() 748 .enumerate() 749 .map(|(idx, line)| { 750 let redacted = redact_secrets(line); 751 format!("{}: {}", start + idx + 1, redacted) 752 }) 753 .collect(); 754 755 let mut resp = json!({ 756 "path": path, 757 "lines": numbered.join("\n"), 758 "total_lines": total_lines 759 }); 760 761 notes.apply(&mut resp); 762 763 (resp, true) 764 }; 765 finish(content) 766 } 767 768 /// Run the approval gate for one request. `Err` carries the tool result to 769 /// hand back to the model when the request does not run. 770 fn gate_tool( 771 name: &str, 772 args: &Value, 773 summary: &str, 774 ctx: &crate::approval::GateContext, 775 ) -> Result<(), Value> { 776 use crate::approval::{after_guardian, decide, Gate, Verdict}; 777 let base = crate::safety::SafetyEngine::default_sovereign_engine().evaluate(name, args); 778 let mut verdict = decide(&Gate { 779 tool: name, 780 args, 781 base: &base, 782 mode: ctx.mode, 783 presence: ctx.presence, 784 policy: &ctx.policy, 785 facts: &ctx.facts, 786 guardian_ready: crate::approval::guardian_ready(), 787 }); 788 if let Verdict::AskGuardian { reason } = verdict { 789 let answer = ask_guardian(name, summary, &reason); 790 crate::approval::record_guardian(&answer); 791 verdict = after_guardian(&answer, reason); 792 } 793 match verdict { 794 Verdict::Allow { .. } => Ok(()), 795 Verdict::Deny { by, reason } => Err(json!({ 796 "error": format!("SECURITY DENIAL [{:?}]: {}", by, reason) 797 })), 798 Verdict::AskGuardian { .. } => unreachable!("guardian answered above"), 799 Verdict::AskPerson { reason } => { 800 println!("{}", format!("⚠️ SAFETY GATE: {}", reason).yellow().bold()); 801 if print_safety_prompt(&format!("Tool: '{}' with summary: '{}'", name, summary)) { 802 Ok(()) 803 } else { 804 Err(json!({"error": "Operation aborted by operator safety gate"})) 805 } 806 } 807 } 808 } 809 810 /// Ask the guardian model (smart mode). Any transport failure, timeout or 811 /// unparseable reply is `Failed`, which escalates to the person and counts 812 /// against the breaker. 813 fn ask_guardian(name: &str, summary: &str, reason: &str) -> crate::approval::GuardianAnswer { 814 use crate::approval::GuardianAnswer; 815 let Ok(handle) = tokio::runtime::Handle::try_current() else { 816 return GuardianAnswer::Failed("no async runtime for the guardian".into()); 817 }; 818 let messages = vec![ 819 json!({"role": "system", "content": crate::approval::GUARDIAN_PROMPT}), 820 json!({"role": "user", "content": format!( 821 "tool: {name}\nrequest: {}\nflagged because: {reason}", 822 redact_secrets(summary) 823 )}), 824 ]; 825 let client = crate::client::ChatClient::new(None, None); 826 let reply = tokio::task::block_in_place(|| { 827 handle.block_on(client.stream_turn_with_limit(&messages, false, 32)) 828 }); 829 match reply { 830 Ok(text) => crate::approval::parse_guardian_reply(&text), 831 Err(err) => GuardianAnswer::Failed(err), 832 } 833 } 834 835 /// Run a file tool's write as a recorded agent write (sc#667): prior content 836 /// kept, one ledger line after. Without an active chat session this is a 837 /// plain call. 838 fn recorded_write( 839 tool: &str, 840 path: &str, 841 write: impl FnOnce(&crate::fs_bind::HeldFile) -> (Value, bool), 842 ) -> (Value, bool) { 843 // Pin the authorized file before checkpointing. A refusal here must not 844 // snapshot the directory or run the write. Checkpoint bytes are read back 845 // through the same descriptor the write uses. 846 let held = match crate::fs_bind::hold_for_write(path) { 847 Ok(held) => std::sync::Arc::new(held), 848 Err(err) => return bind_err(err), 849 }; 850 let target = held.authorized().to_path_buf(); 851 let reader = std::sync::Arc::clone(&held); 852 let editor = std::sync::Arc::clone(&held); 853 match crate::checkpoint::record_agent_write_with_reader( 854 &target, 855 tool, 856 move || reader.read_checkpoint(), 857 move || write(editor.as_ref()), 858 ) { 859 Ok(((mut res, ok), warning)) => { 860 if let (Some(w), Some(obj)) = (warning, res.as_object_mut()) { 861 obj.insert("checkpoint_warning".into(), json!(w)); 862 } 863 (res, ok) 864 } 865 Err(refusal) => (json!({"error": refusal}), false), 866 } 867 } 868 869 fn exec_write_file( 870 held: &crate::fs_bind::HeldFile, 871 content: &str, 872 overwrite: bool, 873 intent: &str, 874 vector: &str, 875 ) -> (Value, bool) { 876 let created_parent = match held.write_bytes(content.as_bytes(), overwrite) { 877 Ok(created) => created, 878 Err(err) => return bind_err(err), 879 }; 880 let p = held.authorized(); 881 let mut crumb_error = None; 882 if created_parent { 883 if let Some(parent) = p.parent() { 884 let file_name = p 885 .file_name() 886 .map(|n| n.to_string_lossy().to_string()) 887 .unwrap_or_default(); 888 let (created_by, session_id) = purpose_author(); 889 let parent_purpose = CrumbPurpose { 890 statement: format!("Auto-created to house file: {}", file_name), 891 created_by, 892 session_id, 893 created_at: Utc::now().to_rfc3339(), 894 lifecycle: "permanent".to_string(), 895 }; 896 let crumb = load_or_init_dir_crumb(parent, Some(parent_purpose)); 897 crumb_error = save_dir_crumb(parent, &crumb).err(); 898 } 899 } 900 901 let mut notes = CrumbNotes::default(); 902 notes.sniff(p); 903 notes.record(p, "write", intent, vector); 904 905 let mut resp = json!({ 906 "status": "ok", 907 "path": held.display(), 908 "bytes": content.len() 909 }); 910 notes.apply(&mut resp); 911 if let Some(err) = crumb_error { 912 resp["crumb_error"] = json!(err); 913 } 914 (resp, true) 915 } 916 917 fn exec_replace_file( 918 held: &crate::fs_bind::HeldFile, 919 target: &str, 920 replacement: &str, 921 intent: &str, 922 vector: &str, 923 ) -> (Value, bool) { 924 let content = match held.read_checkpoint() { 925 Ok(Some(bytes)) => match String::from_utf8(bytes) { 926 Ok(text) => text, 927 Err(_) => { 928 return ( 929 json!({"error": "stream did not contain valid UTF-8"}), 930 false, 931 ) 932 } 933 }, 934 Ok(None) => { 935 return ( 936 json!({"error": "No such file or directory (os error 2)"}), 937 false, 938 ) 939 } 940 Err(err) => return (json!({"error": err}), false), 941 }; 942 let p = held.authorized(); 943 let mut notes = CrumbNotes::default(); 944 notes.sniff(p); 945 if !content.contains(target) { 946 return (json!({"error": "target string not found in file"}), false); 947 } 948 let count = content.matches(target).count(); 949 if count > 1 { 950 return ( 951 json!({"error": format!("target string occurred {} times, must be unique", count)}), 952 false, 953 ); 954 } 955 let updated = content.replace(target, replacement); 956 if let Err(err) = held.overwrite_existing(updated.as_bytes()) { 957 return bind_err(err); 958 } 959 notes.record(p, "edit", intent, vector); 960 let mut resp = json!({ 961 "status": "ok", 962 "path": held.display(), 963 "replaced": true 964 }); 965 notes.apply(&mut resp); 966 (resp, true) 967 } 968 969 fn exec_list_dir(path: &str) -> (Value, bool) { 970 let (authorized, entries) = match crate::fs_bind::list_dir(path) { 971 Ok(v) => v, 972 Err(err) => return bind_err(err), 973 }; 974 let crumb_overview = format_dir_crumb_tui(&authorized); 975 let list: Vec = entries 976 .into_iter() 977 .map(|entry| { 978 json!({ 979 "name": entry.name, 980 "is_dir": entry.is_dir, 981 "size_bytes": entry.size_bytes 982 }) 983 }) 984 .collect(); 985 ( 986 json!({ 987 "path": path, 988 "entries": list, 989 "directory_crumb": crumb_overview 990 }), 991 true, 992 ) 993 } 994 995 fn exec_grep_search(query: &str, path: &str) -> (Value, bool) { 996 match crate::fs_bind::grep_search(path, query, 50) { 997 Ok(raw) => { 998 let matches: Vec = raw.into_iter().map(|line| redact_secrets(&line)).collect(); 999 ( 1000 json!({ 1001 "query": query, 1002 "matches": matches, 1003 "count": matches.len() 1004 }), 1005 true, 1006 ) 1007 } 1008 Err(err) => bind_err(err), 1009 } 1010 } 1011 1012 fn exec_crumb_tool(args: &Value) -> (Value, bool) { 1013 let action = args 1014 .get("action") 1015 .and_then(Value::as_str) 1016 .unwrap_or("survey"); 1017 let path_str = args.get("path").and_then(Value::as_str).unwrap_or("."); 1018 let target = Path::new(path_str); 1019 // A file names its directory. The binder authorizes that directory before 1020 // any crumb read or write, the same way the other file tools bind their 1021 // path; only `init` may create it, beneath the workspace (DRA-47). 1022 let named_dir = if target.is_dir() { 1023 target 1024 } else { 1025 match target.parent() { 1026 Some(parent) if !parent.as_os_str().is_empty() => parent, 1027 _ => Path::new("."), 1028 } 1029 }; 1030 let named_dir = named_dir.to_string_lossy(); 1031 let bound = match action { 1032 "init" => crate::fs_bind::make_dir(&named_dir), 1033 "survey" | "whisper" | "record" => crate::fs_bind::list_dir(&named_dir).map(|(d, _)| d), 1034 other => { 1035 return ( 1036 json!({"error": format!("Unknown crumb action: {}", other)}), 1037 false, 1038 ) 1039 } 1040 }; 1041 let dir = match bound { 1042 Ok(dir) => dir, 1043 Err(err) => return bind_err(err), 1044 }; 1045 1046 match action { 1047 "survey" => { 1048 let view = format_dir_crumb_tui(&dir); 1049 (json!({"status": "ok", "crumb_view": view}), true) 1050 } 1051 "whisper" => { 1052 let msg = args.get("message").and_then(Value::as_str).unwrap_or(""); 1053 let target_file = args.get("target_file").and_then(Value::as_str); 1054 // The whisper is the requested effect here, so a failed write is 1055 // the tool's failure, never an "ok". 1056 if let Err(err) = whisper_as_self(&dir, target_file, msg) { 1057 return ( 1058 json!({"error": format!("whisper not recorded: {err}")}), 1059 false, 1060 ); 1061 } 1062 ( 1063 json!({"status": "ok", "message": "Whisper recorded to directory .crumb.local"}), 1064 true, 1065 ) 1066 } 1067 "init" => { 1068 let purpose_str = args 1069 .get("purpose") 1070 .and_then(Value::as_str) 1071 .unwrap_or("Workspace directory"); 1072 let lifecycle = args 1073 .get("lifecycle") 1074 .and_then(Value::as_str) 1075 .unwrap_or("permanent"); 1076 let (created_by, session_id) = purpose_author(); 1077 let purpose_obj = CrumbPurpose { 1078 statement: purpose_str.to_string(), 1079 created_by, 1080 session_id, 1081 created_at: Utc::now().to_rfc3339(), 1082 lifecycle: lifecycle.to_string(), 1083 }; 1084 let mut crumb = load_or_init_dir_crumb(&dir, Some(purpose_obj)); 1085 crumb.description = purpose_str.to_string(); 1086 if let Err(err) = save_dir_crumb(&dir, &crumb) { 1087 return (json!({"error": err}), false); 1088 } 1089 ( 1090 json!({"status": "ok", "message": format!("Initialized .crumb with purpose for {named_dir}")}), 1091 true, 1092 ) 1093 } 1094 _ => { 1095 let intent = args 1096 .get("intent") 1097 .and_then(Value::as_str) 1098 .unwrap_or("Working in directory"); 1099 let vector = args 1100 .get("vector") 1101 .and_then(Value::as_str) 1102 .unwrap_or("Next milestone"); 1103 // Record against the named file when there is one, inside the 1104 // authorized directory. 1105 let recorded = match target.file_name() { 1106 Some(name) if !target.is_dir() => dir.join(name), 1107 _ => dir, 1108 }; 1109 if let Err(err) = record_as_self(&recorded, "record", intent, vector) { 1110 return ( 1111 json!({"error": format!("crumb not recorded: {err}")}), 1112 false, 1113 ); 1114 } 1115 ( 1116 json!({"status": "ok", "message": "Directory crumb recorded"}), 1117 true, 1118 ) 1119 } 1120 } 1121 } 1122 1123 fn exec_create_dir(path: &str, purpose: &str, lifecycle: Option<&str>) -> (Value, bool) { 1124 if path.is_empty() { 1125 return (json!({"error": "Path cannot be empty"}), false); 1126 } 1127 let authorized = match crate::fs_bind::make_dir(path) { 1128 Ok(p) => p, 1129 Err(err) => return bind_err(err), 1130 }; 1131 let p = authorized.as_path(); 1132 1133 let (created_by, session_id) = purpose_author(); 1134 let purpose_obj = CrumbPurpose { 1135 statement: purpose.to_string(), 1136 created_by, 1137 session_id, 1138 created_at: Utc::now().to_rfc3339(), 1139 lifecycle: lifecycle.unwrap_or("permanent").to_string(), 1140 }; 1141 1142 let mut crumb = load_or_init_dir_crumb(p, Some(purpose_obj)); 1143 crumb.description = purpose.to_string(); 1144 let crumb_error = save_dir_crumb(p, &crumb).err(); 1145 1146 // Record scent mark into crumb 1147 let mut notes = CrumbNotes::default(); 1148 notes.record( 1149 p, 1150 "create_dir", 1151 purpose, 1152 "Directory initialized with purpose", 1153 ); 1154 1155 let crumb_overview = format_dir_crumb_tui(p); 1156 1157 let mut resp = json!({ 1158 "status": "ok", 1159 "path": path, 1160 "purpose": purpose, 1161 "crumb_created": crumb_error.is_none(), 1162 "directory_crumb": crumb_overview 1163 }); 1164 notes.apply(&mut resp); 1165 if let Some(err) = crumb_error { 1166 resp["crumb_error"] = json!(err); 1167 } 1168 (resp, true) 1169 } 1170 1171 pub fn adapter_dispatch_tool(args: &Value) -> Value { 1172 let action = args.get("action").and_then(Value::as_str).unwrap_or("list"); 1173 let target = args 1174 .get("target") 1175 .or_else(|| args.get("model")) 1176 .or_else(|| args.get("id")) 1177 .and_then(Value::as_str) 1178 .unwrap_or(""); 1179 let engine_str = args.get("engine").and_then(Value::as_str); 1180 let engine_override = engine_str.and_then(spark_hive::UpstreamEngine::from_name); 1181 1182 match action { 1183 "list" | "catalog" => { 1184 let adapters = spark_hive::get_catalog_adapters(); 1185 let models = spark_hive::ConsumerModel::all(); 1186 let engines = spark_hive::UpstreamEngine::all(); 1187 json!({ 1188 "status": "ok", 1189 "total_adapters": adapters.len(), 1190 "adapters": adapters, 1191 "models": models.iter().map(|m| json!({ 1192 "slug": m.slug(), 1193 "name": m.display_name(), 1194 "params_b": m.param_count_billions(), 1195 "hardware": m.hardware_profile().description(), 1196 "quantization": m.recommended_quantization(), 1197 })).collect::>(), 1198 "engines": engines.iter().map(|e| json!({ 1199 "repo": e.repo(), 1200 "language": e.primary_language(), 1201 "description": e.description(), 1202 })).collect::>() 1203 }) 1204 } 1205 "evaluate" | "socratic" => { 1206 if target.is_empty() { 1207 return json!({"error": "Target model or adapter id must be provided for evaluate"}); 1208 } 1209 let spec = spark_hive::find_or_create_adapter(target, engine_override); 1210 let Some(spec) = spec else { 1211 return json!({"error": format!("Model or adapter {} not found", target)}); 1212 }; 1213 let eval = spark_hive::evaluate_socratic_reflex(&spec.model, &spec.engine); 1214 json!({ 1215 "status": "ok", 1216 "target": spec.id, 1217 "model": spec.model.slug(), 1218 "engine": spec.engine.repo(), 1219 "evaluation": eval 1220 }) 1221 } 1222 "plan" | "pr" => { 1223 if target.is_empty() { 1224 return json!({"error": "Target model or adapter id must be provided for plan"}); 1225 } 1226 let spec = spark_hive::find_or_create_adapter(target, engine_override); 1227 let Some(spec) = spec else { 1228 return json!({"error": format!("Model or adapter {} not found", target)}); 1229 }; 1230 let socratic = spark_hive::evaluate_socratic_reflex(&spec.model, &spec.engine); 1231 let default_sb = crate::platform::PlatformContext::detect() 1232 .home_dir 1233 .join("workspace/aien-sandbox"); 1234 let default_sb_str = default_sb.to_string_lossy(); 1235 let sandbox_path = args 1236 .get("sandbox_path") 1237 .and_then(Value::as_str) 1238 .unwrap_or(&default_sb_str); 1239 let telem = spark_hive::BenchmarkTelemetry::estimate_for_model( 1240 &spec.model, 1241 &spec.engine, 1242 sandbox_path, 1243 None, 1244 ); 1245 let plan = spark_hive::generate_pr_plan(&spec, telem, socratic); 1246 json!({ 1247 "status": "ok", 1248 "plan": plan 1249 }) 1250 } 1251 "emit" => { 1252 if target.is_empty() { 1253 return json!({"error": "Target model or adapter id must be provided for emit"}); 1254 } 1255 let spec = spark_hive::find_or_create_adapter(target, engine_override); 1256 let Some(spec) = spec else { 1257 return json!({"error": format!("Model or adapter {} not found", target)}); 1258 }; 1259 let socratic = spark_hive::evaluate_socratic_reflex(&spec.model, &spec.engine); 1260 let default_sb = crate::platform::PlatformContext::detect() 1261 .home_dir 1262 .join("workspace/aien-sandbox"); 1263 let default_sb_str = default_sb.to_string_lossy(); 1264 let sandbox_path = args 1265 .get("sandbox_path") 1266 .and_then(Value::as_str) 1267 .unwrap_or(&default_sb_str); 1268 let telem = spark_hive::BenchmarkTelemetry::estimate_for_model( 1269 &spec.model, 1270 &spec.engine, 1271 sandbox_path, 1272 None, 1273 ); 1274 let plan = spark_hive::generate_pr_plan(&spec, telem, socratic); 1275 let parent_id = args.get("parent_id").and_then(Value::as_str); 1276 match spark_hive::CombStore::open_default() { 1277 Ok(store) => { 1278 match spark_hive::emit_adapter_pipeline_combs(&store, &plan, parent_id) { 1279 Ok(receipt) => json!({ 1280 "status": "emitted", 1281 "receipt": receipt, 1282 "plan": { 1283 "adapter_id": plan.adapter_id, 1284 "target_repo": plan.target_repo, 1285 "branch": plan.branch, 1286 "commit_message": plan.commit_message, 1287 "pr_title": plan.pr_title, 1288 } 1289 }), 1290 Err(e) => json!({"error": format!("Failed to emit combs: {}", e)}), 1291 } 1292 } 1293 Err(e) => json!({"error": format!("Failed to open hive database: {}", e)}), 1294 } 1295 } 1296 "chains" | "lattice" => match spark_hive::CombStore::open_default() { 1297 Ok(store) => match spark_hive::list_adapter_pipeline_chains(&store) { 1298 Ok(chains) => json!({ 1299 "status": "ok", 1300 "total_chains": chains.len(), 1301 "chains": chains 1302 }), 1303 Err(e) => json!({"error": format!("Failed to query chains: {}", e)}), 1304 }, 1305 Err(e) => json!({"error": format!("Failed to open hive database: {}", e)}), 1306 }, 1307 _ => { 1308 json!({"error": format!("Unknown adapter action {}. Valid actions: list, evaluate, plan, emit, chains", action)}) 1309 } 1310 } 1311 } 1312 1313 fn exec_find_by_name(path: &str, pattern: &str) -> (Value, bool) { 1314 match crate::fs_bind::find_names(path, pattern, 50) { 1315 Ok(raw) => { 1316 let matches: Vec = raw.into_iter().map(|line| redact_secrets(&line)).collect(); 1317 ( 1318 json!({ 1319 "path": path, 1320 "pattern": pattern, 1321 "matches": matches, 1322 "count": matches.len() 1323 }), 1324 true, 1325 ) 1326 } 1327 Err(err) => bind_err(err), 1328 } 1329 } 1330 1331 fn exec_ask_question(question: &str, options: Option<&Vec>) -> (Value, bool) { 1332 println!( 1333 "\n{}", 1334 format!("❓ Question from AIEN: {}", question) 1335 .yellow() 1336 .bold() 1337 ); 1338 if let Some(opts) = options { 1339 for (i, opt) in opts.iter().enumerate() { 1340 if let Some(opt_str) = opt.as_str() { 1341 println!(" {}. {}", i + 1, opt_str.cyan()); 1342 } 1343 } 1344 } 1345 print!("{}", "Your Answer ❯ ".cyan().bold()); 1346 let _ = std::io::stdout().flush(); 1347 let mut input = String::new(); 1348 let _ = std::io::stdin().read_line(&mut input); 1349 let trimmed = input.trim().to_string(); 1350 ( 1351 json!({ 1352 "status": "answered", 1353 "question": question, 1354 "answer": trimmed 1355 }), 1356 true, 1357 ) 1358 } 1359 1360 #[cfg(test)] 1361 mod tests { 1362 use super::*; 1363 1364 /// sc#813: every crumb action refuses a path that escapes the workspace 1365 /// allow-list through a symlink, and writes nothing on the other side. 1366 #[cfg(unix)] 1367 #[test] 1368 fn crumb_tool_refuses_a_symlink_escape_for_every_action() { 1369 use std::os::unix::fs::symlink; 1370 let outside = tempfile::tempdir_in("/var/tmp").unwrap(); 1371 let outside = outside.path().canonicalize().unwrap(); 1372 let work = tempfile::tempdir_in("/tmp").unwrap(); 1373 let work = work.path().canonicalize().unwrap(); 1374 let esc = work.join("esc"); 1375 symlink(&outside, &esc).unwrap(); 1376 let esc_s = esc.to_str().unwrap(); 1377 let fresh = esc.join("fresh"); 1378 let cases = [ 1379 json!({"action": "survey", "path": esc_s}), 1380 json!({"action": "whisper", "path": esc_s, "message": "m"}), 1381 json!({"action": "record", "path": esc_s}), 1382 json!({"action": "init", "path": esc_s}), 1383 json!({"action": "init", "path": fresh.join("x").to_str().unwrap()}), 1384 json!({"action": "whisper", "path": outside.to_str().unwrap(), "message": "m"}), 1385 ]; 1386 for args in cases { 1387 let (result, ok) = exec_crumb_tool(&args); 1388 assert!(!ok, "{args} was allowed: {result}"); 1389 assert!( 1390 result["error"] 1391 .as_str() 1392 .unwrap_or("") 1393 .contains("CONFINEMENT DENIAL"), 1394 "{args}: {result}" 1395 ); 1396 } 1397 let left: Vec<_> = std::fs::read_dir(&outside).unwrap().collect(); 1398 assert!(left.is_empty(), "wrote outside the workspace: {left:?}"); 1399 } 1400 1401 #[cfg(unix)] 1402 #[test] 1403 fn crumb_tool_init_creates_an_allowed_directory() { 1404 let work = tempfile::tempdir_in("/tmp").unwrap(); 1405 let work = work.path().canonicalize().unwrap(); 1406 let dir = work.join("a/b"); 1407 let target = dir.join("file.txt"); 1408 let (result, ok) = exec_crumb_tool( 1409 &json!({"action": "init", "path": target.to_str().unwrap(), "purpose": "p"}), 1410 ); 1411 assert!(ok, "{result}"); 1412 assert!(dir.is_dir()); 1413 assert!(dir.join(".crumb").exists()); 1414 } 1415 1416 #[test] 1417 fn round3_goal_tool_failure_flag_is_false() { 1418 for result in [ 1419 json!({"status":"error","error":"write goals failed"}), 1420 json!({"error":"denied"}), 1421 ] { 1422 assert!(!goal_tool_result(result).1); 1423 } 1424 assert!(goal_tool_result(json!({"status":"ok"})).1); 1425 } 1426 1427 // Tests that install the process-wide checkpoint session must serialize. 1428 static CHECKPOINT_SESSION_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); 1429 struct StopCheckpointSession; 1430 impl Drop for StopCheckpointSession { 1431 fn drop(&mut self) { 1432 crate::checkpoint::stop_session(); 1433 } 1434 } 1435 1436 #[cfg(unix)] 1437 #[test] 1438 fn denied_recorded_write_does_not_snapshot_or_invoke_write() { 1439 use std::os::unix::fs::symlink; 1440 let _serial = CHECKPOINT_SESSION_TEST 1441 .lock() 1442 .unwrap_or_else(|e| e.into_inner()); 1443 let _stop = StopCheckpointSession; 1444 let home = tempfile::tempdir().unwrap(); 1445 let work = tempfile::tempdir_in("/tmp").unwrap(); 1446 let work = work.path().canonicalize().unwrap(); 1447 std::fs::write(work.join("sentinel"), "SYNTHETIC_CHECKPOINT_SENTINEL").unwrap(); 1448 let denied = work.join("dangling"); 1449 symlink(work.join("absent-target"), &denied).unwrap(); 1450 crate::checkpoint::start_scoped_session(home.path(), "denied-path", work.clone()).unwrap(); 1451 crate::checkpoint::begin_turn(); 1452 let called = std::cell::Cell::new(false); 1453 let (result, ok) = recorded_write("write_to_file", denied.to_str().unwrap(), |_| { 1454 called.set(true); 1455 (json!({"error": "synthetic later denial"}), false) 1456 }); 1457 assert!(!ok); 1458 assert!(result["error"] 1459 .as_str() 1460 .unwrap() 1461 .contains("CONFINEMENT DENIAL")); 1462 assert!(!called.get(), "write closure ran before confinement denial"); 1463 let store = crate::checkpoint::store_root(home.path()); 1464 assert!( 1465 !store.join("objects").exists(), 1466 "denied write copied checkpoint content" 1467 ); 1468 assert!( 1469 !store.join("snapshots").exists(), 1470 "denied write created a snapshot" 1471 ); 1472 assert!( 1473 !store.join("ledger").exists(), 1474 "denied write created a ledger" 1475 ); 1476 assert!(!work.join("absent-target").exists()); 1477 } 1478 1479 #[cfg(unix)] 1480 #[test] 1481 fn recorded_write_checkpoint_uses_validated_target_identity() { 1482 use std::os::unix::fs::symlink; 1483 let _serial = CHECKPOINT_SESSION_TEST 1484 .lock() 1485 .unwrap_or_else(|e| e.into_inner()); 1486 let _stop = StopCheckpointSession; 1487 let home = tempfile::tempdir().unwrap(); 1488 let work = tempfile::tempdir_in("/tmp").unwrap(); 1489 let work = work.path().canonicalize().unwrap(); 1490 let target = work.join("target"); 1491 std::fs::write(&target, "before").unwrap(); 1492 let alias = work.join("alias"); 1493 symlink(&target, &alias).unwrap(); 1494 crate::checkpoint::start_scoped_session(home.path(), "canonical-target", work).unwrap(); 1495 crate::checkpoint::begin_turn(); 1496 let (_, ok) = recorded_write("write_to_file", alias.to_str().unwrap(), |_| { 1497 std::fs::write(&alias, "after").unwrap(); 1498 (json!({"status": "ok"}), true) 1499 }); 1500 assert!(ok); 1501 let store = 1502 crate::checkpoint::CheckpointStore::new(crate::checkpoint::store_root(home.path())); 1503 let (entries, _) = store.load_ledger("canonical-target").unwrap(); 1504 assert_eq!(entries.len(), 1); 1505 assert_eq!(entries[0].path, target.to_str().unwrap()); 1506 } 1507 1508 #[test] 1509 fn effect_receipt_is_hashed_and_secret_free() { 1510 let _env = crate::objective::PROVENANCE_ENV 1511 .lock() 1512 .unwrap_or_else(|e| e.into_inner()); 1513 let dir = tempfile::tempdir().unwrap(); 1514 std::env::set_var("AIEN_PROVENANCE_DIR", dir.path()); 1515 let _ = record_effect_receipt( 1516 "write_to_file", 1517 &json!({"path":"/tmp/receipt-test","content":"secret-value"}), 1518 &json!({"status":"ok"}), 1519 true, 1520 ); 1521 let entry = std::fs::read_dir(dir.path()) 1522 .unwrap() 1523 .next() 1524 .unwrap() 1525 .unwrap(); 1526 let text = std::fs::read_to_string(entry.path()).unwrap(); 1527 assert!(text.contains("arguments_digest")); 1528 assert!(!text.contains("secret-value")); 1529 std::env::remove_var("AIEN_PROVENANCE_DIR"); 1530 } 1531 1532 #[test] 1533 fn test_adapter_tool_dispatch_list() { 1534 let args = json!({"action": "list"}); 1535 let res = adapter_dispatch_tool(&args); 1536 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "ok"); 1537 assert!(res.get("adapters").unwrap().as_array().unwrap().len() >= 7); 1538 assert_eq!(res.get("models").unwrap().as_array().unwrap().len(), 9); 1539 } 1540 1541 #[test] 1542 fn test_adapter_tool_dispatch_evaluate() { 1543 let args = json!({"action": "evaluate", "target": "deepseek-r1-distill-qwen-7b"}); 1544 let res = adapter_dispatch_tool(&args); 1545 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "ok"); 1546 let eval = res.get("evaluation").unwrap(); 1547 assert!(eval.get("approved").unwrap().as_bool().unwrap()); 1548 } 1549 1550 #[test] 1551 fn test_adapter_tool_dispatch_plan() { 1552 let args = json!({"action": "plan", "target": "qwen2.5-coder-7b", "engine": "vllm"}); 1553 let res = adapter_dispatch_tool(&args); 1554 assert_eq!(res.get("status").unwrap().as_str().unwrap(), "ok"); 1555 let plan = res.get("plan").unwrap(); 1556 assert_eq!( 1557 plan.get("target_repo").unwrap().as_str().unwrap(), 1558 "vllm-project/vllm" 1559 ); 1560 assert!(plan 1561 .get("pr_script") 1562 .unwrap() 1563 .as_str() 1564 .unwrap() 1565 .contains("gh repo fork")); 1566 } 1567 1568 #[test] 1569 fn test_safety_engine_allows_adapter_and_socratic() { 1570 let safety = crate::safety::SafetyEngine::default_sovereign_engine(); 1571 let adapter_args = json!({"action": "list"}); 1572 let socratic_args = json!({"question": "Is local offline execution sovereign?"}); 1573 1574 assert_eq!( 1575 safety.evaluate("adapter", &adapter_args), 1576 crate::safety::SafetyDecision::Allow 1577 ); 1578 assert_eq!( 1579 safety.evaluate("socratic", &socratic_args), 1580 crate::safety::SafetyDecision::Allow 1581 ); 1582 } 1583 1584 #[test] 1585 fn test_path_confinement_in_tool_dispatch() { 1586 let bad_view = json!({"path": "/etc/shadow"}); 1587 let res = dispatch_tool("view_file", &bad_view); 1588 assert!(res 1589 .get("error") 1590 .unwrap() 1591 .as_str() 1592 .unwrap() 1593 .contains("CONFINEMENT DENIAL")); 1594 1595 let bad_write = json!({"path": "/usr/bin/evil_binary", "content": "malicious"}); 1596 let res = dispatch_tool("write_to_file", &bad_write); 1597 assert!(res 1598 .get("error") 1599 .unwrap() 1600 .as_str() 1601 .unwrap() 1602 .contains("CONFINEMENT DENIAL")); 1603 1604 let bad_cmd = json!({"command": "ls", "cwd": "/etc"}); 1605 let res = dispatch_tool("run_command", &bad_cmd); 1606 assert!(res 1607 .get("error") 1608 .unwrap() 1609 .as_str() 1610 .unwrap() 1611 .contains("CONFINEMENT DENIAL")); 1612 } 1613 1614 /// Every entry under `root`, symlinks not followed. 1615 #[cfg(unix)] 1616 fn tree(root: &Path) -> Vec { 1617 let mut out = Vec::new(); 1618 let mut stack = vec![root.to_path_buf()]; 1619 while let Some(dir) = stack.pop() { 1620 for entry in std::fs::read_dir(&dir).unwrap().flatten() { 1621 let path = entry.path(); 1622 if entry.file_type().unwrap().is_dir() { 1623 stack.push(path.clone()); 1624 } 1625 out.push(path); 1626 } 1627 } 1628 out.sort(); 1629 out 1630 } 1631 1632 /// DRA-47: the `crumb` tool creates directories and `.crumb` / 1633 /// `.crumb.local` files. Every action must go through the workspace 1634 /// binder: an absolute path, a `..` escape and a symlink escape out of a 1635 /// workspace are refused and leave the outside directory untouched. An 1636 /// in-workspace init and record still write (negative control). 1637 #[cfg(unix)] 1638 #[test] 1639 fn crumb_tool_writes_nothing_outside_the_workspace() { 1640 use std::os::unix::fs::symlink; 1641 let shm = std::path::PathBuf::from("/dev/shm"); 1642 assert!(shm.is_dir(), "/dev/shm is required for an unpermitted dir"); 1643 let outside = tempfile::tempdir_in(&shm).unwrap(); 1644 let out = outside.path().canonicalize().unwrap(); 1645 assert!( 1646 crate::safety::validate_workspace_path( 1647 out.to_str().unwrap(), 1648 &crate::fs_bind::permitted_workspaces() 1649 ) 1650 .is_err(), 1651 "outside dir is permitted; the test would not prove confinement" 1652 ); 1653 std::fs::create_dir(out.join("plain")).unwrap(); 1654 let ws_tmp = tempfile::tempdir_in("/tmp").unwrap(); 1655 let ws = ws_tmp.path().canonicalize().unwrap(); 1656 symlink(&out, ws.join("link")).unwrap(); 1657 let up = "../".repeat(ws.components().count() - 1); 1658 let dotdot = format!( 1659 "{}/{}{}/dotdot/leaf", 1660 ws.display(), 1661 up, 1662 out.strip_prefix("/").unwrap().display() 1663 ); 1664 let plain = out.join("plain").display().to_string(); 1665 let made = out.join("made/leaf").display().to_string(); 1666 let via_link = ws.join("link/viasym/leaf").display().to_string(); 1667 let link_dir = ws.join("link").display().to_string(); 1668 let escapes = [ 1669 json!({"action": "init", "path": made}), 1670 json!({"action": "init", "path": dotdot}), 1671 json!({"action": "init", "path": via_link}), 1672 json!({"action": "record", "path": plain}), 1673 json!({"action": "record", "path": link_dir}), 1674 json!({"action": "whisper", "path": plain, "message": "m"}), 1675 json!({"action": "whisper", "path": link_dir, "message": "m"}), 1676 json!({"action": "survey", "path": plain}), 1677 json!({"action": "survey", "path": link_dir}), 1678 ]; 1679 let runtime = tokio::runtime::Builder::new_multi_thread() 1680 .enable_all() 1681 .build() 1682 .unwrap(); 1683 runtime.block_on(async { 1684 let before = tree(&out); 1685 let mut escaped = Vec::new(); 1686 for args in &escapes { 1687 let res = dispatch_tool("crumb", args); 1688 let after = tree(&out); 1689 let err = res.get("error").and_then(Value::as_str).unwrap_or(""); 1690 if after != before || !err.contains("CONFINEMENT DENIAL") { 1691 let new: Vec<_> = after.iter().filter(|p| !before.contains(p)).collect(); 1692 escaped.push(format!("{args} -> {res}; created outside: {new:?}")); 1693 for p in new.iter().rev() { 1694 let _ = std::fs::remove_file(p).or_else(|_| std::fs::remove_dir(p)); 1695 } 1696 } 1697 } 1698 assert!( 1699 escaped.is_empty(), 1700 "{} of {} crumb calls escaped:\n{}", 1701 escaped.len(), 1702 escapes.len(), 1703 escaped.join("\n") 1704 ); 1705 1706 let inside = ws.join("ok/leaf").display().to_string(); 1707 let res = dispatch_tool("crumb", &json!({"action": "init", "path": inside})); 1708 assert!(res.get("error").is_none(), "in-workspace init: {res}"); 1709 assert!(ws.join("ok/.crumb").is_file(), "in-workspace init: {res}"); 1710 let ok_dir = ws.join("ok").display().to_string(); 1711 let res = dispatch_tool("crumb", &json!({"action": "record", "path": ok_dir})); 1712 assert!(res.get("error").is_none(), "in-workspace record: {res}"); 1713 assert!(ws.join("ok/.crumb.local").is_file(), "in-workspace record"); 1714 }); 1715 } 1716 1717 /// DRA-47: a `.crumb` or `.crumb.local` symlink planted in a workspace 1718 /// directory (say by a cloned repository) must not redirect a crumb read 1719 /// or write to its target outside the workspace. 1720 #[cfg(unix)] 1721 #[test] 1722 fn crumb_sidecar_symlink_is_not_followed() { 1723 use std::os::unix::fs::symlink; 1724 let outside = tempfile::tempdir_in("/dev/shm").unwrap(); 1725 let out = outside.path().canonicalize().unwrap(); 1726 let victim_crumb = out.join("victim-crumb"); 1727 let victim_local = out.join("victim-local"); 1728 std::fs::write(&victim_crumb, "VICTIM_CRUMB").unwrap(); 1729 std::fs::write(&victim_local, "VICTIM_LOCAL").unwrap(); 1730 let ws_tmp = tempfile::tempdir_in("/tmp").unwrap(); 1731 let ws = ws_tmp.path().canonicalize().unwrap(); 1732 let planted = ws.join("planted"); 1733 std::fs::create_dir(&planted).unwrap(); 1734 symlink(&victim_crumb, planted.join(".crumb")).unwrap(); 1735 symlink(&victim_local, planted.join(".crumb.local")).unwrap(); 1736 let dir = planted.display().to_string(); 1737 let runtime = tokio::runtime::Builder::new_multi_thread() 1738 .enable_all() 1739 .build() 1740 .unwrap(); 1741 runtime.block_on(async { 1742 let mut escaped = Vec::new(); 1743 for args in [ 1744 json!({"action": "init", "path": dir}), 1745 json!({"action": "record", "path": dir}), 1746 json!({"action": "whisper", "path": dir, "message": "m"}), 1747 json!({"action": "survey", "path": dir}), 1748 ] { 1749 let _ = dispatch_tool("crumb", &args); 1750 for (victim, marker) in [ 1751 (&victim_crumb, "VICTIM_CRUMB"), 1752 (&victim_local, "VICTIM_LOCAL"), 1753 ] { 1754 let now = std::fs::read_to_string(victim).unwrap(); 1755 if now != marker { 1756 escaped.push(format!("{args} rewrote {}", victim.display())); 1757 std::fs::write(victim, marker).unwrap(); 1758 } 1759 } 1760 } 1761 assert!( 1762 escaped.is_empty(), 1763 "crumb wrote through a planted sidecar symlink:\n{}", 1764 escaped.join("\n") 1765 ); 1766 }); 1767 } 1768 1769 #[test] 1770 fn test_policy_approved_write_reaches_effect_handler() { 1771 let runtime = tokio::runtime::Builder::new_multi_thread() 1772 .enable_all() 1773 .build() 1774 .unwrap(); 1775 runtime.block_on(async { 1776 let path = format!("/tmp/aien-policy-effect-{}", std::process::id()); 1777 let args = json!({"path": path, "content": "approved", "overwrite": true}); 1778 let result = dispatch_tool("write_to_file", &args); 1779 assert!( 1780 result.get("error").is_none(), 1781 "approved write failed: {result}" 1782 ); 1783 assert_eq!(std::fs::read_to_string(&path).unwrap(), "approved"); 1784 let _ = std::fs::remove_file(path); 1785 }); 1786 } 1787 1788 fn gate_ctx( 1789 mode: crate::approval::ApprovalMode, 1790 deny: &[&str], 1791 ) -> crate::approval::GateContext { 1792 use crate::approval::*; 1793 GateContext { 1794 mode, 1795 presence: Presence::Person, 1796 policy: CompiledPolicy::compile(&OperatorPolicy { 1797 mode: None, 1798 deny: deny.iter().map(|s| s.to_string()).collect(), 1799 allow: Vec::new(), 1800 }), 1801 facts: RuntimeFacts { 1802 protected: Vec::new(), 1803 home: std::path::PathBuf::from("/tmp"), 1804 cwd: std::path::PathBuf::from("/tmp"), 1805 }, 1806 } 1807 } 1808 1809 /// sc#667 acceptance through the real dispatcher: an operator deny 1810 /// pattern stops a real command in every mode; without the pattern the 1811 /// same command runs (negative control). 1812 #[test] 1813 fn operator_deny_pattern_blocks_a_real_command_in_every_mode() { 1814 let runtime = tokio::runtime::Builder::new_multi_thread() 1815 .enable_all() 1816 .build() 1817 .unwrap(); 1818 runtime.block_on(async { 1819 for mode in crate::approval::ALL_MODES { 1820 let dir = tempfile::Builder::new() 1821 .prefix("aien-sc667-deny-") 1822 .tempdir_in("/tmp") 1823 .unwrap(); 1824 let marker = dir.path().join("marker"); 1825 let args = json!({ 1826 "command": format!("touch {}", marker.display()), 1827 "cwd": dir.path().to_string_lossy(), 1828 }); 1829 let res = 1830 dispatch_tool_with("run_command", &args, &gate_ctx(mode, &[r"touch .*marker"])); 1831 let err = res.get("error").and_then(Value::as_str).unwrap_or(""); 1832 assert!(err.contains("OperatorDeny"), "{mode:?}: {res}"); 1833 assert!(!marker.exists(), "{mode:?}: command ran despite the floor"); 1834 1835 let res = dispatch_tool_with("run_command", &args, &gate_ctx(mode, &[])); 1836 let err = res.get("error").and_then(Value::as_str).unwrap_or(""); 1837 assert!( 1838 err.contains("aborted") || err.contains("SAFETY") || err.contains("approval"), 1839 "{mode:?}: bash -c ran with no person: {res}" 1840 ); 1841 assert!(!marker.exists(), "{mode:?}: command ran without approval"); 1842 } 1843 }); 1844 } 1845 1846 /// sc#667 acceptance through the real dispatcher: agent writes go to the 1847 /// ledger; a rollback after mixed operator and agent edits restores only 1848 /// the agent's files. 1849 #[test] 1850 fn rollback_through_the_dispatcher_spares_operator_edits() { 1851 let _serial = CHECKPOINT_SESSION_TEST 1852 .lock() 1853 .unwrap_or_else(|e| e.into_inner()); 1854 let _stop = StopCheckpointSession; 1855 let runtime = tokio::runtime::Builder::new_multi_thread() 1856 .enable_all() 1857 .build() 1858 .unwrap(); 1859 runtime.block_on(async { 1860 let home = tempfile::tempdir().unwrap(); 1861 let work = tempfile::Builder::new() 1862 .prefix("aien-sc667-work-") 1863 .tempdir_in("/tmp") 1864 .unwrap(); 1865 let work = work.path().canonicalize().unwrap(); 1866 let agent_file = work.join("agent.txt"); 1867 let created = work.join("created.txt"); 1868 let operator_file = work.join("operator.txt"); 1869 std::fs::write(&agent_file, "original").unwrap(); 1870 std::fs::write(&operator_file, "operator v0").unwrap(); 1871 1872 let session = format!("sc667-dispatch-{}", std::process::id()); 1873 crate::checkpoint::start_scoped_session(home.path(), &session, work.clone()).unwrap(); 1874 crate::checkpoint::begin_turn(); 1875 let ctx = gate_ctx(crate::approval::ApprovalMode::Manual, &[]); 1876 for (p, text) in [(&agent_file, "agent edit"), (&created, "agent new")] { 1877 let args = json!({"path": p.to_string_lossy(), "content": text, "overwrite": true}); 1878 let res = dispatch_tool_with("write_to_file", &args, &ctx); 1879 assert!(res.get("error").is_none(), "{res}"); 1880 } 1881 let args = json!({ 1882 "path": agent_file.to_string_lossy(), 1883 "target": "edit", 1884 "replacement": "edit twice", 1885 }); 1886 let res = dispatch_tool_with("replace_file_content", &args, &ctx); 1887 assert!(res.get("error").is_none(), "{res}"); 1888 crate::checkpoint::stop_session(); 1889 1890 std::fs::write(&operator_file, "operator v1").unwrap(); 1891 1892 let report = crate::checkpoint::rollback(home.path(), Some(1), Some(&session)).unwrap(); 1893 assert_eq!(std::fs::read_to_string(&agent_file).unwrap(), "original"); 1894 assert!(!created.exists()); 1895 assert_eq!( 1896 std::fs::read_to_string(&operator_file).unwrap(), 1897 "operator v1" 1898 ); 1899 assert!(report 1900 .spared 1901 .contains(&operator_file.to_string_lossy().into_owned())); 1902 }); 1903 } 1904 1905 #[test] 1906 fn run_command_in_manual_mode_requires_approval() { 1907 let ctx = gate_ctx(crate::approval::ApprovalMode::Manual, &[]); 1908 let res = dispatch_tool_with( 1909 "run_command", 1910 &json!({"command": "true", "cwd": "/tmp"}), 1911 &ctx, 1912 ); 1913 let err = res.get("error").and_then(Value::as_str).unwrap_or(""); 1914 assert!( 1915 err.contains("aborted") || err.contains("approval") || err.contains("SAFETY"), 1916 "{res}" 1917 ); 1918 } 1919 1920 #[test] 1921 fn command_child_does_not_inherit_the_parent_environment() { 1922 let key = "AIEN_ENV_PROBE_SECRET"; 1923 let value = "probe-value-not-for-the-child"; 1924 std::env::set_var(key, value); 1925 let (res, _) = exec_command_in(&format!("printenv {key}"), "/tmp", Duration::from_secs(5)); 1926 std::env::remove_var(key); 1927 let rendered = res.to_string(); 1928 assert!(!rendered.contains(value), "{key} was inherited: {res}"); 1929 } 1930 1931 #[test] 1932 fn command_timeout_kills_the_process_group() { 1933 let started = Instant::now(); 1934 let (res, ok) = exec_command_in("sleep 30", "/tmp", Duration::from_millis(300)); 1935 assert!( 1936 started.elapsed() < Duration::from_secs(3), 1937 "sleep was not killed: {res}" 1938 ); 1939 assert!(!ok, "{res}"); 1940 assert!( 1941 res["error"].as_str().unwrap_or("").contains("timed out"), 1942 "{res}" 1943 ); 1944 1945 let started = Instant::now(); 1946 let _ = exec_command_in("sleep 30 &", "/tmp", Duration::from_secs(2)); 1947 assert!( 1948 started.elapsed() < Duration::from_secs(3), 1949 "a background grandchild held the command open" 1950 ); 1951 } 1952 1953 #[test] 1954 fn setsid_grandchild_cannot_hold_the_drain_open() { 1955 let dir = tempfile::tempdir().unwrap(); 1956 let script = dir.path().join("hold.sh"); 1957 let pidfile = dir.path().join("pid"); 1958 // The holder records its pid only after `setsid`, and the leader 1959 // waits for that, so the escape always happens before the group kill. 1960 std::fs::write( 1961 &script, 1962 "#!/bin/sh\nsetsid sh -c 'echo $$ > \"$1\"; exec sleep 60' hold \"$1\" &\nwhile [ ! -s \"$1\" ]; do sleep 0.01; done\necho leader-done\n", 1963 ) 1964 .unwrap(); 1965 std::fs::set_permissions( 1966 &script, 1967 ::from_mode(0o755), 1968 ) 1969 .unwrap(); 1970 let command = format!("{} {}", script.display(), pidfile.display()); 1971 let started = Instant::now(); 1972 // The timeout is far above the bound, so only the post-exit drain 1973 // limit can make the call return in time. 1974 let (res, _) = exec_command_in(&command, "/tmp", Duration::from_secs(10)); 1975 let elapsed = started.elapsed(); 1976 let pid_txt = std::fs::read_to_string(&pidfile).unwrap_or_default(); 1977 let pid: i32 = pid_txt.trim().parse().unwrap_or(0); 1978 if pid > 0 { 1979 unsafe { 1980 libc::kill(pid, libc::SIGKILL); 1981 } 1982 } 1983 assert!( 1984 elapsed < Duration::from_secs(3), 1985 "setsid grandchild held the drain: {elapsed:?} {res}" 1986 ); 1987 } 1988 }