blyte 0.82.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
//! Headless single-shot solver runner for executing direct agent prompts.
//!
//! Wires together the configured LLM provider, execution shell (local host or container sandbox),
//! filesystem abstraction, context strategy, and verification gate runner into an autonomous loop.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex};

/// Fold budget for research runs, which quote code read many turns before they write it up.
/// High enough that folding is only a safety net: unfolded research runs were cheaper, shorter and
/// invented fewer names than runs folded at 96k (`docs/specs/2026-10-19-claim-check.md`, FX).
pub const RESEARCH_FOLD_BUDGET: usize = 180_000;

/// Tracks turn and gate progress across the run, for the deadline watchdog.
#[derive(Debug, Default, Clone, Copy)]
pub struct Progress {
    pub turns: u32,
    pub gate_attempts: u32,
    pub in_gate: bool,
    pub gate_wait_ms: u64,
    pub usage: blyte_provider::Usage,
}

/// Saved-originals configuration for an in-place run (`--snapshot-dir`, `--snapshot-manifest`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InPlace {
    pub before_dir: PathBuf,
    pub manifest: PathBuf,
}

/// Execution parameters for running an autonomous solver task to completion.
#[derive(Debug, Clone)]
pub struct TaskConfig {
    /// Goal or task prompt for the agent to resolve.
    pub prompt: String,
    /// Optional command string executed to determine task success (exit 0).
    pub gate: Option<String>,
    pub context_strategy: String,
    /// Model identifier override passed to the provider.
    pub model: Option<String>,
    /// Container identifier if execution is sandboxed inside a Docker container.
    pub container: Option<String>,
    /// Maximum allowed turn iterations before exhausting budget.
    pub max_turns: usize,
    /// Maximum verification gate retry attempts.
    pub max_gates: usize,
    /// Whether to roll back working tree on gate failure.
    pub rollback: bool,
    /// Target repository or workspace root on the local filesystem.
    pub root: PathBuf,
    /// Working directory inside the container (`--container-workdir`).
    pub container_workdir: String,
    /// Wall-clock budget in seconds (`--max-seconds`).
    pub max_seconds: Option<u64>,
    /// Maximum spend in USD (`--max-cost`).
    pub max_cost_usd: Option<f64>,
    /// Where to write the JSON run report, if anywhere (`--report`).
    pub report: Option<PathBuf>,
    /// Fold budget in approximate tokens (`--fold-budget`).
    pub fold_budget: Option<usize>,
    /// Sandbox local command execution mode (`--sandbox`).
    pub sandbox: String,
    /// Network outbound mode for commands (`--network`).
    pub network: String,
    /// Paths permitted for reading despite credential deny-list (`--allow-read`).
    pub allow_read: Vec<PathBuf>,
    /// Environment variables permitted to pass to commands despite looking like credentials (`--pass-env`).
    pub pass_env: Vec<String>,
    /// Whether this is a research run: periodically remind the model to keep report.md updated.
    pub research: bool,
    /// Research run: check report.md's claims against their cited lines.
    pub claim_check: bool,
    /// Run the verification gate once before the first model call and stop as blocked if it fails.
    pub base_check: bool,
    /// Directory containing an untouched checkout of the base commit for background base checks.
    pub base_check_dir: Option<PathBuf>,
    /// Whether this run is in converse mode (`--converse`).
    pub converse: bool,
    /// Command to run on the host when the conversation model delegates work via the `dispatch` tool (`--dispatch-cmd`).
    pub dispatch_cmd: Option<String>,
    /// Saved-originals configuration when editing the workspace folder in place.
    pub in_place: Option<InPlace>,
}

impl From<&crate::cli::Cli> for TaskConfig {
    /// Maps parsed CLI flags into a concrete `TaskConfig` configuration.
    fn from(cli: &crate::cli::Cli) -> Self {
        blyte_agent::tools::set_read_roots(cli.read_roots.clone());
        // Fall back to current working directory if not running in container mode
        let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

        let network = match &cli.network {
            Some(v) => v.clone(),
            None if cli.converse && cli.sandbox == "on" && cli.container.is_none() => "off".into(),
            None => "on".into(),
        };

        let in_place = match (&cli.snapshot_dir, &cli.snapshot_manifest) {
            (Some(before_dir), Some(manifest)) => Some(InPlace {
                before_dir: before_dir.clone(),
                manifest: manifest.clone(),
            }),
            _ => None,
        };

        Self {
            prompt: cli.prompt.clone().unwrap_or_default(),
            gate: cli.gate.clone(),
            context_strategy: cli.context.clone(),
            model: cli.model.clone(),
            container: cli.container.clone(),
            max_turns: cli.max_turns,
            max_gates: cli.max_gates,
            rollback: cli.rollback && in_place.is_none(),
            root,
            container_workdir: cli.container_workdir.clone(),
            max_seconds: cli.max_seconds,
            max_cost_usd: cli.max_cost_usd,
            report: cli.report.clone(),
            fold_budget: cli.fold_budget,
            sandbox: cli.sandbox.clone(),
            network,
            allow_read: cli.allow_read.clone(),
            pass_env: cli.pass_env.clone(),
            research: cli.research,
            claim_check: cli.claim_check,
            base_check: cli.base_check,
            base_check_dir: cli.base_check_dir.clone(),
            converse: cli.converse,
            dispatch_cmd: cli.dispatch_cmd.clone(),
            in_place,
        }
    }
}

struct TempDirGuard(Option<PathBuf>);

impl Drop for TempDirGuard {
    fn drop(&mut self) {
        if let Some(ref path) = self.0 {
            let _ = std::fs::remove_dir_all(path);
        }
    }
}

pub fn build_sandbox_profile(config: &TaskConfig) -> Result<blyte_agent::sandbox::Profile, String> {
    let (profile, tmpdir) = build_sandbox_for_root(config, &config.root)?;
    if !config.converse && config.in_place.is_none() {
        if let Some(path) = tmpdir {
            let _ = std::fs::remove_dir_all(path);
        }
    }
    Ok(profile)
}

fn build_sandbox_for_root(
    config: &TaskConfig,
    root: &Path,
) -> Result<(blyte_agent::sandbox::Profile, Option<PathBuf>), String> {
    let sandbox = if config.converse || config.in_place.is_some() {
        blyte_agent::sandbox::conversation_sandbox_net(
            root,
            &config.allow_read,
            config.network == "on",
        )?
    } else {
        blyte_agent::sandbox::default_sandbox_net(root, &config.allow_read, config.network == "on")?
    };
    Ok((sandbox.profile, sandbox.tmpdir))
}

pub struct ConversePolicy {
    pub allowed_count: usize,
    pub private_tmpdir: Option<PathBuf>,
}

pub fn configure_converse_policy_with_paths(
    converse: bool,
    sandbox_on: bool,
    root: &Path,
    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
) -> Result<ConversePolicy, String> {
    if !converse || !sandbox_on {
        blyte_agent::tools::set_write_scope(None);
        blyte_agent::tools::set_approval(None);
        return Ok(ConversePolicy {
            allowed_count: 0,
            private_tmpdir: None,
        });
    }
    let is_repo = crate::serve::is_repository(root)?;
    let paths = blyte_agent::sandbox::conversation_paths(root)?;
    let mut tmp_cleanup = TempDirGuard(if paths.created_tmpdir {
        paths.tmpdir.clone()
    } else {
        None
    });
    let (mut allowed, edit_worktrees) = if is_repo {
        let tasks_dir = blyte_agent::sandbox::conversation_tasks_dir(root);
        std::fs::create_dir_all(&tasks_dir)
            .map_err(|e| format!("cannot create {}: {e}", tasks_dir.display()))?;
        let tasks_canon = tasks_dir
            .canonicalize()
            .map_err(|e| format!("cannot canonicalize {}: {e}", tasks_dir.display()))?;
        let edit_worktrees = tasks_canon
            .parent()
            .map(|p| {
                p.canonicalize()
                    .map_err(|e| format!("cannot canonicalize {}: {e}", p.display()))
            })
            .transpose()?;
        (vec![tasks_canon], edit_worktrees)
    } else {
        (Vec::new(), None)
    };
    for dir in paths.allowed {
        match dir.canonicalize() {
            Ok(canon) => {
                if !allowed.contains(&canon) {
                    allowed.push(canon);
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => return Err(format!("cannot canonicalize {}: {e}", dir.display())),
        }
    }
    blyte_agent::tools::set_write_scope(Some(blyte_agent::tools::WriteScope {
        allowed,
        edit_worktrees,
    }));
    let rules = crate::approval_file::load()?;
    let allowed_count = rules.len();
    let approver: Arc<dyn blyte_agent::approval::Approver> =
        approver.unwrap_or_else(|| Arc::new(blyte_agent::approval::NoApprover));
    blyte_agent::tools::set_approval(Some(blyte_agent::approval::ApprovalConfig {
        rules,
        approver,
    }));
    tmp_cleanup.0 = None;
    Ok(ConversePolicy {
        allowed_count,
        private_tmpdir: paths.tmpdir,
    })
}

pub fn configure_converse_policy(
    converse: bool,
    sandbox_on: bool,
    root: &Path,
    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
) -> Result<usize, String> {
    Ok(configure_converse_policy_with_paths(converse, sandbox_on, root, approver)?.allowed_count)
}

struct BackgroundBaseCheckData {
    state: blyte_agent::run::BaseCheckState,
    elapsed_seconds: Option<f64>,
}

/// Runs the verification gate on the untouched base checkout on a background thread.
pub struct BackgroundBaseCheck {
    shared: Arc<(Mutex<BackgroundBaseCheckData>, Condvar)>,
    cancel: Arc<blyte_agent::shell::CancelHandle>,
    handle: Mutex<Option<std::thread::JoinHandle<()>>>,
}

impl BackgroundBaseCheck {
    /// Starts the gate steps in `base_dir` on a thread using the same shell, sandbox, and
    /// environment rules as the run's gate.
    pub fn start(
        config: &TaskConfig,
        gate: String,
        base_dir: PathBuf,
        deadline: Option<std::time::Instant>,
    ) -> Result<Self, String> {
        let cancel = Arc::new(blyte_agent::shell::CancelHandle::new());
        check_in_place_sandbox(config)?;
        let (shell, tmp_guard): (Box<dyn blyte_agent::shell::Shell + Send>, TempDirGuard) =
            match &config.container {
                Some(cid) => (
                    Box::new(blyte_agent::shell::CancellableContainerShell {
                        inner: blyte_agent::shell::ContainerShell {
                            container_id: cid.clone(),
                            workdir: base_dir.clone(),
                        },
                        cancel: Arc::clone(&cancel),
                    }),
                    TempDirGuard(None),
                ),
                None => {
                    let (inner, tmpdir) =
                        if config.sandbox == "on" && blyte_agent::sandbox::available() {
                            let (profile, tmpdir) = build_sandbox_for_root(config, &base_dir)?;
                            (
                                blyte_agent::shell::LocalShell::sandboxed(profile)
                                    .with_tmpdir(tmpdir.clone()),
                                tmpdir,
                            )
                        } else {
                            (blyte_agent::shell::LocalShell::new(), None)
                        };
                    (
                        Box::new(blyte_agent::shell::CancellableLocalShell {
                            inner,
                            cancel: Arc::clone(&cancel),
                        }),
                        TempDirGuard(tmpdir),
                    )
                }
            };
        let shared = Arc::new((
            Mutex::new(BackgroundBaseCheckData {
                state: blyte_agent::run::BaseCheckState::Pending,
                elapsed_seconds: None,
            }),
            Condvar::new(),
        ));
        let thread_shared = Arc::clone(&shared);
        let thread_cancel = Arc::clone(&cancel);
        let join = std::thread::spawn(move || {
            let _tmp_guard = tmp_guard;
            let started = std::time::Instant::now();
            let mut deadline = deadline;
            let result = blyte_agent::run::run_gate_steps_cancellable(
                shell.as_ref(),
                &gate,
                &base_dir,
                &[],
                &mut deadline,
                |_| {},
                &std::time::Instant::now,
                Some(&thread_cancel),
            );
            if thread_cancel.is_cancelled() {
                return;
            }
            let elapsed = started.elapsed().as_secs_f64();
            let next_state = blyte_agent::run::base_check_state_from_gate(&result);
            let (lock, cvar) = &*thread_shared;
            let mut guard = match lock.lock() {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
            guard.state = next_state;
            guard.elapsed_seconds = Some(elapsed);
            cvar.notify_all();
        });
        Ok(Self {
            shared,
            cancel,
            handle: Mutex::new(Some(join)),
        })
    }
}

impl blyte_agent::run::BaseCheckHandle for BackgroundBaseCheck {
    fn poll(&self) -> blyte_agent::run::BaseCheckState {
        let (lock, _) = &*self.shared;
        match lock.lock() {
            Ok(g) => g.state.clone(),
            Err(e) => e.into_inner().state.clone(),
        }
    }

    fn wait(&self) -> blyte_agent::run::BaseCheckState {
        let (lock, cvar) = &*self.shared;
        let mut guard = match lock.lock() {
            Ok(g) => g,
            Err(e) => e.into_inner(),
        };
        while matches!(guard.state, blyte_agent::run::BaseCheckState::Pending) {
            if self.cancel.is_cancelled() {
                break;
            }
            guard = match cvar.wait(guard) {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
        }
        guard.state.clone()
    }

    fn stop(&self) {
        self.cancel.cancel();
        let (lock, cvar) = &*self.shared;
        let guard = match lock.lock() {
            Ok(g) => g,
            Err(e) => e.into_inner(),
        };
        cvar.notify_all();
        drop(guard);
        let join = match self.handle.lock() {
            Ok(mut g) => g.take(),
            Err(e) => e.into_inner().take(),
        };
        if let Some(h) = join {
            let _ = h.join();
        }
    }

    fn elapsed_seconds(&self) -> Option<f64> {
        let (lock, _) = &*self.shared;
        match lock.lock() {
            Ok(g) => g.elapsed_seconds,
            Err(e) => e.into_inner().elapsed_seconds,
        }
    }
}

impl Drop for BackgroundBaseCheck {
    fn drop(&mut self) {
        blyte_agent::run::BaseCheckHandle::stop(self);
    }
}

pub fn check_in_place_sandbox(config: &TaskConfig) -> Result<(), String> {
    if config.in_place.is_some() {
        if config.container.is_some() {
            return Err(
                "in-place runs need the sandbox: --container cannot be used with in-place runs"
                    .into(),
            );
        }
        if config.sandbox != "on" {
            return Err(format!(
                "in-place runs need the sandbox: --sandbox is '{}'",
                config.sandbox
            ));
        }
        if !blyte_agent::sandbox::available() {
            return Err("in-place runs need the sandbox: sandbox is unavailable".into());
        }
    }
    Ok(())
}

pub fn build_local_shell(
    config: &TaskConfig,
) -> Result<blyte_agent::shell::PersistentShell, String> {
    Ok(build_local_shell_with_tmpdir(config)?.0)
}

fn build_local_shell_with_tmpdir(
    config: &TaskConfig,
) -> Result<(blyte_agent::shell::PersistentShell, Option<PathBuf>), String> {
    check_in_place_sandbox(config)?;
    if config.sandbox == "on" {
        if blyte_agent::sandbox::available() {
            let (profile, tmpdir) = build_sandbox_for_root(config, &config.root)?;
            if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
                eprintln!(
                    "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
                );
            }
            if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
                eprintln!(
                    "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
                );
            }
            if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } = &profile {
                eprintln!(
                    "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
                );
                if *block_tcp {
                    eprintln!(
                        "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
                    );
                }
            }
            let shell =
                blyte_agent::shell::PersistentShell::local_sandboxed(config.root.clone(), profile)
                    .with_tmpdir(tmpdir.clone());
            if config.converse {
                let root = config.root.clone();
                let allow_read = config.allow_read.clone();
                let network = config.network == "on";
                Ok((
                    shell.with_profile_builder(Arc::new(move || {
                        blyte_agent::sandbox::conversation_profile_for_open_edits(
                            &root,
                            &allow_read,
                            network,
                        )
                    })),
                    tmpdir,
                ))
            } else {
                Ok((shell, tmpdir))
            }
        } else {
            eprintln!("warning: sandbox unavailable; running unsandboxed");
            Ok((
                blyte_agent::shell::PersistentShell::local(config.root.clone()),
                None,
            ))
        }
    } else {
        Ok((
            blyte_agent::shell::PersistentShell::local(config.root.clone()),
            None,
        ))
    }
}

/// Validates network configuration against the environment and active flags.
///
/// Refuses `--network=off` when running with `--container`, when `--sandbox=off`,
/// when the sandbox is unavailable, or on Linux when `landlock_abi() < 4`.
pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
    if config.network == "off" {
        if config.container.is_some() {
            return Err(
                "--network=off is not supported with --container; set the container's network instead"
                    .into(),
            );
        }
        if config.sandbox != "on" {
            return Err("--network=off needs the sandbox".into());
        }
        #[cfg(target_os = "linux")]
        if blyte_agent::sandbox::landlock_abi() < 4 {
            return Err("--network=off on Linux needs Linux 6.7 or later".into());
        }
        if !blyte_agent::sandbox::available() {
            return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
        }
    }
    Ok(())
}

pub fn write_watchdog_report<F, W: Write>(
    config: &TaskConfig,
    progress: &Progress,
    msg: &str,
    elapsed: std::time::Duration,
    resolve_model: F,
    err_out: &mut W,
) -> Result<Option<crate::report::RunRecord>, String>
where
    F: FnOnce(Option<&str>) -> Result<String, String>,
{
    let Some(path) = &config.report else {
        return Ok(None);
    };
    let mut record = crate::report::RunRecord::from_error(config, msg, elapsed);
    record.turns = progress.turns;
    record.gate_attempts = progress.gate_attempts;
    record.usage = crate::report::UsageRecord {
        input: progress.usage.input,
        cached: progress.usage.cached,
        output: progress.usage.output,
        thinking: progress.usage.thinking,
    };
    let model_id = match resolve_model(config.model.as_deref()) {
        Ok(id) if !id.is_empty() => Some(id),
        Ok(_) => {
            let _ = writeln!(
                err_out,
                "blyte: watchdog warning: provider returned empty model id"
            );
            config.model.clone().filter(|m| !m.is_empty())
        }
        Err(err) => {
            let _ = writeln!(
                err_out,
                "blyte: watchdog warning: could not resolve provider for cost lookup: {err}"
            );
            config.model.clone().filter(|m| !m.is_empty())
        }
    };
    if let Some(id) = model_id {
        record.cost_usd = blyte_provider::pricing(&id).map(|pr| pr.cost(&progress.usage));
        record.model_id = Some(id);
    }
    crate::report::write(path, &record)?;
    Ok(Some(record))
}

/// Executes an autonomous solver run using the provided task configuration and live stdout.
///
/// Configures the AI provider, context strategy, execution environment (local or container),
/// and deterministic gate loop, printing live event progress as turns execute.
///
/// # Arguments
///
/// * `config` - Parameters governing prompt, budgets, gate verification, and environment.
///
/// # Returns
///
/// Returns `Ok((Outcome, RunReport))` containing final completion status and metrics,
/// or an `Err(String)` describing initialization failure.
pub fn run_task(
    config: TaskConfig,
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    let started = std::time::Instant::now();
    let progress = Arc::new(Mutex::new(Progress::default()));
    if let Some(s) = config.max_seconds {
        // BLYTE_WATCHDOG_GRACE_SECS exists for tests.
        let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
            .ok()
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(30);
        let watchdog_config = config.clone();
        let watchdog_progress = Arc::clone(&progress);
        std::thread::spawn(move || {
            loop {
                let wait_ms = match watchdog_progress.lock() {
                    Ok(g) => g.gate_wait_ms,
                    Err(e) => e.into_inner().gate_wait_ms,
                };
                let deadline = started
                    + std::time::Duration::from_secs(s.saturating_add(grace_secs))
                    + std::time::Duration::from_millis(wait_ms);
                match deadline.checked_duration_since(std::time::Instant::now()) {
                    Some(remaining) if !remaining.is_zero() => {
                        std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
                    }
                    _ => break,
                }
            }
            let p = match watchdog_progress.lock() {
                Ok(g) => *g,
                Err(e) => *e.into_inner(),
            };
            let msg = if p.in_gate {
                format!(
                    "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
                    p.gate_attempts
                )
            } else {
                format!(
                    "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
                    p.turns
                )
            };
            let mut stderr = std::io::stderr();
            if let Err(err) = write_watchdog_report(
                &watchdog_config,
                &p,
                &msg,
                started.elapsed(),
                |m| {
                    blyte_provider::resolve_provider(m)
                        .map(|pr| pr.model_id())
                        .map_err(|e| e.to_string())
                },
                &mut stderr,
            ) {
                eprintln!("blyte: watchdog failed to write report: {err}");
            }
            eprintln!("blyte: {msg}");
            std::process::exit(1);
        });
    }
    let verification_cmd = config.gate.as_deref().unwrap_or("");
    let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
    state.brief.max_cost_usd = config.max_cost_usd;
    let mut stdout = std::io::stdout();
    let result =
        run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
    // The loop writes its own report; this covers a run that never reached it (e.g. no API
    // key), so a caller always finds one. An absent report would read as a crash.
    if let (Err(e), Some(path)) = (&result, &config.report) {
        crate::report::write(
            path,
            &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
        )?;
    }
    result
}

/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`.
///
/// Preserves session mutations (epistemic ledger, patches, attempts) directly in the provided `state`.
///
/// # Arguments
///
/// * `config` - Execution parameters.
/// * `state` - The mutable session state to advance.
/// * `writer` - Stream writer sink for formatted events.
///
/// # Returns
///
/// Returns `Ok((Outcome, RunReport))` or an `Err(String)` describing failure.
pub fn run_task_with_state_and_writer<W: Write>(
    config: &TaskConfig,
    state: &mut blyte_agent::state::State,
    writer: &mut W,
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    let progress = Arc::new(Mutex::new(Progress::default()));
    run_task_with_state_writer_and_progress(config, state, writer, progress)
}

/// Executes an autonomous solver run against an existing mutable `State`, passing every raw event
/// directly to `on_event` without formatting lines to a writer.
pub fn run_task_with_state_and_events(
    config: &TaskConfig,
    state: &mut blyte_agent::state::State,
    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
}

pub fn run_task_with_state_and_max_duration(
    config: &TaskConfig,
    state: &mut blyte_agent::state::State,
    max_duration: Option<std::time::Duration>,
    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
}

/// Executes an autonomous solver run with an explicit approver override (used by the surface).
pub fn run_task_with_approver(
    config: &TaskConfig,
    state: &mut blyte_agent::state::State,
    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
    run_task_with_event_callback(config, state, approver, max_duration, &|event| {
        on_event(event)
    })
}

/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
/// and updating the shared `progress` record.
pub fn run_task_with_state_writer_and_progress<W: Write>(
    config: &TaskConfig,
    state: &mut blyte_agent::state::State,
    writer: &mut W,
    progress: Arc<Mutex<Progress>>,
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    let writer_mutex = Mutex::new(writer);
    let on_event = |event: &blyte_agent::run::Event<'_>| {
        {
            let mut p = match progress.lock() {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
            match event {
                blyte_agent::run::Event::Turn { n, usage, .. } => {
                    p.turns = *n;
                    p.usage.input += usage.input;
                    p.usage.cached += usage.cached;
                    p.usage.output += usage.output;
                    p.usage.thinking += usage.thinking;
                    p.in_gate = false;
                }
                blyte_agent::run::Event::GateStart { attempt } => {
                    p.gate_attempts = *attempt;
                    p.in_gate = true;
                }
                blyte_agent::run::Event::GateSlotWait { ms } => {
                    p.gate_wait_ms += ms;
                }
                blyte_agent::run::Event::Gate { .. } => {
                    p.in_gate = false;
                }
                _ => {}
            }
        }
        let line = crate::repl::format_event(event);
        if !line.is_empty() {
            if let Ok(mut w) = writer_mutex.lock() {
                let _ = writeln!(w, "{line}");
            }
        }
    };
    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
    run_task_with_event_callback(config, state, None, max_duration, &on_event)
}

fn build_usage_entry(
    config: &TaskConfig,
    model_id: &str,
    outcome: String,
    turns: u32,
    usage: &blyte_provider::Usage,
) -> crate::usage_log::Entry {
    let (surface, surface_name) = crate::usage_log::surface_from(
        std::env::var(crate::usage_log::SURFACE_ID_ENV).ok(),
        std::env::var(crate::usage_log::SURFACE_NAME_ENV).ok(),
    );
    crate::usage_log::Entry {
        ts: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        repo: crate::usage_log::repo_of(&config.root),
        session: crate::usage_log::session_from(
            std::env::var("BLYTE_SESSION").ok(),
            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
        ),
        surface,
        surface_name,
        dispatch: std::env::var("BLYTE_DISPATCH_ID")
            .ok()
            .filter(|s| !s.is_empty()),
        research: config.research,
        model: model_id.to_string(),
        outcome,
        turns,
        input: usage.input,
        cached: usage.cached,
        output: usage.output,
        thinking: usage.thinking,
        cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
    }
}

#[derive(Debug, PartialEq, Eq)]
struct ExceededField {
    field: &'static str,
    written: u64,
    total: u64,
}

fn usage_remainder(
    total_turns: u32,
    total_usage: &blyte_provider::Usage,
    written_turns: u32,
    written_usage: &blyte_provider::Usage,
) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
    let mut exceeded = Vec::new();
    if written_turns > total_turns {
        exceeded.push(ExceededField {
            field: "turns",
            written: u64::from(written_turns),
            total: u64::from(total_turns),
        });
    }
    if written_usage.input > total_usage.input {
        exceeded.push(ExceededField {
            field: "input",
            written: written_usage.input,
            total: total_usage.input,
        });
    }
    if written_usage.cached > total_usage.cached {
        exceeded.push(ExceededField {
            field: "cached",
            written: written_usage.cached,
            total: total_usage.cached,
        });
    }
    if written_usage.output > total_usage.output {
        exceeded.push(ExceededField {
            field: "output",
            written: written_usage.output,
            total: total_usage.output,
        });
    }
    if written_usage.thinking > total_usage.thinking {
        exceeded.push(ExceededField {
            field: "thinking",
            written: written_usage.thinking,
            total: total_usage.thinking,
        });
    }
    if !exceeded.is_empty() {
        return Err(exceeded);
    }
    Ok((
        total_turns - written_turns,
        blyte_provider::Usage {
            input: total_usage.input - written_usage.input,
            cached: total_usage.cached - written_usage.cached,
            output: total_usage.output - written_usage.output,
            thinking: total_usage.thinking - written_usage.thinking,
        },
    ))
}

/// Whether to print the list of withheld environment variables: once for each distinct list in
/// this process. A surface runs many turns in one process, and the list is the same for each.
fn withheld_notice_is_due(withheld: &[String]) -> bool {
    static SHOWN: std::sync::Mutex<Option<Vec<String>>> = std::sync::Mutex::new(None);
    if withheld.is_empty() {
        return false;
    }
    let mut shown = SHOWN.lock().unwrap_or_else(|e| e.into_inner());
    if shown.as_deref() == Some(withheld) {
        return false;
    }
    *shown = Some(withheld.to_vec());
    true
}

fn run_task_with_event_callback(
    config: &TaskConfig,
    state: &mut blyte_agent::state::State,
    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
    max_duration: Option<std::time::Duration>,
    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
    check_network_mode(config)?;
    check_in_place_sandbox(config)?;
    let started = std::time::Instant::now();
    let (conversation_owned_tmpdir, _one_shot_tmp_guard) = if config.converse {
        if std::env::var("BLYTE_SESSION")
            .map(|v| v.is_empty())
            .unwrap_or(true)
        {
            let now_secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let id = crate::repl::new_session_id(now_secs, std::process::id());
            std::env::set_var("BLYTE_SESSION", &id);
        }
        let sandbox_on = config.sandbox == "on";
        let policy =
            configure_converse_policy_with_paths(true, sandbox_on, &config.root, approver)?;
        let (owned_tmpdir, guard) = if state.runtime.conversation.is_none() {
            (None, policy.private_tmpdir.map(|p| TempDirGuard(Some(p))))
        } else {
            (policy.private_tmpdir, None)
        };
        if state.brief.instructions.is_none() {
            let lines = crate::conversation_text::set_state_instructions(
                state,
                config.dispatch_cmd.is_some(),
                &config.root,
                sandbox_on,
                policy.allowed_count,
            )?;
            if state.runtime.conversation.is_none() {
                for line in &lines {
                    eprintln!("blyte: {line}");
                }
            }
        }
        let exe = std::env::current_exe()
            .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
        blyte_agent::tools::set_blyte_tool(Some(exe));
        if blyte_agent::sandbox::is_git_repository(&config.root) {
            blyte_agent::tools::set_blyte_tasks_dir(None);
            blyte_agent::tools::set_blyte_run_store(None);
            blyte_agent::tools::set_in_place_lock_path(None);
        } else {
            let state_dir = crate::surface_registry::state_dir()?;
            let tasks_dir = crate::surface_dir::tasks_dir(&state_dir, &config.root)?;
            let run_store = crate::surface_dir::run_store(&state_dir, &config.root)?;
            let lock_path = crate::surface_dir::in_place_lock_path(&state_dir, &config.root)?;
            blyte_agent::tools::set_blyte_tasks_dir(Some(tasks_dir));
            blyte_agent::tools::set_blyte_run_store(Some(run_store));
            blyte_agent::tools::set_in_place_lock_path(Some(lock_path));
        }
        (owned_tmpdir, guard)
    } else {
        configure_converse_policy(false, false, &config.root, None)?;
        blyte_agent::tools::set_blyte_tool(None);
        blyte_agent::tools::set_blyte_tasks_dir(None);
        blyte_agent::tools::set_blyte_run_store(None);
        blyte_agent::tools::set_in_place_lock_path(None);
        (None, None)
    };
    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
    // 1. Initialize LLM provider from environment credentials or model specification.
    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
        Ok(p) => p,
        Err(blyte_provider::ProviderError::MissingKey(key)) => {
            return Err(format!(
                "Provider error: no API key: set {key} in environment"
            ));
        }
        Err(e) => return Err(format!("Provider error: {e}")),
    };

    let model_id = provider.model_id();
    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
        return Err(format!(
            "--max-cost needs a known price for {model_id}; none is known"
        ));
    }
    state.brief.max_cost_usd = config.max_cost_usd;

    // 2. Select context assembly strategy.
    let folded = blyte_agent::context::Folded {
        // Research quotes code read many turns earlier, so it keeps more before folding.
        budget_tokens: config.fold_budget.unwrap_or(if config.research {
            RESEARCH_FOLD_BUDGET
        } else {
            blyte_agent::context::Folded::default().budget_tokens
        }),
    };
    let conversational = blyte_agent::context::Conversational;
    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
        match config.context_strategy.as_str() {
            "conversational" => &conversational,
            _ => &folded,
        };

    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
    // and `export` carry over). Container files go through a session too. Each falls back to a
    // process per command if a session cannot start.
    let local_fs = blyte_agent::fs::LocalFs;
    let snapshot_fs = match &config.in_place {
        Some(in_place) => Some(blyte_agent::snapshot_fs::SnapshotFs::new(
            blyte_agent::fs::LocalFs,
            config.root.clone(),
            in_place.before_dir.clone(),
            in_place.manifest.clone(),
        )?),
        None => None,
    };
    let mut _private_tmp_guard = TempDirGuard(None);
    let (persistent, session_fs, root) = match &config.container {
        Some(cid) => (
            blyte_agent::shell::PersistentShell::container(
                cid.clone(),
                PathBuf::from(&config.container_workdir),
            ),
            Some(blyte_agent::fs::SessionFs::container(
                cid.clone(),
                PathBuf::from(&config.container_workdir),
            )),
            PathBuf::from(&config.container_workdir),
        ),
        None => {
            blyte_agent::shell::set_pass_env(config.pass_env.clone());
            if !config.converse {
                if let Some(r) = blyte_agent::rules::load(&config.root) {
                    eprintln!("blyte: repository rules from {}", r.source.display());
                }
            }
            let withheld = blyte_agent::shell::withheld_env();
            if withheld_notice_is_due(&withheld) {
                eprintln!(
                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
                    withheld.join(", ")
                );
            }
            let (shell, tmpdir) = build_local_shell_with_tmpdir(config)?;
            if tmpdir.is_some() && tmpdir != conversation_owned_tmpdir {
                _private_tmp_guard.0 = tmpdir;
            }
            (shell, None, config.root.clone())
        }
    };
    let shell: &dyn blyte_agent::shell::Shell = &persistent;
    let fs: &dyn blyte_agent::fs::Fs = match (&session_fs, &snapshot_fs) {
        (Some(f), _) => f,
        (None, Some(f)) => f,
        (None, None) => &local_fs,
    };

    let usage_path = crate::usage_log::default_path();
    let written = Mutex::new((0u32, blyte_provider::Usage::default()));
    let runner_on_event = |event: blyte_agent::run::Event<'_>| {
        if let blyte_agent::run::Event::Turn { usage, .. } = &event {
            if let Some(path) = &usage_path {
                let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
                match crate::usage_log::append(path, &entry) {
                    Ok(()) => {
                        let mut w = match written.lock() {
                            Ok(g) => g,
                            Err(e) => e.into_inner(),
                        };
                        w.0 += 1;
                        w.1.input += usage.input;
                        w.1.cached += usage.cached;
                        w.1.output += usage.output;
                        w.1.thinking += usage.thinking;
                    }
                    Err(err) => eprintln!("warning: usage log: {err}"),
                }
            }
        }
        on_event(&event);
    };

    let bg_base_check = match &config.base_check_dir {
        Some(base_dir)
            if !blyte_agent::run::gate_steps(&state.brief.verification_cmd).is_empty() =>
        {
            let deadline = max_duration.map(|d| std::time::Instant::now() + d);
            Some(BackgroundBaseCheck::start(
                config,
                state.brief.verification_cmd.clone(),
                base_dir.clone(),
                deadline,
            )?)
        }
        _ => None,
    };
    let base_check = if let Some(ref bg) = bg_base_check {
        blyte_agent::run::BaseCheck::Polled(bg)
    } else if config.base_check {
        blyte_agent::run::BaseCheck::BeforeFirstTurn
    } else {
        blyte_agent::run::BaseCheck::None
    };

    let runner = blyte_agent::run::Runner {
        provider: provider.as_ref(),
        shell,
        fs,
        context: context_strategy,
        root,
        budget: blyte_agent::run::Budget {
            max_turns: config.max_turns as u32,
            max_gate_attempts: config.max_gates as u32,
            max_duration,
        },
        rollback: config.rollback && config.in_place.is_none(),
        on_event: Some(&runner_on_event),
        research: config.research,
        claim_check: config.claim_check,
        base_check,
    };

    let (mut outcome, report) = runner.run(state);
    if config.in_place.is_some()
        && state.brief.verification_cmd.trim().is_empty()
        && matches!(outcome, blyte_agent::run::Outcome::Verified)
    {
        outcome = blyte_agent::run::Outcome::Finished;
    }
    drop(bg_base_check);

    if let Some(path) = &usage_path {
        let (written_turns, written_usage) = match written.lock() {
            Ok(g) => *g,
            Err(e) => *e.into_inner(),
        };
        let (closing_turns, closing_usage) = match usage_remainder(
            report.outcome_turns,
            &report.usage,
            written_turns,
            &written_usage,
        ) {
            Ok(rem) => rem,
            Err(exceeded) => {
                for ExceededField {
                    field,
                    written,
                    total,
                } in exceeded
                {
                    eprintln!(
                        "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
                    );
                }
                (0, blyte_provider::Usage::default())
            }
        };
        let entry = build_usage_entry(
            config,
            &model_id,
            format!("{outcome:?}").to_lowercase(),
            closing_turns,
            &closing_usage,
        );
        if let Err(err) = crate::usage_log::append(path, &entry) {
            eprintln!("warning: usage log: {err}");
        }
    }

    if let Some(path) = &config.report {
        let mut record = crate::report::RunRecord::from_run(
            config,
            &model_id,
            &outcome,
            &report,
            state,
            started.elapsed(),
        );
        record.effort = provider.effort();
        crate::report::write(path, &record)?;
    }
    Ok((outcome, report))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn usage_remainder_computes_exact_and_partial_remainders() {
        let total = blyte_provider::Usage {
            input: 600,
            cached: 150,
            output: 90,
            thinking: 75,
        };
        let exact = usage_remainder(3, &total, 3, &total).unwrap();
        assert_eq!(exact, (0, blyte_provider::Usage::default()));

        let written = blyte_provider::Usage {
            input: 500,
            cached: 100,
            output: 80,
            thinking: 50,
        };
        let partial = usage_remainder(3, &total, 2, &written).unwrap();
        assert_eq!(
            partial,
            (
                1,
                blyte_provider::Usage {
                    input: 100,
                    cached: 50,
                    output: 10,
                    thinking: 25,
                }
            )
        );
    }

    #[test]
    fn usage_remainder_reports_exceeding_fields() {
        let total = blyte_provider::Usage {
            input: 100,
            cached: 20,
            output: 30,
            thinking: 10,
        };
        let written = blyte_provider::Usage {
            input: 120,
            cached: 20,
            output: 35,
            thinking: 10,
        };
        let err = usage_remainder(2, &total, 3, &written).unwrap_err();
        assert_eq!(
            err,
            vec![
                ExceededField {
                    field: "turns",
                    written: 3,
                    total: 2,
                },
                ExceededField {
                    field: "input",
                    written: 120,
                    total: 100,
                },
                ExceededField {
                    field: "output",
                    written: 35,
                    total: 30,
                },
            ]
        );
    }

    fn test_task_config(root: &Path, report: Option<PathBuf>, model: Option<String>) -> TaskConfig {
        TaskConfig {
            prompt: "test".to_string(),
            gate: Some("true".to_string()),
            context_strategy: "folded".to_string(),
            model,
            container: None,
            max_turns: 10,
            max_gates: 3,
            rollback: false,
            root: root.to_path_buf(),
            container_workdir: "/workspace".to_string(),
            max_seconds: Some(10),
            max_cost_usd: None,
            report,
            fold_budget: None,
            sandbox: "off".to_string(),
            network: "on".to_string(),
            allow_read: Vec::new(),
            pass_env: Vec::new(),
            research: false,
            claim_check: false,
            base_check: false,
            base_check_dir: None,
            converse: false,
            dispatch_cmd: None,
            in_place: None,
        }
    }

    #[test]
    fn watchdog_report_write_failure_names_path_and_model_id_is_never_empty() {
        let dir = tempfile::tempdir().unwrap();
        let report_dir = dir.path().join("unwritable.report.json");
        std::fs::create_dir_all(&report_dir).unwrap();

        let cfg = test_task_config(dir.path(), Some(report_dir.clone()), None);
        let progress = Progress {
            turns: 2,
            gate_attempts: 1,
            in_gate: false,
            gate_wait_ms: 0,
            usage: blyte_provider::Usage {
                input: 1000,
                cached: 0,
                output: 500,
                thinking: 0,
            },
        };
        let mut err_buf = Vec::new();
        let err = write_watchdog_report(
            &cfg,
            &progress,
            "stopped past --max-seconds",
            std::time::Duration::from_secs(5),
            |_| Err("missing API key".to_string()),
            &mut err_buf,
        )
        .expect_err("writing watchdog report to a directory must fail");

        assert!(
            err.contains(&report_dir.display().to_string()),
            "write error must name report path, got: {err}"
        );
        let warning = String::from_utf8(err_buf).unwrap();
        assert!(
            warning.contains("missing API key"),
            "provider resolution error must be logged, got: {warning}"
        );

        let ok_report = dir.path().join("ok.report.json");
        let ok_cfg = test_task_config(dir.path(), Some(ok_report.clone()), None);
        let mut ok_err = Vec::new();
        let rec = write_watchdog_report(
            &ok_cfg,
            &progress,
            "stopped past --max-seconds",
            std::time::Duration::from_secs(5),
            |_| Ok("gemini-3.8-flash-high".to_string()),
            &mut ok_err,
        )
        .expect("writing watchdog report to file must succeed")
        .expect("record must be returned");

        assert_eq!(rec.model_id.as_deref(), Some("gemini-3.8-flash-high"));
        assert!(rec.cost_usd.is_some());

        let fallback_report = dir.path().join("fallback.report.json");
        let fallback_cfg = test_task_config(dir.path(), Some(fallback_report), None);
        let mut fallback_err = Vec::new();
        let fallback_rec = write_watchdog_report(
            &fallback_cfg,
            &progress,
            "stopped past --max-seconds",
            std::time::Duration::from_secs(5),
            |_| Err("no provider".to_string()),
            &mut fallback_err,
        )
        .expect("writing watchdog report must succeed")
        .expect("record must be returned");

        assert_ne!(fallback_rec.model_id.as_deref(), Some(""));
        assert_eq!(fallback_rec.model_id, None);
        assert!(String::from_utf8(fallback_err)
            .unwrap()
            .contains("no provider"));
    }

    #[test]
    fn build_usage_entry_records_surface_env() {
        let _guard = crate::usage_log::ENV_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let prev_id = std::env::var_os(crate::usage_log::SURFACE_ID_ENV);
        let prev_name = std::env::var_os(crate::usage_log::SURFACE_NAME_ENV);

        let dir = tempfile::tempdir().unwrap();
        let cfg = test_task_config(dir.path(), None, None);
        let usage = blyte_provider::Usage::default();

        std::env::set_var(crate::usage_log::SURFACE_ID_ENV, "s1");
        std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, "alpha");
        let with_surface = build_usage_entry(&cfg, "m", "verified".into(), 1, &usage);

        std::env::remove_var(crate::usage_log::SURFACE_ID_ENV);
        std::env::remove_var(crate::usage_log::SURFACE_NAME_ENV);
        let without_surface = build_usage_entry(&cfg, "m", "verified".into(), 1, &usage);

        match prev_id {
            Some(v) => std::env::set_var(crate::usage_log::SURFACE_ID_ENV, v),
            None => std::env::remove_var(crate::usage_log::SURFACE_ID_ENV),
        }
        match prev_name {
            Some(v) => std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, v),
            None => std::env::remove_var(crate::usage_log::SURFACE_NAME_ENV),
        }

        assert_eq!(with_surface.surface.as_deref(), Some("s1"));
        assert_eq!(with_surface.surface_name.as_deref(), Some("alpha"));
        assert_eq!(without_surface.surface, None);
        assert_eq!(without_surface.surface_name, None);
    }
}