1use std::{
5 any::Any,
6 cell::RefCell,
7 collections::HashMap,
8 fmt,
9 sync::{Arc, Condvar, Mutex, OnceLock},
10 time::Instant,
11};
12
13tokio::task_local! {
14 static DEFERRED_HEATMAP: RefCell<Vec<HeatmapObservation>>;
15}
16
17thread_local! {
18 static SYNC_DEFERRED_HEATMAP: RefCell<Option<Vec<HeatmapObservation>>> = const {
19 RefCell::new(None)
20 };
21}
22
23use lean_ctx_protocol::{AcceptanceState, AcceptedOutcomeV1, TaskEnvelopeV1};
24
25use crate::core::{
26 outcome::{
27 contracts::{OutcomeContractV1, TaskClass},
28 evaluator::OutcomeEvaluator,
29 signals::{LocalSignalAdapters, OutcomeSignal as CanonicalSignal},
30 },
31 task_spine::TaskSpine,
32 triage::{TriageEngine, profile::TaskProfileLocal},
33 value_gate::{
34 ExecutionCost, OutcomeSignal, TaskOutcome, ValueAssessment, ValueGate,
35 cost_tracker::calculate_cost,
36 },
37};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum LifecycleStage {
42 IdentifyCaller,
43 ResolveWorkspace,
44 ResolveEntitlements,
45 ApplySecurityBoundaries,
46 GatherContextStrategy,
47 AskAutopilot,
48 DispatchPrimitive,
49 ReversiblePostProcess,
50 RecordContextIr,
51 RecordLedger,
52 RecordEvidence,
53 RecordOutcome,
54 UpdateLearning,
55 UpdateHeatmap,
56 UpdateBreakEven,
57 Checkpoint,
58 ScheduleTelemetry,
59 FlushState,
60}
61
62pub const LIFECYCLE_STAGE_ORDER: [LifecycleStage; 18] = [
63 LifecycleStage::IdentifyCaller,
64 LifecycleStage::ResolveWorkspace,
65 LifecycleStage::ResolveEntitlements,
66 LifecycleStage::ApplySecurityBoundaries,
67 LifecycleStage::GatherContextStrategy,
68 LifecycleStage::AskAutopilot,
69 LifecycleStage::DispatchPrimitive,
70 LifecycleStage::ReversiblePostProcess,
71 LifecycleStage::RecordContextIr,
72 LifecycleStage::RecordLedger,
73 LifecycleStage::RecordEvidence,
74 LifecycleStage::RecordOutcome,
75 LifecycleStage::UpdateLearning,
76 LifecycleStage::UpdateHeatmap,
77 LifecycleStage::UpdateBreakEven,
78 LifecycleStage::Checkpoint,
79 LifecycleStage::ScheduleTelemetry,
80 LifecycleStage::FlushState,
81];
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum StageDisposition {
85 Applied,
86 Skipped(&'static str),
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct StageExecution {
91 pub stage: LifecycleStage,
92 pub disposition: StageDisposition,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
96pub enum ToolSurface {
97 Mcp,
98 Cli,
99 Daemon,
100 Hook,
101 Proxy,
102}
103
104#[derive(Debug, Clone)]
105pub struct ToolRequest {
106 pub tool_name: String,
107 pub query: Option<String>,
108 pub session_id: String,
109 pub agent_id: String,
110 pub surface: ToolSurface,
111 pub idempotency_key: Option<String>,
112}
113
114#[derive(Debug, Clone, Default)]
115pub struct RuntimeContext {
116 pub client_name: Option<String>,
117 pub project_root: Option<String>,
118}
119
120#[derive(Debug, Clone, Copy, Default)]
121pub struct ProductEntitlements {
122 pub autopilot: bool,
123 pub personalized_learning: bool,
124}
125
126#[derive(Debug, Clone)]
127pub struct CompletionObservation {
128 pub input_tokens: u64,
129 pub output_tokens: u64,
130 pub model: String,
131 pub provider: String,
132 pub success: bool,
133 pub outcome_signals: Vec<OutcomeSignal>,
135 pub shadow_auto_record: bool,
136 pub shadow_tokens: Option<(u64, u64)>,
137 pub proxy_economics: Option<ProxyEconomicsObservation>,
138 pub heatmap: Option<HeatmapObservation>,
139}
140
141#[derive(Debug, Clone)]
142pub struct ProxyEconomicsObservation {
143 pub tokens_pruned: usize,
144 pub original_tokens: usize,
145 pub task_class: String,
146}
147
148#[derive(Debug, Clone)]
149pub struct HeatmapObservation {
150 pub path: String,
151 pub original_tokens: usize,
152 pub saved_tokens: usize,
153}
154
155pub(crate) fn record_heatmap_access(path: &str, original_tokens: usize, saved_tokens: usize) {
157 let observation = HeatmapObservation {
158 path: path.to_owned(),
159 original_tokens,
160 saved_tokens,
161 };
162 if DEFERRED_HEATMAP
163 .try_with(|pending| pending.borrow_mut().push(observation.clone()))
164 .is_ok()
165 {
166 return;
167 }
168 let deferred = SYNC_DEFERRED_HEATMAP.with(|pending| {
169 let mut pending = pending.borrow_mut();
170 pending.as_mut().is_some_and(|items| {
171 items.push(observation);
172 true
173 })
174 });
175 if !deferred {
176 crate::core::heatmap::record_file_access(path, original_tokens, saved_tokens);
177 }
178}
179
180pub(crate) fn begin_sync_heatmap_capture() {
181 SYNC_DEFERRED_HEATMAP.with(|pending| *pending.borrow_mut() = Some(Vec::new()));
182}
183
184fn take_deferred_heatmap() -> Vec<HeatmapObservation> {
185 DEFERRED_HEATMAP
186 .try_with(|pending| std::mem::take(&mut *pending.borrow_mut()))
187 .unwrap_or_else(|_| {
188 SYNC_DEFERRED_HEATMAP.with(|pending| pending.borrow_mut().take().unwrap_or_default())
189 })
190}
191
192pub struct CancellationCompletion {
194 pub observation: CompletionObservation,
195 pub ledger: StageDisposition,
196}
197
198pub type CancellationHandler = Box<dyn FnOnce() -> CancellationCompletion + Send>;
199
200#[async_trait::async_trait]
201pub trait ExecutionDriver: Send {
202 type Primitive: Send;
203 type Processed: Send;
204 type Output: Clone + Send + Sync + 'static;
205 type Error: Clone + Send + Sync + 'static;
206
207 fn cancellation_handler(&self) -> Option<CancellationHandler> {
210 None
211 }
212
213 async fn identify_caller(
214 &mut self,
215 _context: &TaskContext,
216 ) -> Result<StageDisposition, Self::Error> {
217 Ok(StageDisposition::Skipped("caller identity unavailable"))
218 }
219
220 async fn resolve_workspace(
221 &mut self,
222 _context: &TaskContext,
223 ) -> Result<StageDisposition, Self::Error> {
224 Ok(StageDisposition::Skipped("workspace unavailable"))
225 }
226
227 async fn resolve_entitlements(
228 &mut self,
229 _context: &TaskContext,
230 ) -> Result<StageDisposition, Self::Error> {
231 Ok(StageDisposition::Skipped("no product entitlement source"))
232 }
233
234 async fn apply_security_boundaries(
235 &mut self,
236 _context: &TaskContext,
237 ) -> Result<StageDisposition, Self::Error> {
238 Ok(StageDisposition::Skipped("no surface security adapter"))
239 }
240
241 async fn gather_context_strategy(
242 &mut self,
243 _context: &TaskContext,
244 ) -> Result<StageDisposition, Self::Error> {
245 Ok(StageDisposition::Skipped("no context strategy"))
246 }
247
248 async fn ask_autopilot(
249 &mut self,
250 context: &TaskContext,
251 ) -> Result<StageDisposition, Self::Error> {
252 Ok(if context.entitlements.autopilot {
253 StageDisposition::Skipped("no canonical autopilot decision")
255 } else {
256 StageDisposition::Skipped("not entitled")
257 })
258 }
259
260 async fn validate_cached_replay(
262 &mut self,
263 _context: &TaskContext,
264 ) -> Result<Option<Self::Output>, Self::Error> {
265 Ok(None)
266 }
267
268 async fn dispatch_primitive(
269 &mut self,
270 context: &TaskContext,
271 ) -> Result<(Self::Primitive, StageDisposition), Self::Error>;
272
273 async fn reversible_post_process(
274 &mut self,
275 context: &TaskContext,
276 primitive: Self::Primitive,
277 ) -> Result<(Self::Processed, StageDisposition), Self::Error>;
278
279 async fn record_context_ir(
280 &mut self,
281 context: &TaskContext,
282 processed: &Self::Processed,
283 ) -> Result<StageDisposition, Self::Error>;
284
285 async fn record_ledger(
286 &mut self,
287 context: &TaskContext,
288 processed: &Self::Processed,
289 ) -> Result<StageDisposition, Self::Error>;
290
291 async fn checkpoint(
292 &mut self,
293 _context: &TaskContext,
294 _output: &mut Self::Output,
295 ) -> Result<StageDisposition, Self::Error> {
296 Ok(StageDisposition::Skipped("checkpoint not configured"))
297 }
298
299 fn output_from_processed(&mut self, processed: Self::Processed) -> Self::Output;
300
301 fn observe(
302 &self,
303 result: &Result<Self::Output, LifecycleRunError<Self::Error>>,
304 ) -> CompletionObservation;
305}
306
307impl CompletionObservation {
308 pub fn tool_result(input_tokens: u64, output_tokens: u64, model: &str, success: bool) -> Self {
309 Self {
310 input_tokens,
311 output_tokens,
312 model: model.to_owned(),
313 provider: "mcp".to_owned(),
314 success,
315 outcome_signals: Vec::new(),
317 shadow_auto_record: false,
318 shadow_tokens: None,
319 proxy_economics: None,
320 heatmap: None,
321 }
322 }
323}
324
325#[derive(Debug, Clone)]
326pub struct LifecycleOutcome {
327 pub accepted_outcome: AcceptedOutcomeV1,
328 pub assessment: Option<ValueAssessment>,
329}
330
331#[derive(Debug, Clone)]
332enum RunState {
333 Open,
334 Completing,
335 Completed(Box<LifecycleOutcome>),
336}
337
338#[cfg(test)]
339type FinalizationHook = Arc<dyn Fn(LifecycleStage, Option<&LifecycleOutcome>) + Send + Sync>;
340
341#[cfg(test)]
342fn test_finalization_point(
343 context: &TaskContext,
344 stage: LifecycleStage,
345 outcome: Option<&LifecycleOutcome>,
346) {
347 let hook = context
348 .shared
349 .finalization_hook
350 .lock()
351 .unwrap_or_else(std::sync::PoisonError::into_inner)
352 .clone();
353 if let Some(hook) = hook {
354 hook(stage, outcome);
355 }
356}
357
358struct SharedRun {
359 state: Mutex<RunState>,
360 completed: Condvar,
361 dispatch: Mutex<DispatchState>,
362 dispatch_completed: tokio::sync::Notify,
363 stages: Mutex<Vec<StageExecution>>,
364 computed_outcome: OnceLock<LifecycleOutcome>,
365 telemetry_started: std::sync::atomic::AtomicBool,
366 flush_started: std::sync::atomic::AtomicBool,
367 #[cfg(test)]
368 flush_hook: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
369 #[cfg(test)]
370 finalization_hook: Mutex<Option<FinalizationHook>>,
371 autopilot: OnceLock<Arc<crate::core::context_kernel::bridge::runtime::PreparedKernelContext>>,
372 #[cfg(test)]
373 autopilot_planning_attempts: std::sync::atomic::AtomicUsize,
374}
375
376enum DispatchState {
377 Idle,
378 Running,
379 Finished(Arc<dyn Any + Send + Sync>),
380 Aborted(Box<LifecycleOutcome>),
381}
382
383#[derive(Debug, Clone)]
384pub enum LifecycleRunError<E> {
385 Dispatch(E),
386 Aborted(Box<LifecycleOutcome>),
387 ReplayTypeMismatch,
389}
390
391impl fmt::Debug for SharedRun {
392 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
393 formatter.debug_struct("SharedRun").finish_non_exhaustive()
394 }
395}
396
397impl Default for SharedRun {
398 fn default() -> Self {
399 Self {
400 state: Mutex::new(RunState::Open),
401 completed: Condvar::new(),
402 dispatch: Mutex::new(DispatchState::Idle),
403 dispatch_completed: tokio::sync::Notify::new(),
404 stages: Mutex::new(Vec::new()),
405 computed_outcome: OnceLock::new(),
406 telemetry_started: std::sync::atomic::AtomicBool::new(false),
407 flush_started: std::sync::atomic::AtomicBool::new(false),
408 #[cfg(test)]
409 flush_hook: Mutex::new(None),
410 #[cfg(test)]
411 finalization_hook: Mutex::new(None),
412 autopilot: OnceLock::new(),
413 #[cfg(test)]
414 autopilot_planning_attempts: std::sync::atomic::AtomicUsize::new(0),
415 }
416 }
417}
418
419#[derive(Debug, Clone)]
421pub struct TaskContext {
422 pub task_id: String,
423 pub session_id: String,
424 pub triage_class: String,
425 pub profile_intent: String,
426 pub profile_complexity: String,
427 pub filtered_lines: usize,
428 pub start_time: Instant,
429 pub envelope: TaskEnvelopeV1,
430 pub profile: TaskProfileLocal,
431 pub surface: ToolSurface,
432 pub runtime: RuntimeContext,
433 pub entitlements: ProductEntitlements,
434 planning_query: Option<String>,
435 shared: Arc<SharedRun>,
436}
437
438#[path = "execution_lifecycle_state.rs"]
439mod task_state;
440
441#[derive(Debug)]
442struct DecisionSpine {
443 triage: TriageEngine,
444 value_gate: ValueGate,
445 task_profiles: Mutex<HashMap<String, TaskProfileLocal>>,
446 runs: Mutex<HashMap<task_state::TaskReplayKey, TaskContext>>,
447 assessments: Mutex<HashMap<String, ValueAssessment>>,
448 outcomes: Mutex<HashMap<String, LifecycleOutcome>>,
449}
450
451#[derive(Debug, Clone)]
453pub struct ExecutionLifecycle {
454 spine: Arc<DecisionSpine>,
455}
456
457impl Default for ExecutionLifecycle {
458 fn default() -> Self {
459 Self::with_triage(TriageEngine::default())
460 }
461}
462
463impl ExecutionLifecycle {
464 pub fn global() -> &'static Self {
465 static LIFECYCLE: std::sync::OnceLock<ExecutionLifecycle> = std::sync::OnceLock::new();
466 LIFECYCLE.get_or_init(Self::default)
467 }
468
469 pub fn with_triage(triage: TriageEngine) -> Self {
470 Self::with_components(triage, ValueGate)
471 }
472
473 pub fn with_components(triage: TriageEngine, value_gate: ValueGate) -> Self {
474 Self {
475 spine: Arc::new(DecisionSpine::new(triage, value_gate)),
476 }
477 }
478
479 pub fn begin(
480 &self,
481 request: ToolRequest,
482 runtime: RuntimeContext,
483 entitlements: ProductEntitlements,
484 ) -> TaskContext {
485 self.spine.begin(request, runtime, entitlements, None)
486 }
487
488 fn prepare(&self, context: &TaskContext) {
489 let _ = context.advance(LifecycleStage::IdentifyCaller);
490 let _ = context.advance(LifecycleStage::ResolveWorkspace);
491 let _ = context.advance(LifecycleStage::ResolveEntitlements);
492 let _ = context.advance(LifecycleStage::ApplySecurityBoundaries);
493 let _ = context.advance(LifecycleStage::GatherContextStrategy);
494 if context.entitlements.autopilot {
495 let _ = context.skip(
496 LifecycleStage::AskAutopilot,
497 "no canonical autopilot decision",
498 );
499 } else {
500 let _ = context.skip(LifecycleStage::AskAutopilot, "not entitled");
501 }
502 }
503
504 pub async fn run<D>(
505 &self,
506 request: ToolRequest,
507 runtime: RuntimeContext,
508 entitlements: ProductEntitlements,
509 driver: D,
510 ) -> Result<D::Output, LifecycleRunError<D::Error>>
511 where
512 D: ExecutionDriver,
513 {
514 self.run_with_task_identity(request, runtime, entitlements, driver, None)
515 .await
516 }
517
518 pub(crate) async fn run_with_task_identity<D>(
520 &self,
521 request: ToolRequest,
522 runtime: RuntimeContext,
523 entitlements: ProductEntitlements,
524 driver: D,
525 identity: Option<crate::core::task_spine::AdmittedTaskIdentity>,
526 ) -> Result<D::Output, LifecycleRunError<D::Error>>
527 where
528 D: ExecutionDriver,
529 {
530 TaskSpine::scope(
532 None,
533 DEFERRED_HEATMAP.scope(
534 RefCell::new(Vec::new()),
535 self.run_scoped(request, runtime, entitlements, driver, identity),
536 ),
537 )
538 .await
539 }
540
541 async fn run_scoped<D>(
542 &self,
543 request: ToolRequest,
544 runtime: RuntimeContext,
545 entitlements: ProductEntitlements,
546 driver: D,
547 identity: Option<crate::core::task_spine::AdmittedTaskIdentity>,
548 ) -> Result<D::Output, LifecycleRunError<D::Error>>
549 where
550 D: ExecutionDriver,
551 {
552 let context = self
553 .spine
554 .begin(request, runtime, entitlements, identity.as_ref());
555 TaskSpine::scope(
556 Some(context.envelope.clone()),
557 Box::pin(self.run_context(context, driver)),
559 )
560 .await
561 }
562
563 async fn run_context<D>(
564 &self,
565 context: TaskContext,
566 mut driver: D,
567 ) -> Result<D::Output, LifecycleRunError<D::Error>>
568 where
569 D: ExecutionDriver,
570 {
571 if let Some(cached) = context
572 .cached_or_claim_dispatch::<D::Output, D::Error>()
573 .await
574 {
575 if matches!(cached, Err(LifecycleRunError::ReplayTypeMismatch)) {
576 return cached;
577 }
578 return match driver.validate_cached_replay(&context).await {
579 Ok(Some(current_denial)) => Ok(current_denial),
580 Ok(None) => cached,
581 Err(error) => Err(LifecycleRunError::Dispatch(error)),
582 };
583 }
584 let mut permit = DispatchPermit::new(context.shared.clone());
585 let guard = LifecycleGuard::for_run(self, context.clone(), driver.cancellation_handler());
586 *context
587 .shared
588 .state
589 .lock()
590 .unwrap_or_else(std::sync::PoisonError::into_inner) = RunState::Completing;
591 macro_rules! run_admission_stage {
592 ($method:ident, $stage:expr) => {
593 match driver.$method(&context).await {
594 Ok(disposition) => {
595 let _ = context.record_stage($stage, disposition);
596 }
597 Err(error) => {
598 let _ = context.advance($stage);
599 context.skip_through(LifecycleStage::RecordLedger, "admission failed");
600 let result = Err(LifecycleRunError::Dispatch(error));
601 let _ = guard.complete(driver.observe(&result));
602 permit.publish(result.clone());
603 return result;
604 }
605 }
606 };
607 }
608
609 run_admission_stage!(identify_caller, LifecycleStage::IdentifyCaller);
610 run_admission_stage!(resolve_workspace, LifecycleStage::ResolveWorkspace);
611 run_admission_stage!(resolve_entitlements, LifecycleStage::ResolveEntitlements);
612 run_admission_stage!(
613 apply_security_boundaries,
614 LifecycleStage::ApplySecurityBoundaries
615 );
616 run_admission_stage!(
617 gather_context_strategy,
618 LifecycleStage::GatherContextStrategy
619 );
620 run_admission_stage!(ask_autopilot, LifecycleStage::AskAutopilot);
621
622 let primitive = match driver.dispatch_primitive(&context).await {
623 Ok((primitive, disposition)) => {
624 let _ = context.record_stage(LifecycleStage::DispatchPrimitive, disposition);
625 primitive
626 }
627 Err(error) => {
628 let _ = context.advance(LifecycleStage::DispatchPrimitive);
629 let _ = context.skip(LifecycleStage::ReversiblePostProcess, "dispatch failed");
630 let _ = context.skip(LifecycleStage::RecordContextIr, "dispatch failed");
631 let _ = context.skip(LifecycleStage::RecordLedger, "dispatch failed");
632 let result = Err(LifecycleRunError::Dispatch(error));
633 let _ = guard.complete(driver.observe(&result));
634 permit.publish(result.clone());
635 return result;
636 }
637 };
638 let processed = match driver.reversible_post_process(&context, primitive).await {
639 Ok((processed, disposition)) => {
640 let _ = context.record_stage(LifecycleStage::ReversiblePostProcess, disposition);
641 processed
642 }
643 Err(error) => {
644 let _ = context.advance(LifecycleStage::ReversiblePostProcess);
645 let _ = context.skip(LifecycleStage::RecordContextIr, "post-processing failed");
646 let _ = context.skip(LifecycleStage::RecordLedger, "post-processing failed");
647 let result = Err(LifecycleRunError::Dispatch(error));
648 let _ = guard.complete(driver.observe(&result));
649 permit.publish(result.clone());
650 return result;
651 }
652 };
653 let ir = driver.record_context_ir(&context, &processed).await;
654 match ir {
655 Ok(disposition) => {
656 let _ = context.record_stage(LifecycleStage::RecordContextIr, disposition);
657 }
658 Err(error) => {
659 let _ = context.advance(LifecycleStage::RecordContextIr);
660 let _ = context.skip(LifecycleStage::RecordLedger, "Context IR failed");
661 let result = Err(LifecycleRunError::Dispatch(error));
662 let _ = guard.complete(driver.observe(&result));
663 permit.publish(result.clone());
664 return result;
665 }
666 }
667 match driver.record_ledger(&context, &processed).await {
668 Ok(disposition) => {
669 let _ = context.record_stage(LifecycleStage::RecordLedger, disposition);
670 }
671 Err(error) => {
672 let _ = context.advance(LifecycleStage::RecordLedger);
673 let result = Err(LifecycleRunError::Dispatch(error));
674 let _ = guard.complete(driver.observe(&result));
675 permit.publish(result.clone());
676 return result;
677 }
678 }
679 let mut output = driver.output_from_processed(processed);
680 let provisional = Ok(output.clone());
681 let observation = driver.observe(&provisional);
682 *guard
683 .observation
684 .lock()
685 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(observation.clone());
686 let fallback_observation = observation.clone();
687 let outcome = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
688 self.finalize_through_economics(&context, observation)
689 })) {
690 Ok(outcome) => {
691 *guard
692 .outcome
693 .lock()
694 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(outcome.clone());
695 match driver.checkpoint(&context, &mut output).await {
696 Ok(disposition) => {
697 let _ = context.record_stage(LifecycleStage::Checkpoint, disposition);
698 }
699 Err(_) => {
700 let _ = context.skip(LifecycleStage::Checkpoint, "checkpoint failed");
701 }
702 }
703 let telemetry_observation = driver.observe(&Ok(output.clone()));
704 self.finish_cleanup(&context, &telemetry_observation);
705 outcome
706 }
707 Err(_) => self.finalize_after_panic(&context, fallback_observation),
708 };
709 let mut state = context
710 .shared
711 .state
712 .lock()
713 .unwrap_or_else(std::sync::PoisonError::into_inner);
714 *state = RunState::Completed(Box::new(outcome));
715 context.shared.completed.notify_all();
716 drop(state);
717 let result = Ok(output);
718 permit.publish(result.clone());
719 result
720 }
721
722 pub fn complete(
723 &self,
724 context: &TaskContext,
725 observation: CompletionObservation,
726 ) -> LifecycleOutcome {
727 self.prepare(context);
728 self.complete_ordered(context, observation).0
729 }
730
731 pub fn complete_once(
737 &self,
738 context: &TaskContext,
739 observation: CompletionObservation,
740 ) -> Option<LifecycleOutcome> {
741 self.prepare(context);
742 let (outcome, completed_now) = self.complete_ordered(context, observation);
743 completed_now.then_some(outcome)
744 }
745
746 fn complete_ordered(
747 &self,
748 context: &TaskContext,
749 observation: CompletionObservation,
750 ) -> (LifecycleOutcome, bool) {
751 let mut state = context
752 .shared
753 .state
754 .lock()
755 .unwrap_or_else(std::sync::PoisonError::into_inner);
756 loop {
757 match &*state {
758 RunState::Completed(outcome) => return (outcome.as_ref().clone(), false),
759 RunState::Completing => {
760 state = context
761 .shared
762 .completed
763 .wait(state)
764 .unwrap_or_else(std::sync::PoisonError::into_inner);
765 }
766 RunState::Open => {
767 *state = RunState::Completing;
768 break;
769 }
770 }
771 }
772 drop(state);
773 context.skip_through(
774 LifecycleStage::RecordLedger,
775 "surface ended before dispatch",
776 );
777
778 let fallback_observation = observation.clone();
779 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
780 self.finalize(context, observation)
781 }))
782 .unwrap_or_else(|_| {
783 tracing::error!(
784 task_id = context.task_id,
785 "execution lifecycle finalizer panicked"
786 );
787 self.finalize_after_panic(context, fallback_observation)
788 });
789 let mut state = context
790 .shared
791 .state
792 .lock()
793 .unwrap_or_else(std::sync::PoisonError::into_inner);
794 *state = RunState::Completed(Box::new(outcome.clone()));
795 context.shared.completed.notify_all();
796 (outcome, true)
797 }
798
799 fn complete_cancelled(
800 &self,
801 context: &TaskContext,
802 observation: &CompletionObservation,
803 completed_outcome: Option<LifecycleOutcome>,
804 ) -> LifecycleOutcome {
805 let outcome = if let Some(outcome) = completed_outcome {
808 outcome
809 } else {
810 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
813 self.finalize_through_economics(context, observation.clone())
814 }))
815 .unwrap_or_else(|_| self.finalize_after_panic(context, observation.clone()))
816 };
817 context.skip_through(LifecycleStage::Checkpoint, "execution cancelled");
818 self.finish_cleanup(context, observation);
819 self.spine
820 .outcomes
821 .lock()
822 .unwrap_or_else(std::sync::PoisonError::into_inner)
823 .entry(context.task_id.clone())
824 .or_insert_with(|| outcome.clone());
825 *context
826 .shared
827 .state
828 .lock()
829 .unwrap_or_else(std::sync::PoisonError::into_inner) =
830 RunState::Completed(Box::new(outcome.clone()));
831 context.shared.completed.notify_all();
832 outcome
833 }
834
835 fn complete_owned(
836 &self,
837 context: &TaskContext,
838 observation: CompletionObservation,
839 ) -> LifecycleOutcome {
840 context.skip_through(
841 LifecycleStage::RecordLedger,
842 "surface ended before dispatch",
843 );
844 let state = context
845 .shared
846 .state
847 .lock()
848 .unwrap_or_else(std::sync::PoisonError::into_inner);
849 if let RunState::Completed(outcome) = &*state {
850 return outcome.as_ref().clone();
851 }
852 drop(state);
853 let fallback_observation = observation.clone();
854 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
855 self.finalize(context, observation)
856 }))
857 .unwrap_or_else(|_| self.finalize_after_panic(context, fallback_observation));
858 let mut state = context
859 .shared
860 .state
861 .lock()
862 .unwrap_or_else(std::sync::PoisonError::into_inner);
863 *state = RunState::Completed(Box::new(outcome.clone()));
864 context.shared.completed.notify_all();
865 outcome
866 }
867
868 fn finalize(
869 &self,
870 context: &TaskContext,
871 observation: CompletionObservation,
872 ) -> LifecycleOutcome {
873 let telemetry = observation.clone();
874 let outcome = if context.completed_stages().len() >= 15 {
875 self.outcome_for(&context.task_id)
876 .unwrap_or_else(|| self.finalize_through_economics(context, observation))
877 } else {
878 self.finalize_through_economics(context, observation)
879 };
880 let _ = context.skip(LifecycleStage::Checkpoint, "checkpoint not configured");
881 self.finish_cleanup(context, &telemetry);
882 outcome
883 }
884
885 fn finalize_through_economics(
886 &self,
887 context: &TaskContext,
888 observation: CompletionObservation,
889 ) -> LifecycleOutcome {
890 TaskSpine::set(context.envelope.clone());
891 if let Some(outcome) = context.shared.computed_outcome.get() {
892 context.skip_through(
894 LifecycleStage::UpdateBreakEven,
895 "finalization already attempted",
896 );
897 return outcome.clone();
898 }
899
900 #[cfg(test)]
901 test_finalization_point(context, LifecycleStage::RecordEvidence, None);
902
903 let CompletionObservation {
904 input_tokens,
905 output_tokens,
906 model,
907 provider,
908 success: _,
909 outcome_signals,
910 shadow_auto_record,
911 shadow_tokens,
912 proxy_economics,
913 heatmap,
914 } = observation;
915 #[cfg(test)]
916 let _ = (
917 output_tokens,
918 &outcome_signals,
919 shadow_auto_record,
920 shadow_tokens,
921 );
922
923 let accepted_outcome =
925 evaluate_outcome_signals(&context.task_id, &context.profile_intent, &outcome_signals);
926
927 let assessment = (accepted_outcome.accepted != AcceptanceState::Unknown
928 && !outcome_signals.is_empty())
929 .then(|| {
930 let cost = ExecutionCost {
931 input_tokens,
932 output_tokens,
933 cache_read_tokens: 0,
934 model: model.clone(),
935 provider,
936 estimated_cost_micros: calculate_cost(input_tokens, output_tokens, 0, &model),
937 };
938 let outcome = TaskOutcome {
939 task_id: context.task_id.clone(),
940 completed: true,
941 signals: outcome_signals.clone(),
942 };
943 self.spine
944 .value_gate
945 .assess(&context.task_id, &cost, &outcome)
946 });
947
948 let outcome = LifecycleOutcome {
949 accepted_outcome,
950 assessment,
951 };
952 let _ = context.shared.computed_outcome.set(outcome.clone());
955
956 if let Some(assessment) = outcome.assessment.as_ref() {
957 #[cfg(not(test))]
958 self.record_evidence(context, output_tokens, shadow_tokens, assessment);
959 #[cfg(test)]
960 let _ = assessment;
961 let _ = context.advance(LifecycleStage::RecordEvidence);
962 } else {
963 let _ = context.skip(
964 LifecycleStage::RecordEvidence,
965 "outcome has no accepted evidence",
966 );
967 }
968 if let Some(assessment) = outcome.assessment.as_ref() {
969 self.spine
970 .assessments
971 .lock()
972 .unwrap_or_else(std::sync::PoisonError::into_inner)
973 .insert(context.task_id.clone(), assessment.clone());
974 }
975 self.spine
976 .outcomes
977 .lock()
978 .unwrap_or_else(std::sync::PoisonError::into_inner)
979 .insert(context.task_id.clone(), outcome.clone());
980 let _ = context.advance(LifecycleStage::RecordOutcome);
981 if let Some(assessment) = outcome.assessment.as_ref()
982 && context.entitlements.personalized_learning
983 {
984 #[cfg(not(test))]
985 crate::core::value_gate::record_assessment(assessment);
986 #[cfg(not(test))]
987 self.record_shadow(
988 context,
989 output_tokens,
990 &outcome_signals,
991 shadow_auto_record,
992 shadow_tokens,
993 assessment,
994 );
995 #[cfg(test)]
996 let _ = assessment;
997 let _ = context.advance(LifecycleStage::UpdateLearning);
998 } else {
999 let _ = context.skip(
1000 LifecycleStage::UpdateLearning,
1001 "not entitled or outcome unknown",
1002 );
1003 }
1004 let mut heatmaps = take_deferred_heatmap();
1005 if let Some(heatmap) = heatmap {
1006 heatmaps.push(heatmap);
1007 }
1008 if heatmaps.is_empty() {
1009 let _ = context.skip(LifecycleStage::UpdateHeatmap, "no file access recorded");
1010 } else {
1011 for heatmap in heatmaps {
1012 crate::core::heatmap::record_file_access(
1013 &heatmap.path,
1014 heatmap.original_tokens,
1015 heatmap.saved_tokens,
1016 );
1017 }
1018 let _ = context.advance(LifecycleStage::UpdateHeatmap);
1019 }
1020 if context.surface == ToolSurface::Proxy {
1021 #[cfg(test)]
1022 test_finalization_point(context, LifecycleStage::UpdateBreakEven, Some(&outcome));
1023 let economics = proxy_economics.unwrap_or_else(|| ProxyEconomicsObservation {
1024 tokens_pruned: 0,
1025 original_tokens: usize::try_from(input_tokens).unwrap_or(usize::MAX),
1026 task_class: context.triage_class.clone(),
1027 });
1028 #[cfg(not(test))]
1029 crate::proxy::value_gate_proxy::record_completion(
1030 economics.tokens_pruned,
1031 economics.original_tokens,
1032 &economics.task_class,
1033 outcome.accepted_outcome.accepted,
1034 );
1035 #[cfg(test)]
1036 let _ = economics;
1037 let _ = context.advance(LifecycleStage::UpdateBreakEven);
1038 } else {
1039 let _ = context.skip(LifecycleStage::UpdateBreakEven, "no provider economics");
1040 }
1041 outcome
1042 }
1043
1044 fn finish_cleanup(&self, context: &TaskContext, observation: &CompletionObservation) {
1045 if !context
1046 .completed_stages()
1047 .contains(&LifecycleStage::ScheduleTelemetry)
1048 && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1049 self.record_telemetry(context, observation);
1050 }))
1051 .is_err()
1052 {
1053 context.skip(LifecycleStage::ScheduleTelemetry, "telemetry panicked");
1054 }
1055 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1058 self.flush_state(context);
1059 }));
1060 }
1061
1062 fn record_telemetry(&self, context: &TaskContext, observation: &CompletionObservation) {
1063 if context
1064 .shared
1065 .telemetry_started
1066 .swap(true, std::sync::atomic::Ordering::AcqRel)
1067 {
1068 context.skip(
1069 LifecycleStage::ScheduleTelemetry,
1070 "telemetry already attempted",
1071 );
1072 return;
1073 }
1074 #[cfg(test)]
1075 test_finalization_point(context, LifecycleStage::ScheduleTelemetry, None);
1076 #[cfg(not(test))]
1077 {
1078 let metrics = crate::core::telemetry::global_metrics();
1079 metrics.record_tool_call(
1080 u64::try_from(context.start_time.elapsed().as_micros()).unwrap_or(u64::MAX),
1081 observation.success,
1082 );
1083 metrics.record_tokens(
1084 observation.input_tokens,
1085 observation.output_tokens,
1086 observation
1087 .input_tokens
1088 .saturating_sub(observation.output_tokens),
1089 );
1090 }
1091 #[cfg(test)]
1092 let _ = (context, observation);
1093 let _ = context.advance(LifecycleStage::ScheduleTelemetry);
1094 }
1095
1096 fn flush_state(&self, context: &TaskContext) {
1097 if context
1100 .shared
1101 .flush_started
1102 .swap(true, std::sync::atomic::Ordering::AcqRel)
1103 {
1104 return;
1105 }
1106 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1107 #[cfg(test)]
1108 {
1109 let hook = context
1110 .shared
1111 .flush_hook
1112 .lock()
1113 .unwrap_or_else(std::sync::PoisonError::into_inner)
1114 .clone();
1115 if let Some(hook) = hook {
1116 hook();
1117 return;
1118 }
1119 }
1120 crate::core::tool_lifecycle::flush_all();
1121 }));
1122 match result {
1123 Ok(()) => {
1124 let _ = context.advance(LifecycleStage::FlushState);
1125 }
1126 Err(payload) => {
1127 let _ = context.skip(LifecycleStage::FlushState, "state flush panicked");
1128 std::panic::resume_unwind(payload);
1129 }
1130 }
1131 }
1132
1133 fn finalize_after_panic(
1134 &self,
1135 context: &TaskContext,
1136 mut observation: CompletionObservation,
1137 ) -> LifecycleOutcome {
1138 observation.success = false;
1139 let outcome = context
1142 .shared
1143 .computed_outcome
1144 .get()
1145 .cloned()
1146 .unwrap_or_else(|| {
1147 let contract =
1148 OutcomeContractV1::for_task_class(task_class(&context.profile_intent));
1149 LifecycleOutcome {
1150 accepted_outcome: OutcomeEvaluator::new()
1151 .evaluate_with_context(
1152 &contract,
1153 &[],
1154 crate::core::outcome::evaluator::EvaluationContext::new(
1155 &context.task_id,
1156 &contract.contract_version,
1157 crate::core::outcome::evaluator::EVALUATOR_VERSION,
1158 ),
1159 )
1160 .outcome,
1161 assessment: None,
1162 }
1163 });
1164 context.skip_through(
1165 LifecycleStage::UpdateBreakEven,
1166 "lifecycle finalizer failed",
1167 );
1168 let _ = context.skip(LifecycleStage::Checkpoint, "lifecycle finalizer failed");
1169 self.finish_cleanup(context, &observation);
1170 if let Some(assessment) = outcome.assessment.as_ref() {
1171 self.spine
1172 .assessments
1173 .lock()
1174 .unwrap_or_else(std::sync::PoisonError::into_inner)
1175 .insert(context.task_id.clone(), assessment.clone());
1176 }
1177 self.spine
1178 .outcomes
1179 .lock()
1180 .unwrap_or_else(std::sync::PoisonError::into_inner)
1181 .insert(context.task_id.clone(), outcome.clone());
1182 outcome
1183 }
1184
1185 #[cfg(not(test))]
1186 fn record_evidence(
1187 &self,
1188 context: &TaskContext,
1189 output_tokens: u64,
1190 shadow_tokens: Option<(u64, u64)>,
1191 assessment: &ValueAssessment,
1192 ) {
1193 let (raw_input_tokens, compressed_input_tokens) =
1194 shadow_tokens.unwrap_or((output_tokens, output_tokens));
1195 let entry = crate::core::live_evidence_ledger::EvidenceLedgerEntry::completed(
1196 &context.task_id,
1197 &context.session_id,
1198 &context.triage_class,
1199 raw_input_tokens.saturating_sub(compressed_input_tokens),
1200 compressed_input_tokens,
1201 assessment.cpao_micros,
1202 assessment.outcome_accepted,
1203 );
1204 if let Err(error) = crate::core::live_evidence_ledger::append_completion(&entry) {
1205 tracing::warn!("failed to persist evidence ledger entry: {error}");
1206 }
1207 }
1208
1209 #[cfg(not(test))]
1210 fn record_shadow(
1211 &self,
1212 context: &TaskContext,
1213 output_tokens: u64,
1214 outcome_signals: &[OutcomeSignal],
1215 shadow_auto_record: bool,
1216 shadow_tokens: Option<(u64, u64)>,
1217 assessment: &ValueAssessment,
1218 ) {
1219 let (raw_input_tokens, compressed_input_tokens) =
1220 shadow_tokens.unwrap_or((output_tokens, output_tokens));
1221 if !shadow_auto_record || !assessment.outcome_accepted {
1222 return;
1223 }
1224 let duration_ms =
1225 u64::try_from(context.start_time.elapsed().as_millis()).unwrap_or(u64::MAX);
1226 let task = crate::core::shadow::ShadowTask {
1227 task_id: assessment.task_id.clone(),
1228 query: format!("{}: {}", context.profile_intent, context.profile_complexity),
1229 raw_input_tokens,
1230 compressed_input_tokens,
1231 output_tokens,
1232 model_used: assessment.model.clone(),
1233 outcome_signals: outcome_signals.to_vec(),
1234 duration_ms,
1235 };
1236 let _ = std::thread::Builder::new()
1237 .name("lean-ctx-shadow".into())
1238 .spawn(move || crate::core::shadow::runtime::ShadowRuntime::on_task_complete(&task));
1239 }
1240
1241 pub fn profile_for_session(&self, session_id: &str) -> Option<TaskProfileLocal> {
1242 self.spine.profile_for_session(session_id)
1243 }
1244
1245 pub fn assessment_for(&self, task_id: &str) -> Option<ValueAssessment> {
1246 self.spine.assessment_for(task_id)
1247 }
1248
1249 pub fn outcome_for(&self, task_id: &str) -> Option<LifecycleOutcome> {
1250 self.spine
1251 .outcomes
1252 .lock()
1253 .unwrap_or_else(std::sync::PoisonError::into_inner)
1254 .get(task_id)
1255 .cloned()
1256 }
1257}
1258
1259pub struct LifecycleGuard<'a> {
1261 lifecycle: &'a ExecutionLifecycle,
1262 context: TaskContext,
1263 prepare_missing: bool,
1264 cancellation: Option<CancellationHandler>,
1265 observation: Mutex<Option<CompletionObservation>>,
1266 outcome: Mutex<Option<LifecycleOutcome>>,
1267}
1268
1269struct DispatchPermit {
1270 shared: Arc<SharedRun>,
1271 published: bool,
1272}
1273
1274impl DispatchPermit {
1275 fn new(shared: Arc<SharedRun>) -> Self {
1276 Self {
1277 shared,
1278 published: false,
1279 }
1280 }
1281
1282 fn publish<T: Send + Sync + 'static>(&mut self, result: T) {
1283 *self
1284 .shared
1285 .dispatch
1286 .lock()
1287 .unwrap_or_else(std::sync::PoisonError::into_inner) =
1288 DispatchState::Finished(Arc::new(result));
1289 self.published = true;
1290 self.shared.dispatch_completed.notify_waiters();
1291 }
1292}
1293
1294impl Drop for DispatchPermit {
1295 fn drop(&mut self) {
1296 if self.published {
1297 return;
1298 }
1299 let mut dispatch = self
1300 .shared
1301 .dispatch
1302 .lock()
1303 .unwrap_or_else(std::sync::PoisonError::into_inner);
1304 let terminal = match &*self
1305 .shared
1306 .state
1307 .lock()
1308 .unwrap_or_else(std::sync::PoisonError::into_inner)
1309 {
1310 RunState::Completed(outcome) => Some(outcome.clone()),
1311 RunState::Open | RunState::Completing => None,
1312 };
1313 *dispatch = terminal.map_or(DispatchState::Idle, DispatchState::Aborted);
1314 self.shared.dispatch_completed.notify_waiters();
1315 }
1316}
1317
1318impl<'a> LifecycleGuard<'a> {
1319 pub fn new(lifecycle: &'a ExecutionLifecycle, context: TaskContext) -> Self {
1320 lifecycle.prepare(&context);
1321 Self {
1322 lifecycle,
1323 context,
1324 prepare_missing: true,
1325 cancellation: None,
1326 observation: Mutex::new(None),
1327 outcome: Mutex::new(None),
1328 }
1329 }
1330
1331 fn for_run(
1332 lifecycle: &'a ExecutionLifecycle,
1333 context: TaskContext,
1334 cancellation: Option<CancellationHandler>,
1335 ) -> Self {
1336 Self {
1337 lifecycle,
1338 context,
1339 prepare_missing: false,
1340 cancellation,
1341 observation: Mutex::new(None),
1342 outcome: Mutex::new(None),
1343 }
1344 }
1345
1346 pub const fn context(&self) -> &TaskContext {
1347 &self.context
1348 }
1349
1350 pub fn complete(&self, observation: CompletionObservation) -> LifecycleOutcome {
1351 if self.prepare_missing {
1352 self.lifecycle.complete(&self.context, observation)
1353 } else {
1354 self.lifecycle.complete_owned(&self.context, observation)
1355 }
1356 }
1357}
1358
1359impl Drop for LifecycleGuard<'_> {
1360 fn drop(&mut self) {
1361 if self.context.outcome().is_some() {
1362 return;
1363 }
1364 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1365 let mut observation = CompletionObservation::tool_result(0, 0, "unknown", false);
1366 observation.outcome_signals.clear();
1368 if !self
1369 .context
1370 .completed_stages()
1371 .contains(&LifecycleStage::RecordLedger)
1372 {
1373 self.context.skip_through(
1374 LifecycleStage::RecordContextIr,
1375 "execution cancelled before stage completed",
1376 );
1377 let mut ledger = StageDisposition::Skipped("execution cancelled before ledger");
1378 if let Some(handler) = self.cancellation.take() {
1379 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(handler)) {
1380 Ok(completion) => {
1381 observation = completion.observation;
1382 ledger = completion.ledger;
1383 }
1384 Err(_) => {
1385 ledger = StageDisposition::Skipped("cancellation ledger panicked");
1386 }
1387 }
1388 }
1389 self.context
1390 .record_stage(LifecycleStage::RecordLedger, ledger);
1391 }
1392 if let Some(saved) = self
1393 .observation
1394 .lock()
1395 .unwrap_or_else(std::sync::PoisonError::into_inner)
1396 .take()
1397 {
1398 observation = saved;
1399 }
1400 let completed_outcome = self
1401 .outcome
1402 .lock()
1403 .unwrap_or_else(std::sync::PoisonError::into_inner)
1404 .take();
1405 let _ = if self.prepare_missing {
1406 self.lifecycle.complete(&self.context, observation)
1407 } else {
1408 self.lifecycle
1409 .complete_cancelled(&self.context, &observation, completed_outcome)
1410 };
1411 }));
1412 }
1413}
1414
1415pub(crate) fn evaluate_outcome_signals(
1418 task_id: &str,
1419 profile_intent: &str,
1420 signals: &[OutcomeSignal],
1421) -> AcceptedOutcomeV1 {
1422 let signals = canonical_signals(signals, task_id);
1423 let contract = OutcomeContractV1::for_task_class(task_class(profile_intent));
1424 let context = crate::core::outcome::evaluator::EvaluationContext::new(
1425 task_id,
1426 &contract.contract_version,
1427 crate::core::outcome::evaluator::EVALUATOR_VERSION,
1428 );
1429 OutcomeEvaluator::new()
1430 .evaluate_with_context(&contract, &signals, context)
1431 .outcome
1432}
1433
1434fn task_class(value: &str) -> TaskClass {
1435 match value {
1436 "coding_fix" | "bug_fix" | "debugging" => TaskClass::BugFix,
1437 "refactor" | "coding_refactor" => TaskClass::Refactor,
1438 "test_addition" => TaskClass::TestAddition,
1439 "documentation" | "docs" => TaskClass::Documentation,
1440 _ => TaskClass::Investigation,
1441 }
1442}
1443
1444fn canonical_signals(signals: &[OutcomeSignal], task_id: &str) -> Vec<CanonicalSignal> {
1445 signals
1446 .iter()
1447 .map(|signal| {
1448 let signal = match signal {
1449 OutcomeSignal::BuildSucceeded => LocalSignalAdapters::build_success(true),
1450 OutcomeSignal::TestsPassed => LocalSignalAdapters::tests_passing(true),
1451 OutcomeSignal::LintClean => LocalSignalAdapters::lint_clean(true),
1452 OutcomeSignal::UserAccepted => LocalSignalAdapters::human_acceptance(true),
1453 OutcomeSignal::UserRejected => LocalSignalAdapters::human_acceptance(false),
1454 OutcomeSignal::CompileError => LocalSignalAdapters::build_success(false),
1455 OutcomeSignal::TestFailed => LocalSignalAdapters::tests_passing(false),
1456 };
1457 signal.with_evidence_ref(format!("task:{task_id}"))
1458 })
1459 .collect()
1460}
1461
1462#[cfg(test)]
1463#[path = "execution_lifecycle_tests.rs"]
1464mod tests;