Skip to main content

lean_ctx/core/
decision_loop_runtime.rs

1//! Non-blocking bridge between MCP tool execution and the decision loop.
2
3use std::{
4    collections::HashMap,
5    panic::{AssertUnwindSafe, catch_unwind},
6    sync::{Arc, Mutex, OnceLock},
7    time::Instant,
8};
9
10use crate::core::{
11    decision_loop::protocol_profile,
12    task_spine::TaskSpine,
13    triage::{TaskAnalysisInput, TriageEngine},
14    value_gate::{
15        ExecutionCost, OutcomeSignal, TaskOutcome, ValueGate, ValueGateStore,
16        cost_tracker::calculate_cost,
17    },
18};
19
20#[derive(Debug)]
21/// Bridges MCP tool lifecycle events into decision-loop accounting.
22pub struct DecisionLoopRuntime {
23    triage: TriageEngine,
24    value_gate_store: Arc<Mutex<ValueGateStore>>,
25    task_profiles: Mutex<HashMap<String, crate::core::triage::profile::TaskProfileLocal>>,
26}
27
28#[derive(Debug)]
29/// Tracks a tool invocation while its decision-loop work is in progress.
30pub struct TaskContext {
31    pub task_id: String,
32    pub session_id: String,
33    pub triage_class: String,
34    pub profile_intent: String,
35    pub profile_complexity: String,
36    pub filtered_lines: usize,
37    pub start_time: Instant,
38}
39
40impl DecisionLoopRuntime {
41    pub fn get_or_init() -> &'static Self {
42        static RUNTIME: OnceLock<DecisionLoopRuntime> = OnceLock::new();
43        RUNTIME.get_or_init(|| Self {
44            triage: TriageEngine::default(),
45            value_gate_store: Arc::new(Mutex::new(ValueGateStore::default())),
46            task_profiles: Mutex::new(HashMap::new()),
47        })
48    }
49
50    /// Returns the most recently triaged profile for a session.
51    pub fn profile_for_session(
52        &self,
53        session_id: &str,
54    ) -> Option<crate::core::triage::profile::TaskProfileLocal> {
55        self.task_profiles
56            .lock()
57            .unwrap_or_else(std::sync::PoisonError::into_inner)
58            .get(session_id)
59            .cloned()
60    }
61
62    pub fn on_tool_start(
63        &self,
64        tool_name: &str,
65        query: Option<&str>,
66        session_id: &str,
67        agent_id: &str,
68    ) -> TaskContext {
69        catch_unwind(AssertUnwindSafe(|| {
70            self.on_tool_start_inner(tool_name, query, session_id, agent_id)
71        }))
72        .unwrap_or_else(|_| TaskContext {
73            task_id: String::new(),
74            session_id: session_id.to_owned(),
75            triage_class: String::new(),
76            profile_intent: String::new(),
77            profile_complexity: String::new(),
78            filtered_lines: 0,
79            start_time: Instant::now(),
80        })
81    }
82
83    fn on_tool_start_inner(
84        &self,
85        tool_name: &str,
86        query: Option<&str>,
87        session_id: &str,
88        agent_id: &str,
89    ) -> TaskContext {
90        let profile = self
91            .triage
92            .analyze(&TaskAnalysisInput {
93                query: query.map_or_else(String::new, |text| format!("{tool_name}: {text}")),
94                ..Default::default()
95            })
96            .map(|hypothesis| hypothesis.profile)
97            .unwrap_or_default();
98        self.remember_profile(session_id, profile.clone());
99        let mut envelope =
100            TaskSpine::create_envelope(query.unwrap_or(tool_name), session_id, agent_id);
101        TaskSpine::enrich_from_triage(&mut envelope, &protocol_profile(&profile));
102        TaskContext {
103            task_id: envelope.task_id.as_str().to_owned(),
104            session_id: session_id.to_owned(),
105            triage_class: profile.task_class,
106            profile_intent: profile.intent,
107            profile_complexity: profile.complexity,
108            filtered_lines: 0,
109            start_time: Instant::now(),
110        }
111    }
112
113    fn remember_profile(
114        &self,
115        session_id: &str,
116        profile: crate::core::triage::profile::TaskProfileLocal,
117    ) {
118        const MAX_SESSION_PROFILES: usize = 128;
119        let mut profiles = self
120            .task_profiles
121            .lock()
122            .unwrap_or_else(std::sync::PoisonError::into_inner);
123        if !profiles.contains_key(session_id) && profiles.len() >= MAX_SESSION_PROFILES {
124            profiles.clear();
125        }
126        profiles.insert(session_id.to_owned(), profile);
127    }
128
129    pub fn on_tool_end(
130        &self,
131        ctx: &TaskContext,
132        input_tokens: u64,
133        output_tokens: u64,
134        model: &str,
135        success: bool,
136    ) -> Option<crate::core::value_gate::ValueAssessment> {
137        catch_unwind(AssertUnwindSafe(|| {
138            self.on_tool_end_inner(ctx, input_tokens, output_tokens, model, success)
139        }))
140        .ok()
141    }
142
143    /// Records a completed tool and schedules an accepted Shadow Mode sample.
144    ///
145    /// Shadow work is detached from the MCP response path: inability to spawn
146    /// or persist a comparison must never affect the completed tool call.
147    pub fn on_tool_end_with_shadow(
148        &self,
149        ctx: &TaskContext,
150        input_tokens: u64,
151        output_tokens: u64,
152        model: &str,
153        success: bool,
154        shadow_auto_record: bool,
155        shadow_tokens: Option<(u64, u64)>,
156    ) -> Option<crate::core::value_gate::ValueAssessment> {
157        let result = self.on_tool_end(ctx, input_tokens, output_tokens, model, success);
158        let Some(assessment) = result.as_ref() else {
159            return result;
160        };
161        let (raw_input_tokens, compressed_input_tokens) =
162            shadow_tokens.unwrap_or((output_tokens, output_tokens));
163        let entry = crate::core::live_evidence_ledger::EvidenceLedgerEntry::completed(
164            &ctx.task_id,
165            &ctx.session_id,
166            &ctx.triage_class,
167            raw_input_tokens.saturating_sub(compressed_input_tokens),
168            compressed_input_tokens,
169            assessment.cpao_micros,
170            assessment.outcome_accepted,
171        );
172        if let Err(error) = crate::core::live_evidence_ledger::append_completion(&entry) {
173            tracing::warn!("failed to persist evidence ledger entry: {error}");
174        }
175        if !shadow_auto_record || !assessment.outcome_accepted {
176            return result;
177        }
178
179        let duration_ms = u64::try_from(ctx.start_time.elapsed().as_millis()).unwrap_or(u64::MAX);
180        let task = crate::core::shadow::ShadowTask {
181            task_id: assessment.task_id.clone(),
182            query: format!("{}: {}", ctx.profile_intent, ctx.profile_complexity),
183            raw_input_tokens,
184            compressed_input_tokens,
185            output_tokens,
186            model_used: assessment.model.clone(),
187            outcome_signals: vec![OutcomeSignal::BuildSucceeded],
188            duration_ms,
189        };
190        let _ = std::thread::Builder::new()
191            .name("lean-ctx-shadow".into())
192            .spawn(move || {
193                crate::core::shadow::runtime::ShadowRuntime::on_task_complete(&task);
194            });
195        result
196    }
197
198    fn on_tool_end_inner(
199        &self,
200        ctx: &TaskContext,
201        input_tokens: u64,
202        output_tokens: u64,
203        model: &str,
204        success: bool,
205    ) -> crate::core::value_gate::ValueAssessment {
206        let cost = ExecutionCost {
207            input_tokens,
208            output_tokens,
209            cache_read_tokens: 0,
210            model: model.to_owned(),
211            provider: "mcp".to_owned(),
212            estimated_cost_micros: calculate_cost(input_tokens, output_tokens, 0, model),
213        };
214        let outcome = TaskOutcome {
215            task_id: ctx.task_id.clone(),
216            completed: true,
217            signals: vec![if success {
218                OutcomeSignal::BuildSucceeded
219            } else {
220                OutcomeSignal::CompileError
221            }],
222        };
223        let assessment = ValueGate::evaluate_task(&ctx.task_id, &cost, &outcome);
224        self.value_gate_store
225            .lock()
226            .unwrap_or_else(std::sync::PoisonError::into_inner)
227            .record(&assessment);
228        assessment
229    }
230
231    #[cfg(test)]
232    pub(crate) fn with_triage(triage: TriageEngine) -> Self {
233        Self {
234            triage,
235            value_gate_store: Arc::new(Mutex::new(ValueGateStore::default())),
236            task_profiles: Mutex::new(HashMap::new()),
237        }
238    }
239
240    #[cfg(test)]
241    pub(crate) fn latest_assessment_accepted(&self) -> Option<bool> {
242        self.value_gate_store
243            .lock()
244            .unwrap_or_else(std::sync::PoisonError::into_inner)
245            .recent(1)
246            .first()
247            .map(|assessment| assessment.outcome_accepted)
248    }
249
250    #[cfg(test)]
251    pub(crate) fn assessment_for(
252        &self,
253        task_id: &str,
254    ) -> Option<crate::core::value_gate::ValueAssessment> {
255        self.value_gate_store
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner)
258            .recent(100)
259            .into_iter()
260            .find(|assessment| assessment.task_id == task_id)
261    }
262}