Skip to main content

vex_runtime/
executor.rs

1//! Agent executor - runs individual agents with LLM backend
2
3use std::sync::Arc;
4use uuid::Uuid;
5
6use crate::gate::Gate;
7use serde::Deserialize;
8use vex_adversarial::{
9    Consensus, ConsensusProtocol, Debate, DebateRound, ShadowAgent, ShadowConfig, Vote,
10};
11use vex_core::{Agent, ContextPacket, Hash};
12use vex_hardware::api::AgentIdentity;
13use vex_llm::Capability;
14use vex_persist::{AuditStore, StorageBackend};
15
16#[derive(Debug, Deserialize)]
17struct ChallengeResponse {
18    is_challenge: bool,
19    confidence: f64,
20    reasoning: String,
21    suggested_revision: Option<String>,
22}
23
24#[derive(Debug, Deserialize)]
25struct VoteResponse {
26    agrees: bool,
27    reflection: String,
28    confidence: f64,
29}
30
31/// Configuration for agent execution
32#[derive(Debug, Clone)]
33pub struct ExecutorConfig {
34    /// Maximum debate rounds
35    pub max_debate_rounds: u32,
36    /// Consensus protocol to use
37    pub consensus_protocol: ConsensusProtocol,
38    /// Whether to spawn shadow agents
39    pub enable_adversarial: bool,
40}
41
42impl Default for ExecutorConfig {
43    fn default() -> Self {
44        Self {
45            max_debate_rounds: 3,
46            consensus_protocol: ConsensusProtocol::Majority,
47            enable_adversarial: true,
48        }
49    }
50}
51
52/// Result of agent execution
53#[derive(Debug, Clone)]
54pub struct ExecutionResult {
55    /// The agent that produced this result
56    pub agent_id: Uuid,
57    /// The final response
58    pub response: String,
59    /// Whether it was verified by adversarial debate
60    pub verified: bool,
61    /// Confidence score (0.0 - 1.0)
62    pub confidence: f64,
63    /// Context packet with merkle hash
64    pub context: ContextPacket,
65    /// Logit-Merkle trace root (for provenance)
66    pub trace_root: Option<Hash>,
67    /// Debate details (if adversarial was enabled)
68    pub debate: Option<Debate>,
69    /// CHORA Evidence Capsule
70    pub evidence: Option<vex_core::audit::EvidenceCapsule>,
71}
72
73use vex_llm::{LlmProvider, LlmRequest};
74
75/// Agent executor - runs agents with LLM backends
76pub struct AgentExecutor<L: LlmProvider + ?Sized> {
77    /// Configuration
78    pub config: ExecutorConfig,
79    /// LLM backend
80    llm: Arc<L>,
81    /// Policy Gate
82    gate: Arc<dyn Gate>,
83    /// Audit Store (Phase 3)
84    pub audit_store: Option<Arc<AuditStore<dyn StorageBackend>>>,
85    /// Hardware Identity (Phase 3)
86    pub identity: Option<Arc<AgentIdentity>>,
87}
88
89impl<L: LlmProvider + ?Sized> std::fmt::Debug for AgentExecutor<L> {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        f.debug_struct("AgentExecutor")
92            .field("config", &self.config)
93            .field("identity", &self.identity)
94            .finish()
95    }
96}
97
98impl<L: LlmProvider + ?Sized> Clone for AgentExecutor<L> {
99    fn clone(&self) -> Self {
100        Self {
101            config: self.config.clone(),
102            llm: self.llm.clone(),
103            gate: self.gate.clone(),
104            audit_store: self.audit_store.clone(),
105            identity: self.identity.clone(),
106        }
107    }
108}
109
110impl<L: LlmProvider + ?Sized> AgentExecutor<L> {
111    /// Create a new executor
112    pub fn new(llm: Arc<L>, config: ExecutorConfig, gate: Arc<dyn Gate>) -> Self {
113        Self {
114            config,
115            llm,
116            gate,
117            audit_store: None,
118            identity: None,
119        }
120    }
121
122    /// Attach a hardware-rooted identity and audit store (Phase 3)
123    pub fn with_identity(
124        mut self,
125        identity: Arc<AgentIdentity>,
126        audit_store: Arc<AuditStore<dyn StorageBackend>>,
127    ) -> Self {
128        self.identity = Some(identity);
129        self.audit_store = Some(audit_store);
130        self
131    }
132
133    /// Execute an agent with a prompt and return the result
134    pub async fn execute(
135        &self,
136        tenant_id: &str, // Added tenant_id for audit logging
137        agent: &mut Agent,
138        prompt: &str,
139        capabilities: Vec<Capability>,
140    ) -> Result<ExecutionResult, String> {
141        // Step 1: Format context and get initial response from Blue agent
142        let full_prompt = if !agent.context.content.is_empty() {
143            format!(
144                "Previous Context (Time: {}):\n\"{}\"\n\nActive Prompt:\n\"{}\"",
145                agent.context.created_at, agent.context.content, prompt
146            )
147        } else {
148            prompt.to_string()
149        };
150
151        let blue_response = self
152            .llm
153            .complete(LlmRequest::with_role(&agent.config.role, &full_prompt))
154            .await
155            .map_err(|e| e.to_string())?
156            .content;
157
158        // Step 2: If adversarial is enabled, run debate
159        let (final_response, verified, confidence, debate) = if self.config.enable_adversarial {
160            self.run_adversarial_verification(agent, prompt, &blue_response)
161                .await?
162        } else {
163            (blue_response, false, 0.5, None)
164        };
165
166        // Step 2.5: Policy Gate Verification (Mutation Risk Control)
167        let capsule = self
168            .gate
169            .execute_gate(agent.id, prompt, &final_response, confidence, capabilities)
170            .await;
171
172        if capsule.outcome == "HALT" {
173            return Err(format!("Gate Blocking: {}", capsule.reason_code));
174        }
175
176        // Step 3: Create context packet with hash
177        let mut context = ContextPacket::new(&final_response);
178        context.source_agent = Some(agent.id);
179        context.importance = confidence;
180
181        // Step 4: Update agent's context
182        agent.context = context.clone();
183        agent.fitness = confidence;
184
185        let result = ExecutionResult {
186            agent_id: agent.id,
187            response: final_response,
188            verified,
189            confidence,
190            trace_root: context.trace_root.clone(),
191            context: context.clone(),
192            debate,
193            evidence: Some(capsule.clone()),
194        };
195
196        // Step 5: Automatic Hardware-Signed Audit Log (Phase 3)
197        if let Some(store) = &self.audit_store {
198            let _ = store
199                .log(
200                    tenant_id,
201                    vex_core::audit::AuditEventType::AgentExecuted,
202                    vex_core::audit::ActorType::Bot(agent.id),
203                    Some(agent.id),
204                    serde_json::json!({
205                        "prompt": prompt,
206                        "confidence": confidence,
207                        "verified": verified,
208                    }),
209                    self.identity.as_ref().map(|id| id.as_ref()),
210                    Some(capsule.witness_receipt.clone()),
211                )
212                .await;
213        }
214
215        Ok(result)
216    }
217
218    /// Run adversarial verification with Red agent
219    async fn run_adversarial_verification(
220        &self,
221        blue_agent: &Agent,
222        _original_prompt: &str,
223        blue_response: &str,
224    ) -> Result<(String, bool, f64, Option<Debate>), String> {
225        // Create shadow agent
226        let shadow = ShadowAgent::new(blue_agent, ShadowConfig::default());
227
228        // Create debate
229        let mut debate = Debate::new(blue_agent.id, shadow.agent.id, blue_response);
230
231        // Initialize weighted consensus
232        let mut consensus = Consensus::new(ConsensusProtocol::WeightedConfidence);
233
234        // Run debate rounds
235        for round_num in 1..=self.config.max_debate_rounds {
236            // Red agent challenges
237            let mut challenge_prompt = shadow.challenge_prompt(blue_response);
238            challenge_prompt.push_str("\n\nIMPORTANT: Respond in valid JSON format: {\"is_challenge\": boolean, \"confidence\": float (0.0-1.0), \"reasoning\": \"string\", \"suggested_revision\": \"string\" | null}. If you agree with the statement, set is_challenge to false.");
239
240            let red_output = self
241                .llm
242                .complete(LlmRequest::with_role(
243                    &shadow.agent.config.role,
244                    &challenge_prompt,
245                ))
246                .await
247                .map_err(|e| e.to_string())?
248                .content;
249
250            // Try to parse JSON response
251            let (is_challenge, red_confidence, red_reasoning, _suggested_revision) =
252                if let Some(start) = red_output.find('{') {
253                    if let Some(end) = red_output.rfind('}') {
254                        if let Ok(res) =
255                            serde_json::from_str::<ChallengeResponse>(&red_output[start..=end])
256                        {
257                            (
258                                res.is_challenge,
259                                res.confidence,
260                                res.reasoning,
261                                res.suggested_revision,
262                            )
263                        } else {
264                            (
265                                red_output.to_lowercase().contains("disagree"),
266                                0.5,
267                                red_output.clone(),
268                                None,
269                            )
270                        }
271                    } else {
272                        (false, 0.0, "Parsing failed".to_string(), None)
273                    }
274                } else {
275                    (false, 0.0, "No JSON found".to_string(), None)
276                };
277
278            let rebuttal = if is_challenge {
279                let rebuttal_prompt = format!(
280                    "Your previous response was challenged by a Red agent:\n\n\
281                     Original: \"{}\"\n\n\
282                     Challenge: \"{}\"\n\n\
283                     Please address these concerns or provide a revised response.",
284                    blue_response, red_reasoning
285                );
286                Some(
287                    self.llm
288                        .complete(LlmRequest::with_role(
289                            &blue_agent.config.role,
290                            &rebuttal_prompt,
291                        ))
292                        .await
293                        .map_err(|e| e.to_string())?
294                        .content,
295                )
296            } else {
297                None
298            };
299
300            debate.add_round(DebateRound {
301                round: round_num,
302                blue_claim: blue_response.to_string(),
303                red_challenge: red_reasoning.clone(),
304                blue_rebuttal: rebuttal,
305            });
306
307            // Vote: Red votes based on whether it found a challenge
308            consensus.add_vote(Vote {
309                agent_id: shadow.agent.id,
310                agrees: !is_challenge,
311                confidence: red_confidence,
312                reasoning: Some(red_reasoning),
313            });
314
315            if !is_challenge {
316                break;
317            }
318        }
319
320        // Blue agent reflects on the debate and decides its final vote (Fix for #3 bias)
321        let mut reflection_prompt = format!(
322            "You have just finished an adversarial debate about your original response.\n\n\
323             Original Response: \"{}\"\n\n\
324             Debate Rounds:\n",
325            blue_response
326        );
327
328        for (i, round) in debate.rounds.iter().enumerate() {
329            reflection_prompt.push_str(&format!(
330                "Round {}: Red challenged: \"{}\" -> You rebutted: \"{}\"\n",
331                i + 1,
332                round.red_challenge,
333                round.blue_rebuttal.as_deref().unwrap_or("N/A")
334            ));
335        }
336
337        reflection_prompt.push_str("\nBased on this debate, do you still stand by your original response? \
338                                    Respond in valid JSON: {\"agrees\": boolean, \"confidence\": float (0.0-1.0), \"reasoning\": \"string\"}.");
339
340        let blue_vote_res = self
341            .llm
342            .complete(LlmRequest::with_role(
343                &blue_agent.config.role,
344                &reflection_prompt,
345            ))
346            .await;
347
348        let (blue_agrees, blue_confidence, blue_reasoning) = if let Ok(resp) = blue_vote_res {
349            if let Some(start) = resp.content.find('{') {
350                if let Some(end) = resp.content.rfind('}') {
351                    if let Ok(vote) =
352                        serde_json::from_str::<VoteResponse>(&resp.content[start..=end])
353                    {
354                        (vote.agrees, vote.confidence, vote.reflection)
355                    } else {
356                        (
357                            true,
358                            blue_agent.fitness.max(0.5f64),
359                            "Failed to parse reflection JSON".to_string(),
360                        )
361                    }
362                } else {
363                    (
364                        true,
365                        blue_agent.fitness.max(0.5f64),
366                        "No JSON in reflection".to_string(),
367                    )
368                }
369            } else {
370                (
371                    true,
372                    blue_agent.fitness.max(0.5f64),
373                    "No reflection content".to_string(),
374                )
375            }
376        } else {
377            (
378                true,
379                blue_agent.fitness.max(0.5f64),
380                "Reflection LLM call failed".to_string(),
381            )
382        };
383
384        consensus.add_vote(Vote {
385            agent_id: blue_agent.id,
386            agrees: blue_agrees,
387            confidence: blue_confidence.max(0.5f64),
388            reasoning: Some(blue_reasoning),
389        });
390
391        consensus.evaluate();
392
393        // Determine final response
394        let final_response = if consensus.reached && consensus.decision == Some(true) {
395            blue_response.to_string()
396        } else if let Some(last_round) = debate.rounds.last() {
397            // Use rebuttal if available, otherwise original
398            last_round
399                .blue_rebuttal
400                .clone()
401                .unwrap_or_else(|| blue_response.to_string())
402        } else {
403            blue_response.to_string()
404        };
405
406        let verified = consensus.reached;
407        let confidence = consensus.confidence;
408
409        debate.conclude(consensus.decision.unwrap_or(true), confidence);
410
411        Ok((final_response, verified, confidence, Some(debate)))
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418    use vex_core::AgentConfig;
419
420    #[tokio::test]
421    async fn test_executor() {
422        use crate::gate::GenericGateMock;
423        use vex_llm::MockProvider;
424        let llm = Arc::new(MockProvider::smart());
425        let gate = Arc::new(GenericGateMock);
426        let config = ExecutorConfig {
427            enable_adversarial: false,
428            ..Default::default()
429        };
430        let executor = AgentExecutor::new(llm, config, gate);
431        let mut agent = Agent::new(AgentConfig::default());
432
433        let result = executor
434            .execute("test-tenant", &mut agent, "Test prompt", vec![])
435            .await
436            .unwrap();
437        assert!(!result.response.is_empty());
438        // verified is false by design when enable_adversarial = false
439        assert!(!result.verified);
440    }
441}