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/hooks.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 / hooks.rs` 302 lines · 9871 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 async_trait::async_trait; 17 use serde_json::{json, Value}; 18 use std::sync::Arc; 19 20 #[async_trait] 21 pub trait AgentHook: Send + Sync { 22 fn name(&self) -> &'static str; 23 24 async fn pre_turn(&self, _prompt: &mut String) -> Result<(), String> { 25 Ok(()) 26 } 27 28 async fn post_turn(&self, _response: &mut String) {} 29 30 async fn pre_tool(&self, _tool: &str, _args: &mut Value) -> Result, String> { 31 Ok(None) 32 } 33 34 async fn post_tool(&self, _tool: &str, _args: &Value, _result: &mut Value) {} 35 36 async fn on_tool_error(&self, _tool: &str, _args: &Value, _error: &str) -> Option { 37 None 38 } 39 40 async fn on_compaction(&self, _messages: &mut Vec) {} 41 } 42 43 #[derive(Default)] 44 pub struct HookRegistry { 45 hooks: Vec>, 46 } 47 48 impl HookRegistry { 49 pub fn new() -> Self { 50 Self { hooks: Vec::new() } 51 } 52 53 pub fn register(&mut self, hook: Arc) { 54 self.hooks.push(hook); 55 } 56 57 pub async fn run_pre_turn(&self, prompt: &mut String) -> Result<(), String> { 58 for h in &self.hooks { 59 h.pre_turn(prompt).await?; 60 } 61 Ok(()) 62 } 63 64 pub async fn run_post_turn(&self, response: &mut String) { 65 for h in &self.hooks { 66 h.post_turn(response).await; 67 } 68 } 69 70 pub async fn run_pre_tool( 71 &self, 72 tool: &str, 73 args: &mut Value, 74 ) -> Result, String> { 75 for h in &self.hooks { 76 if let Some(short_circuit) = h.pre_tool(tool, args).await? { 77 return Ok(Some(short_circuit)); 78 } 79 } 80 Ok(None) 81 } 82 83 pub async fn run_post_tool(&self, tool: &str, args: &Value, result: &mut Value) { 84 for h in &self.hooks { 85 h.post_tool(tool, args, result).await; 86 } 87 } 88 89 pub async fn run_on_tool_error(&self, tool: &str, args: &Value, error: &str) -> Option { 90 for h in &self.hooks { 91 if let Some(recovery) = h.on_tool_error(tool, args, error).await { 92 return Some(recovery); 93 } 94 } 95 None 96 } 97 98 pub async fn run_on_compaction(&self, messages: &mut Vec) { 99 for h in &self.hooks { 100 h.on_compaction(messages).await; 101 } 102 } 103 104 pub fn default_sovereign_registry() -> Self { 105 let mut reg = Self::new(); 106 reg.register(Arc::new(UnslopHook)); 107 reg.register(Arc::new(VaultRedactionHook)); 108 reg.register(Arc::new(CrumbAutoTrackingHook)); 109 reg.register(Arc::new(CompilerDiagnosticsHook)); 110 reg.register(Arc::new(CortexRecallHook)); 111 reg.register(Arc::new(CortexLearningCaptureHook)); 112 reg 113 } 114 } 115 116 // ========================================== 117 // Standard Sovereign Hooks 118 // ========================================== 119 120 /// 1. Unslop Hook: Enforces strict sovereign voice and wipes em dashes and en dashes 121 pub struct UnslopHook; 122 123 #[async_trait] 124 impl AgentHook for UnslopHook { 125 fn name(&self) -> &'static str { 126 "UnslopHook" 127 } 128 129 async fn post_turn(&self, response: &mut String) { 130 let sanitized = response.replace('—', ", ").replace('–', "-"); 131 *response = sanitized; 132 } 133 } 134 135 /// 2. Vault Redaction Hook: Scans and redacts credentials before outputs persist 136 pub struct VaultRedactionHook; 137 138 #[async_trait] 139 impl AgentHook for VaultRedactionHook { 140 fn name(&self) -> &'static str { 141 "VaultRedactionHook" 142 } 143 144 async fn post_turn(&self, response: &mut String) { 145 *response = crate::vault::redact_secrets(response); 146 } 147 148 async fn post_tool(&self, _tool: &str, _args: &Value, result: &mut Value) { 149 if let Some(s) = result.as_str() { 150 *result = json!(crate::vault::redact_secrets(s)); 151 } else if let Some(obj) = result.as_object_mut() { 152 for val in obj.values_mut() { 153 if let Some(s) = val.as_str() { 154 *val = json!(crate::vault::redact_secrets(s)); 155 } 156 } 157 } 158 } 159 } 160 161 /// 3. Crumb Auto Tracking Hook: Ensures new directories have a .crumb with explicit purpose 162 pub struct CrumbAutoTrackingHook; 163 164 #[async_trait] 165 impl AgentHook for CrumbAutoTrackingHook { 166 fn name(&self) -> &'static str { 167 "CrumbAutoTrackingHook" 168 } 169 170 async fn post_tool(&self, tool: &str, args: &Value, result: &mut Value) { 171 if tool == "create_dir" { 172 let path = args.get("path").and_then(Value::as_str).unwrap_or(""); 173 let purpose = args 174 .get("purpose") 175 .and_then(Value::as_str) 176 .unwrap_or("Directory created during autonomous execution."); 177 if !path.is_empty() { 178 let logged = crate::crumbs::record_as_self( 179 std::path::Path::new(path), 180 "create_dir", 181 purpose, 182 "scaffold", 183 ); 184 if let Some(obj) = result.as_object_mut() { 185 // Advisory notes: a failure is reported, never claimed 186 // as logged, and does not undo the directory creation. 187 obj.insert("crumb_logged".to_string(), json!(logged.is_ok())); 188 if let Err(err) = logged { 189 obj.insert("crumb_local_error".to_string(), json!(err)); 190 } 191 } 192 } 193 } 194 } 195 } 196 197 /// 4. Compiler Diagnostics Hook: Enriches cargo/rustc build failures with structured guidance 198 pub struct CompilerDiagnosticsHook; 199 200 #[async_trait] 201 impl AgentHook for CompilerDiagnosticsHook { 202 fn name(&self) -> &'static str { 203 "CompilerDiagnosticsHook" 204 } 205 206 async fn on_tool_error(&self, tool: &str, args: &Value, error: &str) -> Option { 207 if tool == "run_command" { 208 let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); 209 if cmd.contains("cargo") || cmd.contains("rustc") { 210 return Some(json!({ 211 "status": "compiler_error", 212 "command": cmd, 213 "error": error, 214 "guidance": "Compiler diagnostics detected. Review the line numbers and error codes above, apply surgical edits via replace_file_content, and re-verify with cargo check." 215 })); 216 } 217 } 218 None 219 } 220 } 221 222 /// 5. Cortex Recall Hook: Automatically queries Spark Cortex and injects relevant memories into turn 223 pub struct CortexRecallHook; 224 225 #[async_trait] 226 impl AgentHook for CortexRecallHook { 227 fn name(&self) -> &'static str { 228 "CortexRecallHook" 229 } 230 231 async fn pre_turn(&self, prompt: &mut String) -> Result<(), String> { 232 if let Some(recall) = crate::cortex::assemble_model_context(prompt).await { 233 *prompt = format!("{}\n\n{}", recall, prompt); 234 } 235 Ok(()) 236 } 237 } 238 239 /// 6. Cortex Learning Capture Hook: Automatically records meaningful actions and verifications into Cortex 240 pub struct CortexLearningCaptureHook; 241 242 #[async_trait] 243 impl AgentHook for CortexLearningCaptureHook { 244 fn name(&self) -> &'static str { 245 "CortexLearningCaptureHook" 246 } 247 248 async fn post_tool(&self, tool: &str, args: &Value, result: &mut Value) { 249 match tool { 250 "write_to_file" | "replace_file_content" => { 251 let path = args.get("path").and_then(Value::as_str).unwrap_or(""); 252 let intent = args 253 .get("intent") 254 .and_then(Value::as_str) 255 .unwrap_or("File modified"); 256 if !path.is_empty() { 257 crate::cortex::trigger_background_capture("file_write", path, intent); 258 } 259 } 260 "run_command" => { 261 let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); 262 if (cmd.contains("cargo build") 263 || cmd.contains("cargo check") 264 || cmd.contains("gh repo") 265 || cmd.contains("git commit")) 266 && result.get("error").is_none() 267 { 268 crate::cortex::trigger_background_capture( 269 "command_success", 270 cmd, 271 "Command verified cleanly", 272 ); 273 } 274 } 275 _ => {} 276 } 277 } 278 } 279 280 #[cfg(test)] 281 mod tests { 282 use super::*; 283 284 #[tokio::test] 285 async fn test_unslop_hook() { 286 let registry = HookRegistry::default_sovereign_registry(); 287 let mut text = "This is a feature—not a bug–verified.".to_string(); 288 registry.run_post_turn(&mut text).await; 289 assert!(!text.contains('—')); 290 assert!(!text.contains('–')); 291 assert!(text.contains("feature, not a bug-verified")); 292 } 293 294 #[tokio::test] 295 async fn test_vault_redactor_hook() { 296 let registry = HookRegistry::default_sovereign_registry(); 297 let mut text = 298 "Here is the key: sk-ant-api03-`1234567890123456789012345678901234567890`.".to_string(); 299 registry.run_post_turn(&mut text).await; 300 assert!(text.contains("[REDACTED_ANTHROPIC_KEY]")); 301 } 302 }