lean-ctx 3.11.4

LeanCTX Engine: the open-source runtime for the Context Gateway for AI Systems. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::Result;

use crate::core::agent_connector::capability::{AgentConnectorAdapter, AgentExecutionPolicy};
use crate::core::agent_connector::traits::{AgentConnector, TaskRequest, TaskResult};
#[cfg(test)]
use crate::core::agent_connector::traits::{AgentInfo, TokenUsage};
use crate::core::benchmark_spec::types::{
    BenchmarkEvaluation, BenchmarkOutcome, BenchmarkResult, BenchmarkSpecV1, BenchmarkSummary,
    BenchmarkTask, EvaluationSpecV1, TaskKind,
};
use crate::core::eval_ab::scorers::{CodeScorer, Scorer, score_task};
use crate::core::eval_ab::suite::{Domain, Task as EvaluationTask};
use crate::core::ocla::adapters::AdapterRegistry;
use crate::core::ocla::invocation::PolicyConstraints;

const DEFAULT_TIMEOUT_MS: u64 = 300_000;

#[cfg(test)]
pub(crate) struct MockConnector {
    should_succeed: bool,
}

#[cfg(test)]
impl MockConnector {
    pub(crate) fn new(should_succeed: bool) -> Self {
        Self { should_succeed }
    }
}

#[cfg(test)]
impl AgentConnector for MockConnector {
    fn supports_model_selection(&self) -> bool {
        true
    }
    fn info(&self) -> AgentInfo {
        AgentInfo {
            name: "mock".into(),
            version: Some("1.0.0".into()),
            path: PathBuf::from("/usr/bin/mock"),
            capabilities: vec!["execute".into()],
            available: true,
        }
    }

    fn health_check_with_timeout(&self, _timeout_ms: u64) -> Result<bool> {
        Ok(true)
    }

    fn execute(&self, request: &TaskRequest) -> Result<TaskResult> {
        Ok(TaskResult {
            task_id: request.id.clone(),
            agent: "mock".into(),
            model: "test-model".into(),
            success: self.should_succeed,
            exit_code: i32::from(!self.should_succeed),
            stdout: "task output".into(),
            stderr: String::new(),
            duration_ms: 1000,
            tokens_used: Some(TokenUsage {
                input_tokens: 500,
                output_tokens: 200,
                cache_read_tokens: 0,
                cache_write_tokens: 0,
            }),
            provider_cost_micros: None,
            execution_receipt_ref: None,
            termination: None,
        })
    }

    fn name(&self) -> &'static str {
        "mock"
    }
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) struct RunConfig {
    pub agent_name: String,
    pub profile_name: String,
    pub suite_name: Option<String>,
    pub timeout_override_ms: Option<u64>,
    pub working_dir: PathBuf,
    pub repeats: u32,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            agent_name: String::new(),
            profile_name: "coder".into(),
            suite_name: None,
            timeout_override_ms: None,
            working_dir: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            repeats: 1,
        }
    }
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) enum RunProgress {
    Starting,
    DetectingAgents,
    LoadingProfile,
    RunningTask {
        task_index: usize,
        total: usize,
        task_id: String,
    },
    TaskComplete {
        task_id: String,
        passed: bool,
    },
    AllComplete,
}

#[allow(dead_code)]
pub(crate) struct LocalRunner {
    config: RunConfig,
    connector: Arc<AgentConnectorAdapter>,
    adapters: AdapterRegistry,
}

#[allow(dead_code)]
impl LocalRunner {
    pub(crate) fn with_policy(
        config: RunConfig,
        connector: Box<dyn AgentConnector>,
        policy: AgentExecutionPolicy,
    ) -> Result<Self> {
        let connector = Arc::new(AgentConnectorAdapter::new(Arc::from(connector), policy)?);
        let adapters = AdapterRegistry::new();
        adapters.register_arc(connector.clone())?;
        Ok(Self {
            config,
            connector,
            adapters,
        })
    }

    /// Only the explicitly selected live benchmark/calibration host calls this.
    /// Directory admission bounds the initial cwd, not the agent's filesystem access.
    pub(crate) fn for_live_benchmark(
        config: RunConfig,
        connector: Box<dyn AgentConnector>,
        model: Option<String>,
    ) -> Result<Self> {
        let policy = AgentExecutionPolicy::new(
            &config.working_dir,
            PolicyConstraints {
                allow_remote: true,
                allowed_models: model.into_iter().collect(),
                ..PolicyConstraints::default()
            },
            3_600_000,
        )?;
        Self::with_policy(config, connector, policy)
    }

    pub(crate) fn run(&self, spec: &BenchmarkSpecV1) -> Result<BenchmarkResult> {
        self.run_with_profile(spec, &self.config.profile_name)
    }

    pub(crate) fn run_with_profile(
        &self,
        spec: &BenchmarkSpecV1,
        profile_name: &str,
    ) -> Result<BenchmarkResult> {
        self.run_with_profile_progress(spec, profile_name, |_| {})
    }

    pub(crate) fn run_with_progress<F>(
        &self,
        spec: &BenchmarkSpecV1,
        on_progress: F,
    ) -> Result<BenchmarkResult>
    where
        F: Fn(RunProgress),
    {
        self.run_with_profile_progress(spec, &self.config.profile_name, on_progress)
    }

    fn run_with_profile_progress<F>(
        &self,
        spec: &BenchmarkSpecV1,
        profile_name: &str,
        on_progress: F,
    ) -> Result<BenchmarkResult>
    where
        F: Fn(RunProgress),
    {
        spec.validate()
            .map_err(|error| anyhow::anyhow!("invalid benchmark spec: {error}"))?;
        on_progress(RunProgress::Starting);
        let total = spec.suite.tasks.len();
        let repeats = spec.configuration.repeats;
        let mut outcomes = Vec::with_capacity(total * repeats as usize);

        for repeat in 0..repeats {
            for (idx, task) in spec.suite.tasks.iter().enumerate() {
                on_progress(RunProgress::RunningTask {
                    task_index: idx + (repeat as usize * total),
                    total: total * repeats as usize,
                    task_id: task.id.clone(),
                });
                let request = self.task_request_for_profile(spec, task, profile_name);
                let invocation = self.connector.invocation(request);
                let (result, common) = self
                    .connector
                    .execute_registered(&self.adapters, &invocation)?;
                let mut outcome =
                    outcome_from_task_result(task, &result, &self.config.working_dir)?;
                outcome.capability_observation = Some(common.observation);
                let passed = outcome.passed;
                on_progress(RunProgress::TaskComplete {
                    task_id: task.id.clone(),
                    passed,
                });
                outcomes.push(outcome);
            }
        }

        let summary = BenchmarkSummary::from_outcomes(&outcomes, spec.configuration.quality_floor);
        on_progress(RunProgress::AllComplete);

        Ok(BenchmarkResult {
            spec_id: spec.id.clone(),
            spec_version: spec.version.clone(),
            profile_hash: spec.configuration.profile_hash.clone().unwrap_or_default(),
            agent: self.connector.name().to_owned(),
            model: spec
                .configuration
                .model
                .clone()
                .unwrap_or_else(|| "unknown".to_owned()),
            runtime_version: spec.configuration.runtime_version.clone(),
            outcomes,
            summary,
            completed_at: current_unix_timestamp(),
        })
    }

    fn task_request(&self, spec: &BenchmarkSpecV1, task: &BenchmarkTask) -> TaskRequest {
        self.task_request_for_profile(spec, task, &self.config.profile_name)
    }

    fn task_request_for_profile(
        &self,
        spec: &BenchmarkSpecV1,
        task: &BenchmarkTask,
        profile_name: &str,
    ) -> TaskRequest {
        TaskRequest {
            id: task.id.clone(),
            prompt: task_to_prompt(task),
            working_dir: self.config.working_dir.clone(),
            timeout_ms: self
                .config
                .timeout_override_ms
                .or(task.timeout_ms)
                .unwrap_or(DEFAULT_TIMEOUT_MS),
            model: spec.configuration.model.clone(),
            max_turns: None,
            profile_name: Some(profile_name.to_owned()),
            profile_hash: spec.configuration.profile_hash.clone(),
            delivery_profile: None,
        }
    }
}

#[allow(dead_code)]
pub(crate) fn task_to_prompt(task: &BenchmarkTask) -> String {
    let kind_instruction = match task.kind {
        TaskKind::Explore => "Explore and understand the repository structure.",
        TaskKind::LocateRegression => "Find the source of a regression in the codebase.",
        TaskKind::FixBug => "Diagnose and fix the reported bug.",
        TaskKind::RunTests => "Run the project's test suite and report results.",
        TaskKind::ExplainArchitecture => "Produce a clear architectural summary.",
        TaskKind::Custom => "Complete the following task as described.",
    };
    format!("{kind_instruction}\n\n{}", task.description)
}

fn outcome_from_task_result(
    task: &BenchmarkTask,
    result: &TaskResult,
    working_dir: &std::path::Path,
) -> Result<BenchmarkOutcome> {
    let tokens_in = result.tokens_used.as_ref().map_or(0, |t| t.input_tokens);
    let tokens_out = result.tokens_used.as_ref().map_or(0, |t| t.output_tokens);
    let cost = result
        .provider_cost_micros
        .map_or(0.0, |micros| micros as f64 / 1_000_000.0);
    let evaluation = task
        .evaluation
        .as_ref()
        .map(|spec| evaluate_task(task, spec, &result.stdout, working_dir))
        .transpose()?;
    let (passed, quality_score) = evaluation.as_ref().map_or((false, 0.0), |evaluation| {
        (evaluation.passed, evaluation.score)
    });
    let error = match (result.stderr.trim(), result.success) {
        (stderr, _) if !stderr.is_empty() => Some(stderr.to_owned()),
        (_, false) => Some(format!("agent exited with code {}", result.exit_code)),
        _ => None,
    };
    Ok(BenchmarkOutcome {
        task_id: task.id.clone(),
        passed,
        cost_usd: cost,
        quality_score,
        latency_ms: result.duration_ms,
        tokens_input: tokens_in,
        tokens_output: tokens_out,
        error,
        evaluation,
        execution_receipt_ref: result.execution_receipt_ref.clone(),
        capability_observation: None,
    })
}

fn evaluate_task(
    task: &BenchmarkTask,
    spec: &EvaluationSpecV1,
    output: &str,
    working_dir: &std::path::Path,
) -> Result<BenchmarkEvaluation> {
    spec.validate().map_err(anyhow::Error::msg)?;
    match spec {
        EvaluationSpecV1::Qa {
            answers,
            minimum_f1,
        } => {
            let evaluation_task = EvaluationTask {
                id: task.id.clone(),
                domain: Domain::Qa,
                task_class: None,
                prompt: task.description.clone(),
                workspace: working_dir.display().to_string(),
                retrieval_query: None,
                answers: answers.clone(),
                target_file: None,
                test_cmd: None,
            };
            let score = score_task(&evaluation_task, output, working_dir)?;
            Ok(BenchmarkEvaluation {
                evaluator_id: spec.id().to_owned(),
                metric: score.metric,
                score: score.value,
                passed: score.passed && score.value >= *minimum_f1,
                detail: score.detail,
                output_digest: blake3::hash(output.as_bytes()).to_hex().to_string(),
            })
        }
        EvaluationSpecV1::Code {
            target_file,
            test_cmd,
        } => {
            let evaluation_task = EvaluationTask {
                id: task.id.clone(),
                domain: Domain::Code,
                task_class: None,
                prompt: task.description.clone(),
                workspace: working_dir.display().to_string(),
                retrieval_query: None,
                answers: Vec::new(),
                target_file: Some(target_file.clone()),
                test_cmd: Some(test_cmd.clone()),
            };
            let score = CodeScorer::isolated().score(&evaluation_task, output, working_dir)?;
            Ok(BenchmarkEvaluation {
                evaluator_id: spec.id().to_owned(),
                metric: score.metric,
                score: score.value,
                passed: score.passed,
                detail: score.detail,
                output_digest: blake3::hash(output.as_bytes()).to_hex().to_string(),
            })
        }
    }
}

fn current_unix_timestamp() -> String {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn test_spec() -> BenchmarkSpecV1 {
        use crate::core::benchmark_spec::types::{
            BenchmarkConfiguration, BenchmarkKind, BenchmarkSuite,
        };
        BenchmarkSpecV1 {
            id: "test-spec".into(),
            version: "1.0.0".into(),
            name: "Test".into(),
            description: "Test benchmark".into(),
            suite: BenchmarkSuite {
                kind: BenchmarkKind::TaskScore,
                tasks: vec![
                    BenchmarkTask {
                        id: "t1".into(),
                        name: "Task 1".into(),
                        description: "Do task 1".into(),
                        kind: TaskKind::Explore,
                        timeout_ms: Some(60_000),
                        evaluation: Some(EvaluationSpecV1::Qa {
                            answers: vec!["task output".into()],
                            minimum_f1: 1.0,
                        }),
                    },
                    BenchmarkTask {
                        id: "t2".into(),
                        name: "Task 2".into(),
                        description: "Do task 2".into(),
                        kind: TaskKind::FixBug,
                        timeout_ms: Some(120_000),
                        evaluation: Some(EvaluationSpecV1::Qa {
                            answers: vec!["task output".into()],
                            minimum_f1: 1.0,
                        }),
                    },
                ],
            },
            configuration: BenchmarkConfiguration {
                profile_hash: Some("abc123".into()),
                agent: None,
                model: None,
                runtime_version: "test".into(),
                repeats: 1,
                quality_floor: 0.95,
            },
            created_at: "0".into(),
        }
    }

    #[test]
    fn new_runner_sets_config() {
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();
        assert_eq!(runner.config.profile_name, "coder");
    }

    #[test]
    fn run_with_mock_connector() {
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();
        let result = runner.run(&test_spec()).unwrap();
        assert_eq!(result.outcomes.len(), 2);
        assert!(result.outcomes.iter().all(|o| o.passed));
        assert_eq!(result.summary.passed_tasks, 2);
        assert!(result.summary.quality_evaluated);
        assert!(!result.summary.receipt_evidence_complete);
    }

    #[test]
    fn repeated_observations_do_not_promote_process_success_to_quality() {
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();
        let mut spec = test_spec();
        spec.configuration.repeats = 2;
        for task in &mut spec.suite.tasks {
            task.evaluation = None;
        }
        let result = runner.run(&spec).unwrap();
        let ids: Vec<_> = result
            .outcomes
            .iter()
            .map(|outcome| {
                let observation = outcome.capability_observation.as_ref().unwrap();
                assert!(observation.success);
                assert_eq!(observation.task_id, outcome.task_id);
                assert!(!outcome.passed);
                assert!(outcome.evaluation.is_none());
                assert!(outcome.execution_receipt_ref.is_none());
                outcome.task_id.as_str()
            })
            .collect();
        assert_eq!(ids, ["t1", "t2", "t1", "t2"]);
        assert!(!result.summary.quality_evaluated);
        assert!(!result.summary.quality_floor_met);
        assert!(!result.summary.receipt_evidence_complete);
    }

    #[test]
    fn failed_invocation_observation_is_retained_without_receipt_promotion() {
        use crate::core::ocla::invocation::CapabilityFailureMode;
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(false)),
            None,
        )
        .unwrap();
        let result = runner.run(&test_spec()).unwrap();
        assert_eq!(result.outcomes.len(), 2);
        for outcome in &result.outcomes {
            let observation = outcome.capability_observation.as_ref().unwrap();
            assert!(!observation.success);
            assert_eq!(
                observation.failure_mode,
                Some(CapabilityFailureMode::Internal)
            );
            assert!(outcome.error.is_some());
            assert!(outcome.execution_receipt_ref.is_none());
        }
        assert!(!result.summary.receipt_evidence_complete);
    }

    #[cfg(unix)]
    #[test]
    fn live_runner_executes_its_registered_real_process_and_denies_unadmitted_host() {
        use crate::core::agent_connector::codex::CodexConnector;
        use crate::core::ocla::invocation::CapabilityAdapter;
        use std::os::unix::fs::PermissionsExt;
        let root = tempfile::tempdir().unwrap();
        let executable = root.path().join("fixture-codex");
        std::fs::write(&executable, "#!/bin/sh\nprintf call >> \"$0.calls\"\nif [ \"$1\" = '--version' ]; then printf 'fixture 1.0'; exit 0; fi\nprintf task >> \"$0.tasks\"\nprintf 'task output'\n").unwrap();
        std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap();
        // A fresh executable can undergo OS security assessment before its
        // first instruction. Prepare this known fixture once, without changing
        // the production probe deadline or retrying the operation under test.
        let prepared = crate::core::process_capture::run_with_timeout(
            std::process::Command::new(&executable).arg("--version"),
            std::time::Duration::from_secs(10),
        )
        .expect("capture fixture readiness diagnostics");
        assert!(
            !prepared.timed_out && prepared.output.status.success(),
            "fixture preparation failed: timeout={}, status={:?}, stdout={:?}, stderr={:?}",
            prepared.timed_out,
            prepared.output.status,
            String::from_utf8_lossy(&prepared.output.stdout),
            String::from_utf8_lossy(&prepared.output.stderr),
        );
        assert_eq!(prepared.output.stdout, b"fixture 1.0");
        let calls_path = root.path().join("fixture-codex.calls");
        let prepared_calls = std::fs::read(&calls_path).unwrap();
        assert_eq!(prepared_calls, b"call");
        assert!(!root.path().join("fixture-codex.tasks").exists());
        let info = AgentInfo {
            name: "codex".into(),
            version: Some("fixture 1.0".into()),
            path: executable.clone(),
            capabilities: vec![],
            available: true,
        };
        let config = RunConfig {
            working_dir: root.path().to_owned(),
            ..RunConfig::default()
        };
        let policy =
            AgentExecutionPolicy::new(root.path(), PolicyConstraints::default(), 300_000).unwrap();
        let denied = LocalRunner::with_policy(
            config.clone(),
            Box::new(CodexConnector::new(info.clone())),
            policy,
        )
        .unwrap();
        assert!(denied.run(&test_spec()).is_err());
        assert_eq!(std::fs::read(&calls_path).unwrap(), prepared_calls);
        let runner =
            LocalRunner::for_live_benchmark(config, Box::new(CodexConnector::new(info)), None)
                .unwrap();
        let manifest = runner.connector.manifest();
        let registered = runner
            .adapters
            .lookup(manifest.capability_id.as_str(), &manifest.version)
            .unwrap();
        let expected: Arc<dyn CapabilityAdapter> = runner.connector.clone();
        assert!(Arc::ptr_eq(&registered, &expected));
        let spec = test_spec();
        let result = runner.run(&spec).unwrap();
        assert_eq!(result.outcomes.len(), 2);
        assert_eq!(
            std::fs::read_to_string(root.path().join("fixture-codex.tasks")).unwrap(),
            "tasktask"
        );
        let json: serde_json::Value =
            serde_json::from_str(&crate::core::benchmark_spec::report::format_json(&result))
                .unwrap();
        for (index, (task, outcome)) in spec.suite.tasks.iter().zip(&result.outcomes).enumerate() {
            use crate::core::ocla::invocation::{CapabilityObservationV1, evidence_ref};
            let actual = outcome.capability_observation.as_ref().unwrap();
            let request = runner.task_request_for_profile(&spec, task, &runner.config.profile_name);
            let input_tokens = crate::core::tokens::count_tokens(&request.prompt) as u64;
            let invocation = runner.connector.invocation(request);
            let mut expected = CapabilityObservationV1::success(
                &invocation,
                input_tokens,
                crate::core::tokens::count_tokens("task output") as u64,
                actual.latency_ms,
                Some(evidence_ref("task output")),
            );
            expected
                .metrics
                .insert("local_payload_token_measurement".into(), 1);
            assert_eq!(actual, &expected);
            assert!(actual.latency_ms <= invocation.timeout_ms);
            assert!(actual.latency_ms >= outcome.latency_ms);
            assert!(outcome.execution_receipt_ref.is_none());
            assert_eq!(
                json["outcomes"][index]["capability_observation"],
                serde_json::to_value(expected).unwrap()
            );
        }
    }

    #[test]
    fn evaluator_not_exit_code_decides_quality_and_preserves_receipt_link() {
        let mut spec = test_spec();
        let task = spec.suite.tasks.remove(0);
        let result = TaskResult {
            task_id: task.id.clone(),
            agent: "mock".into(),
            model: "test-model".into(),
            success: false,
            exit_code: 1,
            stdout: "task output".into(),
            stderr: String::new(),
            duration_ms: 1000,
            tokens_used: None,
            provider_cost_micros: None,
            execution_receipt_ref: Some("receipt:task-1".into()),
            termination: None,
        };

        let outcome = outcome_from_task_result(&task, &result, std::path::Path::new("."))
            .expect("declared evaluator should score output");

        assert!(outcome.passed);
        assert_eq!(outcome.quality_score, 1.0);
        assert_eq!(
            outcome.execution_receipt_ref.as_deref(),
            Some("receipt:task-1")
        );
        assert_eq!(outcome.error.as_deref(), Some("agent exited with code 1"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn isolated_code_evaluator_scores_a_fixture_without_touching_the_workspace() {
        let workspace = tempfile::tempdir().expect("temporary fixture workspace");
        std::fs::write(
            workspace.path().join("solution.sh"),
            "add() { printf '%s\\n' 0; }\n",
        )
        .expect("write broken fixture");
        std::fs::write(
            workspace.path().join("test.sh"),
            ". ./solution.sh\n[ \"$(add 2 3)\" = \"5\" ]\n",
        )
        .expect("write deterministic test");
        let task = BenchmarkTask {
            id: "repair".into(),
            name: "Repair".into(),
            description: "Return the repaired solution.".into(),
            kind: TaskKind::FixBug,
            timeout_ms: None,
            evaluation: Some(EvaluationSpecV1::Code {
                target_file: "solution.sh".into(),
                test_cmd: "sh test.sh".into(),
            }),
        };

        let evaluation = evaluate_task(
            &task,
            task.evaluation.as_ref().expect("evaluator"),
            "add() { printf '%s\\n' \"$(( $1 + $2 ))\"; }",
            workspace.path(),
        )
        .expect("isolated evaluator must run");

        assert_eq!(evaluation.evaluator_id, "code-unit-test-v1");
        assert_eq!(evaluation.metric, "unit_test");
        assert!(evaluation.passed);
        assert_eq!(
            std::fs::read_to_string(workspace.path().join("solution.sh"))
                .expect("original fixture remains readable"),
            "add() { printf '%s\\n' 0; }\n"
        );
    }

    #[test]
    fn outcome_uses_only_explicit_provider_cost() {
        let mut spec = test_spec();
        let task = spec.suite.tasks.remove(0);
        let result = TaskResult {
            task_id: task.id.clone(),
            agent: "mock".into(),
            model: "test-model".into(),
            success: true,
            exit_code: 0,
            stdout: "task output".into(),
            stderr: String::new(),
            duration_ms: 1_000,
            tokens_used: Some(TokenUsage {
                input_tokens: 1_000,
                output_tokens: 500,
                cache_read_tokens: 0,
                cache_write_tokens: 0,
            }),
            provider_cost_micros: Some(42),
            execution_receipt_ref: Some("receipt:task-1".into()),
            termination: None,
        };

        let outcome = outcome_from_task_result(&task, &result, std::path::Path::new("."))
            .expect("declared evaluator should score output");
        assert!((outcome.cost_usd - 0.000_042).abs() < f64::EPSILON);

        let unpriced = TaskResult {
            provider_cost_micros: None,
            ..result
        };
        let outcome = outcome_from_task_result(&task, &unpriced, std::path::Path::new("."))
            .expect("declared evaluator should score output");
        assert_eq!(outcome.cost_usd, 0.0);
    }

    #[test]
    fn missing_evaluator_blocks_quality_floor() {
        let mut spec = test_spec();
        spec.suite.tasks[0].evaluation = None;
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();

        let result = runner
            .run(&spec)
            .expect("runner should preserve observed output");

        assert!(!result.summary.quality_evaluated);
        assert!(!result.summary.quality_floor_met);
        assert!(!result.outcomes[0].passed);
    }

    #[test]
    fn task_request_uses_task_timeout_then_default() {
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();
        let spec = test_spec();

        assert_eq!(
            runner.task_request(&spec, &spec.suite.tasks[0]).timeout_ms,
            60_000
        );

        let task_without_timeout = BenchmarkTask {
            id: "default-timeout".into(),
            name: "Default timeout".into(),
            description: "Use the runner default".into(),
            kind: TaskKind::Custom,
            timeout_ms: None,
            evaluation: None,
        };
        assert_eq!(
            runner.task_request(&spec, &task_without_timeout).timeout_ms,
            DEFAULT_TIMEOUT_MS
        );
    }

    #[test]
    fn task_request_uses_explicit_run_profile() {
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();
        let spec = test_spec();
        let request = runner.task_request_for_profile(&spec, &spec.suite.tasks[0], "benchmark-a");

        assert_eq!(request.profile_name.as_deref(), Some("benchmark-a"));
    }

    #[test]
    fn progress_callback_fires() {
        let counter = AtomicUsize::new(0);
        let runner = LocalRunner::for_live_benchmark(
            RunConfig::default(),
            Box::new(MockConnector::new(true)),
            None,
        )
        .unwrap();
        runner
            .run_with_progress(&test_spec(), |_| {
                counter.fetch_add(1, Ordering::Relaxed);
            })
            .unwrap();
        assert_eq!(counter.load(Ordering::Relaxed), 6);
    }

    #[test]
    fn task_to_prompt_covers_all_kinds() {
        for kind in &[
            TaskKind::Explore,
            TaskKind::LocateRegression,
            TaskKind::FixBug,
            TaskKind::RunTests,
            TaskKind::ExplainArchitecture,
            TaskKind::Custom,
        ] {
            let task = BenchmarkTask {
                id: "test".into(),
                name: "Test".into(),
                description: "Test task".into(),
                kind: *kind,
                timeout_ms: None,
                evaluation: None,
            };
            let prompt = task_to_prompt(&task);
            assert!(!prompt.is_empty());
            assert!(prompt.contains(&task.description));
        }
    }
}