Skip to main content

blyte_cli/
task_runner.rs

1//! Headless single-shot solver runner for executing direct agent prompts.
2//!
3//! Wires together the configured LLM provider, execution shell (local host or container sandbox),
4//! filesystem abstraction, context strategy, and verification gate runner into an autonomous loop.
5
6use std::io::Write;
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Condvar, Mutex};
9
10/// Fold budget for research runs, which quote code read many turns before they write it up.
11/// High enough that folding is only a safety net: unfolded research runs were cheaper, shorter and
12/// invented fewer names than runs folded at 96k (`docs/specs/2026-10-19-claim-check.md`, FX).
13pub const RESEARCH_FOLD_BUDGET: usize = 180_000;
14
15/// Tracks turn and gate progress across the run, for the deadline watchdog.
16#[derive(Debug, Default, Clone, Copy)]
17pub struct Progress {
18    pub turns: u32,
19    pub gate_attempts: u32,
20    pub in_gate: bool,
21    pub gate_wait_ms: u64,
22    pub usage: blyte_provider::Usage,
23}
24
25/// Saved-originals configuration for an in-place run (`--snapshot-dir`, `--snapshot-manifest`).
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct InPlace {
28    pub before_dir: PathBuf,
29    pub manifest: PathBuf,
30}
31
32/// Execution parameters for running an autonomous solver task to completion.
33#[derive(Debug, Clone)]
34pub struct TaskConfig {
35    /// Goal or task prompt for the agent to resolve.
36    pub prompt: String,
37    /// Optional command string executed to determine task success (exit 0).
38    pub gate: Option<String>,
39    pub context_strategy: String,
40    /// Model identifier override passed to the provider.
41    pub model: Option<String>,
42    /// Container identifier if execution is sandboxed inside a Docker container.
43    pub container: Option<String>,
44    /// Maximum allowed turn iterations before exhausting budget.
45    pub max_turns: usize,
46    /// Maximum verification gate retry attempts.
47    pub max_gates: usize,
48    /// Whether to roll back working tree on gate failure.
49    pub rollback: bool,
50    /// Target repository or workspace root on the local filesystem.
51    pub root: PathBuf,
52    /// Working directory inside the container (`--container-workdir`).
53    pub container_workdir: String,
54    /// Wall-clock budget in seconds (`--max-seconds`).
55    pub max_seconds: Option<u64>,
56    /// Maximum spend in USD (`--max-cost`).
57    pub max_cost_usd: Option<f64>,
58    /// Where to write the JSON run report, if anywhere (`--report`).
59    pub report: Option<PathBuf>,
60    /// Fold budget in approximate tokens (`--fold-budget`).
61    pub fold_budget: Option<usize>,
62    /// Sandbox local command execution mode (`--sandbox`).
63    pub sandbox: String,
64    /// Network outbound mode for commands (`--network`).
65    pub network: String,
66    /// Paths permitted for reading despite credential deny-list (`--allow-read`).
67    pub allow_read: Vec<PathBuf>,
68    /// Environment variables permitted to pass to commands despite looking like credentials (`--pass-env`).
69    pub pass_env: Vec<String>,
70    /// Whether this is a research run: periodically remind the model to keep report.md updated.
71    pub research: bool,
72    /// Research run: check report.md's claims against their cited lines.
73    pub claim_check: bool,
74    /// Run the verification gate once before the first model call and stop as blocked if it fails.
75    pub base_check: bool,
76    /// Directory containing an untouched checkout of the base commit for background base checks.
77    pub base_check_dir: Option<PathBuf>,
78    /// Whether this run is in converse mode (`--converse`).
79    pub converse: bool,
80    /// Command to run on the host when the conversation model delegates work via the `dispatch` tool (`--dispatch-cmd`).
81    pub dispatch_cmd: Option<String>,
82    /// Saved-originals configuration when editing the workspace folder in place.
83    pub in_place: Option<InPlace>,
84}
85
86impl From<&crate::cli::Cli> for TaskConfig {
87    /// Maps parsed CLI flags into a concrete `TaskConfig` configuration.
88    fn from(cli: &crate::cli::Cli) -> Self {
89        blyte_agent::tools::set_read_roots(cli.read_roots.clone());
90        // Fall back to current working directory if not running in container mode
91        let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
92
93        let network = match &cli.network {
94            Some(v) => v.clone(),
95            None if cli.converse && cli.sandbox == "on" && cli.container.is_none() => "off".into(),
96            None => "on".into(),
97        };
98
99        let in_place = match (&cli.snapshot_dir, &cli.snapshot_manifest) {
100            (Some(before_dir), Some(manifest)) => Some(InPlace {
101                before_dir: before_dir.clone(),
102                manifest: manifest.clone(),
103            }),
104            _ => None,
105        };
106
107        Self {
108            prompt: cli.prompt.clone().unwrap_or_default(),
109            gate: cli.gate.clone(),
110            context_strategy: cli.context.clone(),
111            model: cli.model.clone(),
112            container: cli.container.clone(),
113            max_turns: cli.max_turns,
114            max_gates: cli.max_gates,
115            rollback: cli.rollback && in_place.is_none(),
116            root,
117            container_workdir: cli.container_workdir.clone(),
118            max_seconds: cli.max_seconds,
119            max_cost_usd: cli.max_cost_usd,
120            report: cli.report.clone(),
121            fold_budget: cli.fold_budget,
122            sandbox: cli.sandbox.clone(),
123            network,
124            allow_read: cli.allow_read.clone(),
125            pass_env: cli.pass_env.clone(),
126            research: cli.research,
127            claim_check: cli.claim_check,
128            base_check: cli.base_check,
129            base_check_dir: cli.base_check_dir.clone(),
130            converse: cli.converse,
131            dispatch_cmd: cli.dispatch_cmd.clone(),
132            in_place,
133        }
134    }
135}
136
137struct TempDirGuard(Option<PathBuf>);
138
139impl Drop for TempDirGuard {
140    fn drop(&mut self) {
141        if let Some(ref path) = self.0 {
142            let _ = std::fs::remove_dir_all(path);
143        }
144    }
145}
146
147pub fn build_sandbox_profile(config: &TaskConfig) -> Result<blyte_agent::sandbox::Profile, String> {
148    let (profile, tmpdir) = build_sandbox_for_root(config, &config.root)?;
149    if !config.converse && config.in_place.is_none() {
150        if let Some(path) = tmpdir {
151            let _ = std::fs::remove_dir_all(path);
152        }
153    }
154    Ok(profile)
155}
156
157fn build_sandbox_for_root(
158    config: &TaskConfig,
159    root: &Path,
160) -> Result<(blyte_agent::sandbox::Profile, Option<PathBuf>), String> {
161    let sandbox = if config.converse || config.in_place.is_some() {
162        blyte_agent::sandbox::conversation_sandbox_net(
163            root,
164            &config.allow_read,
165            config.network == "on",
166        )?
167    } else {
168        blyte_agent::sandbox::default_sandbox_net(root, &config.allow_read, config.network == "on")?
169    };
170    Ok((sandbox.profile, sandbox.tmpdir))
171}
172
173pub struct ConversePolicy {
174    pub allowed_count: usize,
175    pub private_tmpdir: Option<PathBuf>,
176}
177
178pub fn configure_converse_policy_with_paths(
179    converse: bool,
180    sandbox_on: bool,
181    root: &Path,
182    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
183) -> Result<ConversePolicy, String> {
184    if !converse || !sandbox_on {
185        blyte_agent::tools::set_write_scope(None);
186        blyte_agent::tools::set_approval(None);
187        return Ok(ConversePolicy {
188            allowed_count: 0,
189            private_tmpdir: None,
190        });
191    }
192    let is_repo = crate::serve::is_repository(root)?;
193    let paths = blyte_agent::sandbox::conversation_paths(root)?;
194    let mut tmp_cleanup = TempDirGuard(if paths.created_tmpdir {
195        paths.tmpdir.clone()
196    } else {
197        None
198    });
199    let (mut allowed, edit_worktrees) = if is_repo {
200        let tasks_dir = blyte_agent::sandbox::conversation_tasks_dir(root);
201        std::fs::create_dir_all(&tasks_dir)
202            .map_err(|e| format!("cannot create {}: {e}", tasks_dir.display()))?;
203        let tasks_canon = tasks_dir
204            .canonicalize()
205            .map_err(|e| format!("cannot canonicalize {}: {e}", tasks_dir.display()))?;
206        let edit_worktrees = tasks_canon
207            .parent()
208            .map(|p| {
209                p.canonicalize()
210                    .map_err(|e| format!("cannot canonicalize {}: {e}", p.display()))
211            })
212            .transpose()?;
213        (vec![tasks_canon], edit_worktrees)
214    } else {
215        (Vec::new(), None)
216    };
217    for dir in paths.allowed {
218        match dir.canonicalize() {
219            Ok(canon) => {
220                if !allowed.contains(&canon) {
221                    allowed.push(canon);
222                }
223            }
224            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
225            Err(e) => return Err(format!("cannot canonicalize {}: {e}", dir.display())),
226        }
227    }
228    blyte_agent::tools::set_write_scope(Some(blyte_agent::tools::WriteScope {
229        allowed,
230        edit_worktrees,
231    }));
232    let rules = crate::approval_file::load()?;
233    let allowed_count = rules.len();
234    let approver: Arc<dyn blyte_agent::approval::Approver> =
235        approver.unwrap_or_else(|| Arc::new(blyte_agent::approval::NoApprover));
236    blyte_agent::tools::set_approval(Some(blyte_agent::approval::ApprovalConfig {
237        rules,
238        approver,
239    }));
240    tmp_cleanup.0 = None;
241    Ok(ConversePolicy {
242        allowed_count,
243        private_tmpdir: paths.tmpdir,
244    })
245}
246
247pub fn configure_converse_policy(
248    converse: bool,
249    sandbox_on: bool,
250    root: &Path,
251    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
252) -> Result<usize, String> {
253    Ok(configure_converse_policy_with_paths(converse, sandbox_on, root, approver)?.allowed_count)
254}
255
256struct BackgroundBaseCheckData {
257    state: blyte_agent::run::BaseCheckState,
258    elapsed_seconds: Option<f64>,
259}
260
261/// Runs the verification gate on the untouched base checkout on a background thread.
262pub struct BackgroundBaseCheck {
263    shared: Arc<(Mutex<BackgroundBaseCheckData>, Condvar)>,
264    cancel: Arc<blyte_agent::shell::CancelHandle>,
265    handle: Mutex<Option<std::thread::JoinHandle<()>>>,
266}
267
268impl BackgroundBaseCheck {
269    /// Starts the gate steps in `base_dir` on a thread using the same shell, sandbox, and
270    /// environment rules as the run's gate.
271    pub fn start(
272        config: &TaskConfig,
273        gate: String,
274        base_dir: PathBuf,
275        deadline: Option<std::time::Instant>,
276    ) -> Result<Self, String> {
277        let cancel = Arc::new(blyte_agent::shell::CancelHandle::new());
278        check_in_place_sandbox(config)?;
279        let (shell, tmp_guard): (Box<dyn blyte_agent::shell::Shell + Send>, TempDirGuard) =
280            match &config.container {
281                Some(cid) => (
282                    Box::new(blyte_agent::shell::CancellableContainerShell {
283                        inner: blyte_agent::shell::ContainerShell {
284                            container_id: cid.clone(),
285                            workdir: base_dir.clone(),
286                        },
287                        cancel: Arc::clone(&cancel),
288                    }),
289                    TempDirGuard(None),
290                ),
291                None => {
292                    let (inner, tmpdir) =
293                        if config.sandbox == "on" && blyte_agent::sandbox::available() {
294                            let (profile, tmpdir) = build_sandbox_for_root(config, &base_dir)?;
295                            (
296                                blyte_agent::shell::LocalShell::sandboxed(profile)
297                                    .with_tmpdir(tmpdir.clone()),
298                                tmpdir,
299                            )
300                        } else {
301                            (blyte_agent::shell::LocalShell::new(), None)
302                        };
303                    (
304                        Box::new(blyte_agent::shell::CancellableLocalShell {
305                            inner,
306                            cancel: Arc::clone(&cancel),
307                        }),
308                        TempDirGuard(tmpdir),
309                    )
310                }
311            };
312        let shared = Arc::new((
313            Mutex::new(BackgroundBaseCheckData {
314                state: blyte_agent::run::BaseCheckState::Pending,
315                elapsed_seconds: None,
316            }),
317            Condvar::new(),
318        ));
319        let thread_shared = Arc::clone(&shared);
320        let thread_cancel = Arc::clone(&cancel);
321        let join = std::thread::spawn(move || {
322            let _tmp_guard = tmp_guard;
323            let started = std::time::Instant::now();
324            let mut deadline = deadline;
325            let result = blyte_agent::run::run_gate_steps_cancellable(
326                shell.as_ref(),
327                &gate,
328                &base_dir,
329                &[],
330                &mut deadline,
331                |_| {},
332                &std::time::Instant::now,
333                Some(&thread_cancel),
334            );
335            if thread_cancel.is_cancelled() {
336                return;
337            }
338            let elapsed = started.elapsed().as_secs_f64();
339            let next_state = blyte_agent::run::base_check_state_from_gate(&result);
340            let (lock, cvar) = &*thread_shared;
341            let mut guard = match lock.lock() {
342                Ok(g) => g,
343                Err(e) => e.into_inner(),
344            };
345            guard.state = next_state;
346            guard.elapsed_seconds = Some(elapsed);
347            cvar.notify_all();
348        });
349        Ok(Self {
350            shared,
351            cancel,
352            handle: Mutex::new(Some(join)),
353        })
354    }
355}
356
357impl blyte_agent::run::BaseCheckHandle for BackgroundBaseCheck {
358    fn poll(&self) -> blyte_agent::run::BaseCheckState {
359        let (lock, _) = &*self.shared;
360        match lock.lock() {
361            Ok(g) => g.state.clone(),
362            Err(e) => e.into_inner().state.clone(),
363        }
364    }
365
366    fn wait(&self) -> blyte_agent::run::BaseCheckState {
367        let (lock, cvar) = &*self.shared;
368        let mut guard = match lock.lock() {
369            Ok(g) => g,
370            Err(e) => e.into_inner(),
371        };
372        while matches!(guard.state, blyte_agent::run::BaseCheckState::Pending) {
373            if self.cancel.is_cancelled() {
374                break;
375            }
376            guard = match cvar.wait(guard) {
377                Ok(g) => g,
378                Err(e) => e.into_inner(),
379            };
380        }
381        guard.state.clone()
382    }
383
384    fn stop(&self) {
385        self.cancel.cancel();
386        let (lock, cvar) = &*self.shared;
387        let guard = match lock.lock() {
388            Ok(g) => g,
389            Err(e) => e.into_inner(),
390        };
391        cvar.notify_all();
392        drop(guard);
393        let join = match self.handle.lock() {
394            Ok(mut g) => g.take(),
395            Err(e) => e.into_inner().take(),
396        };
397        if let Some(h) = join {
398            let _ = h.join();
399        }
400    }
401
402    fn elapsed_seconds(&self) -> Option<f64> {
403        let (lock, _) = &*self.shared;
404        match lock.lock() {
405            Ok(g) => g.elapsed_seconds,
406            Err(e) => e.into_inner().elapsed_seconds,
407        }
408    }
409}
410
411impl Drop for BackgroundBaseCheck {
412    fn drop(&mut self) {
413        blyte_agent::run::BaseCheckHandle::stop(self);
414    }
415}
416
417pub fn check_in_place_sandbox(config: &TaskConfig) -> Result<(), String> {
418    if config.in_place.is_some() {
419        if config.container.is_some() {
420            return Err(
421                "in-place runs need the sandbox: --container cannot be used with in-place runs"
422                    .into(),
423            );
424        }
425        if config.sandbox != "on" {
426            return Err(format!(
427                "in-place runs need the sandbox: --sandbox is '{}'",
428                config.sandbox
429            ));
430        }
431        if !blyte_agent::sandbox::available() {
432            return Err("in-place runs need the sandbox: sandbox is unavailable".into());
433        }
434    }
435    Ok(())
436}
437
438pub fn build_local_shell(
439    config: &TaskConfig,
440) -> Result<blyte_agent::shell::PersistentShell, String> {
441    Ok(build_local_shell_with_tmpdir(config)?.0)
442}
443
444fn build_local_shell_with_tmpdir(
445    config: &TaskConfig,
446) -> Result<(blyte_agent::shell::PersistentShell, Option<PathBuf>), String> {
447    check_in_place_sandbox(config)?;
448    if config.sandbox == "on" {
449        if blyte_agent::sandbox::available() {
450            let (profile, tmpdir) = build_sandbox_for_root(config, &config.root)?;
451            if matches!(profile, blyte_agent::sandbox::Profile::Landlock(_)) {
452                eprintln!(
453                    "blyte: on Linux the sandbox restricts writes only; credential reads are not blocked"
454                );
455            }
456            if matches!(profile, blyte_agent::sandbox::Profile::LandlockOffline(_)) {
457                eprintln!(
458                    "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
459                );
460            }
461            if let blyte_agent::sandbox::Profile::LandlockConfined { block_tcp, .. } = &profile {
462                eprintln!(
463                    "blyte: on Linux, commands can read only system directories, the workspace, tool caches and --allow-read paths"
464                );
465                if *block_tcp {
466                    eprintln!(
467                        "blyte: on Linux --network=off blocks TCP connections only (localhost included); UDP and the Docker socket are not blocked"
468                    );
469                }
470            }
471            let shell =
472                blyte_agent::shell::PersistentShell::local_sandboxed(config.root.clone(), profile)
473                    .with_tmpdir(tmpdir.clone());
474            if config.converse {
475                let root = config.root.clone();
476                let allow_read = config.allow_read.clone();
477                let network = config.network == "on";
478                Ok((
479                    shell.with_profile_builder(Arc::new(move || {
480                        blyte_agent::sandbox::conversation_profile_for_open_edits(
481                            &root,
482                            &allow_read,
483                            network,
484                        )
485                    })),
486                    tmpdir,
487                ))
488            } else {
489                Ok((shell, tmpdir))
490            }
491        } else {
492            eprintln!("warning: sandbox unavailable; running unsandboxed");
493            Ok((
494                blyte_agent::shell::PersistentShell::local(config.root.clone()),
495                None,
496            ))
497        }
498    } else {
499        Ok((
500            blyte_agent::shell::PersistentShell::local(config.root.clone()),
501            None,
502        ))
503    }
504}
505
506/// Validates network configuration against the environment and active flags.
507///
508/// Refuses `--network=off` when running with `--container`, when `--sandbox=off`,
509/// when the sandbox is unavailable, or on Linux when `landlock_abi() < 4`.
510pub fn check_network_mode(config: &TaskConfig) -> Result<(), String> {
511    if config.network == "off" {
512        if config.container.is_some() {
513            return Err(
514                "--network=off is not supported with --container; set the container's network instead"
515                    .into(),
516            );
517        }
518        if config.sandbox != "on" {
519            return Err("--network=off needs the sandbox".into());
520        }
521        #[cfg(target_os = "linux")]
522        if blyte_agent::sandbox::landlock_abi() < 4 {
523            return Err("--network=off on Linux needs Linux 6.7 or later".into());
524        }
525        if !blyte_agent::sandbox::available() {
526            return Err("--network=off needs the sandbox, but the sandbox is unavailable".into());
527        }
528    }
529    Ok(())
530}
531
532pub fn write_watchdog_report<F, W: Write>(
533    config: &TaskConfig,
534    progress: &Progress,
535    msg: &str,
536    elapsed: std::time::Duration,
537    resolve_model: F,
538    err_out: &mut W,
539) -> Result<Option<crate::report::RunRecord>, String>
540where
541    F: FnOnce(Option<&str>) -> Result<String, String>,
542{
543    let Some(path) = &config.report else {
544        return Ok(None);
545    };
546    let mut record = crate::report::RunRecord::from_error(config, msg, elapsed);
547    record.turns = progress.turns;
548    record.gate_attempts = progress.gate_attempts;
549    record.usage = crate::report::UsageRecord {
550        input: progress.usage.input,
551        cached: progress.usage.cached,
552        output: progress.usage.output,
553        thinking: progress.usage.thinking,
554    };
555    let model_id = match resolve_model(config.model.as_deref()) {
556        Ok(id) if !id.is_empty() => Some(id),
557        Ok(_) => {
558            let _ = writeln!(
559                err_out,
560                "blyte: watchdog warning: provider returned empty model id"
561            );
562            config.model.clone().filter(|m| !m.is_empty())
563        }
564        Err(err) => {
565            let _ = writeln!(
566                err_out,
567                "blyte: watchdog warning: could not resolve provider for cost lookup: {err}"
568            );
569            config.model.clone().filter(|m| !m.is_empty())
570        }
571    };
572    if let Some(id) = model_id {
573        record.cost_usd = blyte_provider::pricing(&id).map(|pr| pr.cost(&progress.usage));
574        record.model_id = Some(id);
575    }
576    crate::report::write(path, &record)?;
577    Ok(Some(record))
578}
579
580/// Executes an autonomous solver run using the provided task configuration and live stdout.
581///
582/// Configures the AI provider, context strategy, execution environment (local or container),
583/// and deterministic gate loop, printing live event progress as turns execute.
584///
585/// # Arguments
586///
587/// * `config` - Parameters governing prompt, budgets, gate verification, and environment.
588///
589/// # Returns
590///
591/// Returns `Ok((Outcome, RunReport))` containing final completion status and metrics,
592/// or an `Err(String)` describing initialization failure.
593pub fn run_task(
594    config: TaskConfig,
595) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
596    let started = std::time::Instant::now();
597    let progress = Arc::new(Mutex::new(Progress::default()));
598    if let Some(s) = config.max_seconds {
599        // BLYTE_WATCHDOG_GRACE_SECS exists for tests.
600        let grace_secs: u64 = std::env::var("BLYTE_WATCHDOG_GRACE_SECS")
601            .ok()
602            .and_then(|v| v.trim().parse().ok())
603            .unwrap_or(30);
604        let watchdog_config = config.clone();
605        let watchdog_progress = Arc::clone(&progress);
606        std::thread::spawn(move || {
607            loop {
608                let wait_ms = match watchdog_progress.lock() {
609                    Ok(g) => g.gate_wait_ms,
610                    Err(e) => e.into_inner().gate_wait_ms,
611                };
612                let deadline = started
613                    + std::time::Duration::from_secs(s.saturating_add(grace_secs))
614                    + std::time::Duration::from_millis(wait_ms);
615                match deadline.checked_duration_since(std::time::Instant::now()) {
616                    Some(remaining) if !remaining.is_zero() => {
617                        std::thread::sleep(remaining.min(std::time::Duration::from_millis(500)));
618                    }
619                    _ => break,
620                }
621            }
622            let p = match watchdog_progress.lock() {
623                Ok(g) => *g,
624                Err(e) => *e.into_inner(),
625            };
626            let msg = if p.in_gate {
627                format!(
628                    "stopped {grace_secs} s past --max-seconds {s}: gate attempt {} was still running",
629                    p.gate_attempts
630                )
631            } else {
632                format!(
633                    "stopped {grace_secs} s past --max-seconds {s} during turn {}: a model call or command never returned",
634                    p.turns
635                )
636            };
637            let mut stderr = std::io::stderr();
638            if let Err(err) = write_watchdog_report(
639                &watchdog_config,
640                &p,
641                &msg,
642                started.elapsed(),
643                |m| {
644                    blyte_provider::resolve_provider(m)
645                        .map(|pr| pr.model_id())
646                        .map_err(|e| e.to_string())
647                },
648                &mut stderr,
649            ) {
650                eprintln!("blyte: watchdog failed to write report: {err}");
651            }
652            eprintln!("blyte: {msg}");
653            std::process::exit(1);
654        });
655    }
656    let verification_cmd = config.gate.as_deref().unwrap_or("");
657    let mut state = blyte_agent::state::State::new(&config.prompt, verification_cmd);
658    state.brief.max_cost_usd = config.max_cost_usd;
659    let mut stdout = std::io::stdout();
660    let result =
661        run_task_with_state_writer_and_progress(&config, &mut state, &mut stdout, progress);
662    // The loop writes its own report; this covers a run that never reached it (e.g. no API
663    // key), so a caller always finds one. An absent report would read as a crash.
664    if let (Err(e), Some(path)) = (&result, &config.report) {
665        crate::report::write(
666            path,
667            &crate::report::RunRecord::from_error(&config, e, started.elapsed()),
668        )?;
669    }
670    result
671}
672
673/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`.
674///
675/// Preserves session mutations (epistemic ledger, patches, attempts) directly in the provided `state`.
676///
677/// # Arguments
678///
679/// * `config` - Execution parameters.
680/// * `state` - The mutable session state to advance.
681/// * `writer` - Stream writer sink for formatted events.
682///
683/// # Returns
684///
685/// Returns `Ok((Outcome, RunReport))` or an `Err(String)` describing failure.
686pub fn run_task_with_state_and_writer<W: Write>(
687    config: &TaskConfig,
688    state: &mut blyte_agent::state::State,
689    writer: &mut W,
690) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
691    let progress = Arc::new(Mutex::new(Progress::default()));
692    run_task_with_state_writer_and_progress(config, state, writer, progress)
693}
694
695/// Executes an autonomous solver run against an existing mutable `State`, passing every raw event
696/// directly to `on_event` without formatting lines to a writer.
697pub fn run_task_with_state_and_events(
698    config: &TaskConfig,
699    state: &mut blyte_agent::state::State,
700    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
701) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
702    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
703    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
704}
705
706pub fn run_task_with_state_and_max_duration(
707    config: &TaskConfig,
708    state: &mut blyte_agent::state::State,
709    max_duration: Option<std::time::Duration>,
710    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
711) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
712    run_task_with_event_callback(config, state, None, max_duration, &|event| on_event(event))
713}
714
715/// Executes an autonomous solver run with an explicit approver override (used by the surface).
716pub fn run_task_with_approver(
717    config: &TaskConfig,
718    state: &mut blyte_agent::state::State,
719    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
720    on_event: &(dyn Fn(&blyte_agent::run::Event<'_>) + Sync),
721) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
722    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
723    run_task_with_event_callback(config, state, approver, max_duration, &|event| {
724        on_event(event)
725    })
726}
727
728/// Executes an autonomous solver run against an existing mutable `State`, streaming events to `writer`
729/// and updating the shared `progress` record.
730pub fn run_task_with_state_writer_and_progress<W: Write>(
731    config: &TaskConfig,
732    state: &mut blyte_agent::state::State,
733    writer: &mut W,
734    progress: Arc<Mutex<Progress>>,
735) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
736    let writer_mutex = Mutex::new(writer);
737    let on_event = |event: &blyte_agent::run::Event<'_>| {
738        {
739            let mut p = match progress.lock() {
740                Ok(g) => g,
741                Err(e) => e.into_inner(),
742            };
743            match event {
744                blyte_agent::run::Event::Turn { n, usage, .. } => {
745                    p.turns = *n;
746                    p.usage.input += usage.input;
747                    p.usage.cached += usage.cached;
748                    p.usage.output += usage.output;
749                    p.usage.thinking += usage.thinking;
750                    p.in_gate = false;
751                }
752                blyte_agent::run::Event::GateStart { attempt } => {
753                    p.gate_attempts = *attempt;
754                    p.in_gate = true;
755                }
756                blyte_agent::run::Event::GateSlotWait { ms } => {
757                    p.gate_wait_ms += ms;
758                }
759                blyte_agent::run::Event::Gate { .. } => {
760                    p.in_gate = false;
761                }
762                _ => {}
763            }
764        }
765        let line = crate::repl::format_event(event);
766        if !line.is_empty() {
767            if let Ok(mut w) = writer_mutex.lock() {
768                let _ = writeln!(w, "{line}");
769            }
770        }
771    };
772    let max_duration = config.max_seconds.map(std::time::Duration::from_secs);
773    run_task_with_event_callback(config, state, None, max_duration, &on_event)
774}
775
776fn build_usage_entry(
777    config: &TaskConfig,
778    model_id: &str,
779    outcome: String,
780    turns: u32,
781    usage: &blyte_provider::Usage,
782) -> crate::usage_log::Entry {
783    let (surface, surface_name) = crate::usage_log::surface_from(
784        std::env::var(crate::usage_log::SURFACE_ID_ENV).ok(),
785        std::env::var(crate::usage_log::SURFACE_NAME_ENV).ok(),
786    );
787    crate::usage_log::Entry {
788        ts: std::time::SystemTime::now()
789            .duration_since(std::time::UNIX_EPOCH)
790            .map(|d| d.as_secs())
791            .unwrap_or(0),
792        repo: crate::usage_log::repo_of(&config.root),
793        session: crate::usage_log::session_from(
794            std::env::var("BLYTE_SESSION").ok(),
795            std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
796        ),
797        surface,
798        surface_name,
799        dispatch: std::env::var("BLYTE_DISPATCH_ID")
800            .ok()
801            .filter(|s| !s.is_empty()),
802        research: config.research,
803        model: model_id.to_string(),
804        outcome,
805        turns,
806        input: usage.input,
807        cached: usage.cached,
808        output: usage.output,
809        thinking: usage.thinking,
810        cost_usd: blyte_provider::pricing(model_id).map(|p| p.cost(usage)),
811    }
812}
813
814#[derive(Debug, PartialEq, Eq)]
815struct ExceededField {
816    field: &'static str,
817    written: u64,
818    total: u64,
819}
820
821fn usage_remainder(
822    total_turns: u32,
823    total_usage: &blyte_provider::Usage,
824    written_turns: u32,
825    written_usage: &blyte_provider::Usage,
826) -> Result<(u32, blyte_provider::Usage), Vec<ExceededField>> {
827    let mut exceeded = Vec::new();
828    if written_turns > total_turns {
829        exceeded.push(ExceededField {
830            field: "turns",
831            written: u64::from(written_turns),
832            total: u64::from(total_turns),
833        });
834    }
835    if written_usage.input > total_usage.input {
836        exceeded.push(ExceededField {
837            field: "input",
838            written: written_usage.input,
839            total: total_usage.input,
840        });
841    }
842    if written_usage.cached > total_usage.cached {
843        exceeded.push(ExceededField {
844            field: "cached",
845            written: written_usage.cached,
846            total: total_usage.cached,
847        });
848    }
849    if written_usage.output > total_usage.output {
850        exceeded.push(ExceededField {
851            field: "output",
852            written: written_usage.output,
853            total: total_usage.output,
854        });
855    }
856    if written_usage.thinking > total_usage.thinking {
857        exceeded.push(ExceededField {
858            field: "thinking",
859            written: written_usage.thinking,
860            total: total_usage.thinking,
861        });
862    }
863    if !exceeded.is_empty() {
864        return Err(exceeded);
865    }
866    Ok((
867        total_turns - written_turns,
868        blyte_provider::Usage {
869            input: total_usage.input - written_usage.input,
870            cached: total_usage.cached - written_usage.cached,
871            output: total_usage.output - written_usage.output,
872            thinking: total_usage.thinking - written_usage.thinking,
873        },
874    ))
875}
876
877/// Whether to print the list of withheld environment variables: once for each distinct list in
878/// this process. A surface runs many turns in one process, and the list is the same for each.
879fn withheld_notice_is_due(withheld: &[String]) -> bool {
880    static SHOWN: std::sync::Mutex<Option<Vec<String>>> = std::sync::Mutex::new(None);
881    if withheld.is_empty() {
882        return false;
883    }
884    let mut shown = SHOWN.lock().unwrap_or_else(|e| e.into_inner());
885    if shown.as_deref() == Some(withheld) {
886        return false;
887    }
888    *shown = Some(withheld.to_vec());
889    true
890}
891
892fn run_task_with_event_callback(
893    config: &TaskConfig,
894    state: &mut blyte_agent::state::State,
895    approver: Option<Arc<dyn blyte_agent::approval::Approver>>,
896    max_duration: Option<std::time::Duration>,
897    on_event: &dyn Fn(&blyte_agent::run::Event<'_>),
898) -> Result<(blyte_agent::run::Outcome, blyte_agent::run::RunReport), String> {
899    check_network_mode(config)?;
900    check_in_place_sandbox(config)?;
901    let started = std::time::Instant::now();
902    let (conversation_owned_tmpdir, _one_shot_tmp_guard) = if config.converse {
903        if std::env::var("BLYTE_SESSION")
904            .map(|v| v.is_empty())
905            .unwrap_or(true)
906        {
907            let now_secs = std::time::SystemTime::now()
908                .duration_since(std::time::UNIX_EPOCH)
909                .map(|d| d.as_secs())
910                .unwrap_or(0);
911            let id = crate::repl::new_session_id(now_secs, std::process::id());
912            std::env::set_var("BLYTE_SESSION", &id);
913        }
914        let sandbox_on = config.sandbox == "on";
915        let policy =
916            configure_converse_policy_with_paths(true, sandbox_on, &config.root, approver)?;
917        let (owned_tmpdir, guard) = if state.runtime.conversation.is_none() {
918            (None, policy.private_tmpdir.map(|p| TempDirGuard(Some(p))))
919        } else {
920            (policy.private_tmpdir, None)
921        };
922        if state.brief.instructions.is_none() {
923            let lines = crate::conversation_text::set_state_instructions(
924                state,
925                config.dispatch_cmd.is_some(),
926                &config.root,
927                sandbox_on,
928                policy.allowed_count,
929            )?;
930            if state.runtime.conversation.is_none() {
931                for line in &lines {
932                    eprintln!("blyte: {line}");
933                }
934            }
935        }
936        let exe = std::env::current_exe()
937            .map_err(|e| format!("cannot locate blyte executable for the blyte tool: {e}"))?;
938        blyte_agent::tools::set_blyte_tool(Some(exe));
939        if blyte_agent::sandbox::is_git_repository(&config.root) {
940            blyte_agent::tools::set_blyte_tasks_dir(None);
941            blyte_agent::tools::set_blyte_run_store(None);
942            blyte_agent::tools::set_in_place_lock_path(None);
943        } else {
944            let state_dir = crate::surface_registry::state_dir()?;
945            let tasks_dir = crate::surface_dir::tasks_dir(&state_dir, &config.root)?;
946            let run_store = crate::surface_dir::run_store(&state_dir, &config.root)?;
947            let lock_path = crate::surface_dir::in_place_lock_path(&state_dir, &config.root)?;
948            blyte_agent::tools::set_blyte_tasks_dir(Some(tasks_dir));
949            blyte_agent::tools::set_blyte_run_store(Some(run_store));
950            blyte_agent::tools::set_in_place_lock_path(Some(lock_path));
951        }
952        (owned_tmpdir, guard)
953    } else {
954        configure_converse_policy(false, false, &config.root, None)?;
955        blyte_agent::tools::set_blyte_tool(None);
956        blyte_agent::tools::set_blyte_tasks_dir(None);
957        blyte_agent::tools::set_blyte_run_store(None);
958        blyte_agent::tools::set_in_place_lock_path(None);
959        (None, None)
960    };
961    blyte_agent::tools::set_dispatch_cmd(config.dispatch_cmd.clone());
962    // 1. Initialize LLM provider from environment credentials or model specification.
963    // If credentials for the detected provider are missing, produce a clear error indicating which key to set.
964    let provider = match blyte_provider::resolve_provider(config.model.as_deref()) {
965        Ok(p) => p,
966        Err(blyte_provider::ProviderError::MissingKey(key)) => {
967            return Err(format!(
968                "Provider error: no API key: set {key} in environment"
969            ));
970        }
971        Err(e) => return Err(format!("Provider error: {e}")),
972    };
973
974    let model_id = provider.model_id();
975    if config.max_cost_usd.is_some() && blyte_provider::pricing(&model_id).is_none() {
976        return Err(format!(
977            "--max-cost needs a known price for {model_id}; none is known"
978        ));
979    }
980    state.brief.max_cost_usd = config.max_cost_usd;
981
982    // 2. Select context assembly strategy.
983    let folded = blyte_agent::context::Folded {
984        // Research quotes code read many turns earlier, so it keeps more before folding.
985        budget_tokens: config.fold_budget.unwrap_or(if config.research {
986            RESEARCH_FOLD_BUDGET
987        } else {
988            blyte_agent::context::Folded::default().budget_tokens
989        }),
990    };
991    let conversational = blyte_agent::context::Conversational;
992    let context_strategy: &dyn blyte_agent::context::ContextStrategy =
993        match config.context_strategy.as_str() {
994            "conversational" => &conversational,
995            _ => &folded,
996        };
997
998    // Persistent sessions: one for the harness's commands, one for the model's `bash` (its `cd`
999    // and `export` carry over). Container files go through a session too. Each falls back to a
1000    // process per command if a session cannot start.
1001    let local_fs = blyte_agent::fs::LocalFs;
1002    let snapshot_fs = match &config.in_place {
1003        Some(in_place) => Some(blyte_agent::snapshot_fs::SnapshotFs::new(
1004            blyte_agent::fs::LocalFs,
1005            config.root.clone(),
1006            in_place.before_dir.clone(),
1007            in_place.manifest.clone(),
1008        )?),
1009        None => None,
1010    };
1011    let mut _private_tmp_guard = TempDirGuard(None);
1012    let (persistent, session_fs, root) = match &config.container {
1013        Some(cid) => (
1014            blyte_agent::shell::PersistentShell::container(
1015                cid.clone(),
1016                PathBuf::from(&config.container_workdir),
1017            ),
1018            Some(blyte_agent::fs::SessionFs::container(
1019                cid.clone(),
1020                PathBuf::from(&config.container_workdir),
1021            )),
1022            PathBuf::from(&config.container_workdir),
1023        ),
1024        None => {
1025            blyte_agent::shell::set_pass_env(config.pass_env.clone());
1026            if !config.converse {
1027                if let Some(r) = blyte_agent::rules::load(&config.root) {
1028                    eprintln!("blyte: repository rules from {}", r.source.display());
1029                }
1030            }
1031            let withheld = blyte_agent::shell::withheld_env();
1032            if withheld_notice_is_due(&withheld) {
1033                eprintln!(
1034                    "blyte: withholding from commands: {} (keep one with --pass-env NAME)",
1035                    withheld.join(", ")
1036                );
1037            }
1038            let (shell, tmpdir) = build_local_shell_with_tmpdir(config)?;
1039            if tmpdir.is_some() && tmpdir != conversation_owned_tmpdir {
1040                _private_tmp_guard.0 = tmpdir;
1041            }
1042            (shell, None, config.root.clone())
1043        }
1044    };
1045    let shell: &dyn blyte_agent::shell::Shell = &persistent;
1046    let fs: &dyn blyte_agent::fs::Fs = match (&session_fs, &snapshot_fs) {
1047        (Some(f), _) => f,
1048        (None, Some(f)) => f,
1049        (None, None) => &local_fs,
1050    };
1051
1052    let usage_path = crate::usage_log::default_path();
1053    let written = Mutex::new((0u32, blyte_provider::Usage::default()));
1054    let runner_on_event = |event: blyte_agent::run::Event<'_>| {
1055        if let blyte_agent::run::Event::Turn { usage, .. } = &event {
1056            if let Some(path) = &usage_path {
1057                let entry = build_usage_entry(config, &model_id, "turn".to_string(), 1, usage);
1058                match crate::usage_log::append(path, &entry) {
1059                    Ok(()) => {
1060                        let mut w = match written.lock() {
1061                            Ok(g) => g,
1062                            Err(e) => e.into_inner(),
1063                        };
1064                        w.0 += 1;
1065                        w.1.input += usage.input;
1066                        w.1.cached += usage.cached;
1067                        w.1.output += usage.output;
1068                        w.1.thinking += usage.thinking;
1069                    }
1070                    Err(err) => eprintln!("warning: usage log: {err}"),
1071                }
1072            }
1073        }
1074        on_event(&event);
1075    };
1076
1077    let bg_base_check = match &config.base_check_dir {
1078        Some(base_dir)
1079            if !blyte_agent::run::gate_steps(&state.brief.verification_cmd).is_empty() =>
1080        {
1081            let deadline = max_duration.map(|d| std::time::Instant::now() + d);
1082            Some(BackgroundBaseCheck::start(
1083                config,
1084                state.brief.verification_cmd.clone(),
1085                base_dir.clone(),
1086                deadline,
1087            )?)
1088        }
1089        _ => None,
1090    };
1091    let base_check = if let Some(ref bg) = bg_base_check {
1092        blyte_agent::run::BaseCheck::Polled(bg)
1093    } else if config.base_check {
1094        blyte_agent::run::BaseCheck::BeforeFirstTurn
1095    } else {
1096        blyte_agent::run::BaseCheck::None
1097    };
1098
1099    let runner = blyte_agent::run::Runner {
1100        provider: provider.as_ref(),
1101        shell,
1102        fs,
1103        context: context_strategy,
1104        root,
1105        budget: blyte_agent::run::Budget {
1106            max_turns: config.max_turns as u32,
1107            max_gate_attempts: config.max_gates as u32,
1108            max_duration,
1109        },
1110        rollback: config.rollback && config.in_place.is_none(),
1111        on_event: Some(&runner_on_event),
1112        research: config.research,
1113        claim_check: config.claim_check,
1114        base_check,
1115    };
1116
1117    let (mut outcome, report) = runner.run(state);
1118    if config.in_place.is_some()
1119        && state.brief.verification_cmd.trim().is_empty()
1120        && matches!(outcome, blyte_agent::run::Outcome::Verified)
1121    {
1122        outcome = blyte_agent::run::Outcome::Finished;
1123    }
1124    drop(bg_base_check);
1125
1126    if let Some(path) = &usage_path {
1127        let (written_turns, written_usage) = match written.lock() {
1128            Ok(g) => *g,
1129            Err(e) => *e.into_inner(),
1130        };
1131        let (closing_turns, closing_usage) = match usage_remainder(
1132            report.outcome_turns,
1133            &report.usage,
1134            written_turns,
1135            &written_usage,
1136        ) {
1137            Ok(rem) => rem,
1138            Err(exceeded) => {
1139                for ExceededField {
1140                    field,
1141                    written,
1142                    total,
1143                } in exceeded
1144                {
1145                    eprintln!(
1146                        "error: usage log: turn lines exceed the run's total ({field}: {written} > {total})"
1147                    );
1148                }
1149                (0, blyte_provider::Usage::default())
1150            }
1151        };
1152        let entry = build_usage_entry(
1153            config,
1154            &model_id,
1155            format!("{outcome:?}").to_lowercase(),
1156            closing_turns,
1157            &closing_usage,
1158        );
1159        if let Err(err) = crate::usage_log::append(path, &entry) {
1160            eprintln!("warning: usage log: {err}");
1161        }
1162    }
1163
1164    if let Some(path) = &config.report {
1165        let mut record = crate::report::RunRecord::from_run(
1166            config,
1167            &model_id,
1168            &outcome,
1169            &report,
1170            state,
1171            started.elapsed(),
1172        );
1173        record.effort = provider.effort();
1174        crate::report::write(path, &record)?;
1175    }
1176    Ok((outcome, report))
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182
1183    #[test]
1184    fn usage_remainder_computes_exact_and_partial_remainders() {
1185        let total = blyte_provider::Usage {
1186            input: 600,
1187            cached: 150,
1188            output: 90,
1189            thinking: 75,
1190        };
1191        let exact = usage_remainder(3, &total, 3, &total).unwrap();
1192        assert_eq!(exact, (0, blyte_provider::Usage::default()));
1193
1194        let written = blyte_provider::Usage {
1195            input: 500,
1196            cached: 100,
1197            output: 80,
1198            thinking: 50,
1199        };
1200        let partial = usage_remainder(3, &total, 2, &written).unwrap();
1201        assert_eq!(
1202            partial,
1203            (
1204                1,
1205                blyte_provider::Usage {
1206                    input: 100,
1207                    cached: 50,
1208                    output: 10,
1209                    thinking: 25,
1210                }
1211            )
1212        );
1213    }
1214
1215    #[test]
1216    fn usage_remainder_reports_exceeding_fields() {
1217        let total = blyte_provider::Usage {
1218            input: 100,
1219            cached: 20,
1220            output: 30,
1221            thinking: 10,
1222        };
1223        let written = blyte_provider::Usage {
1224            input: 120,
1225            cached: 20,
1226            output: 35,
1227            thinking: 10,
1228        };
1229        let err = usage_remainder(2, &total, 3, &written).unwrap_err();
1230        assert_eq!(
1231            err,
1232            vec![
1233                ExceededField {
1234                    field: "turns",
1235                    written: 3,
1236                    total: 2,
1237                },
1238                ExceededField {
1239                    field: "input",
1240                    written: 120,
1241                    total: 100,
1242                },
1243                ExceededField {
1244                    field: "output",
1245                    written: 35,
1246                    total: 30,
1247                },
1248            ]
1249        );
1250    }
1251
1252    fn test_task_config(root: &Path, report: Option<PathBuf>, model: Option<String>) -> TaskConfig {
1253        TaskConfig {
1254            prompt: "test".to_string(),
1255            gate: Some("true".to_string()),
1256            context_strategy: "folded".to_string(),
1257            model,
1258            container: None,
1259            max_turns: 10,
1260            max_gates: 3,
1261            rollback: false,
1262            root: root.to_path_buf(),
1263            container_workdir: "/workspace".to_string(),
1264            max_seconds: Some(10),
1265            max_cost_usd: None,
1266            report,
1267            fold_budget: None,
1268            sandbox: "off".to_string(),
1269            network: "on".to_string(),
1270            allow_read: Vec::new(),
1271            pass_env: Vec::new(),
1272            research: false,
1273            claim_check: false,
1274            base_check: false,
1275            base_check_dir: None,
1276            converse: false,
1277            dispatch_cmd: None,
1278            in_place: None,
1279        }
1280    }
1281
1282    #[test]
1283    fn watchdog_report_write_failure_names_path_and_model_id_is_never_empty() {
1284        let dir = tempfile::tempdir().unwrap();
1285        let report_dir = dir.path().join("unwritable.report.json");
1286        std::fs::create_dir_all(&report_dir).unwrap();
1287
1288        let cfg = test_task_config(dir.path(), Some(report_dir.clone()), None);
1289        let progress = Progress {
1290            turns: 2,
1291            gate_attempts: 1,
1292            in_gate: false,
1293            gate_wait_ms: 0,
1294            usage: blyte_provider::Usage {
1295                input: 1000,
1296                cached: 0,
1297                output: 500,
1298                thinking: 0,
1299            },
1300        };
1301        let mut err_buf = Vec::new();
1302        let err = write_watchdog_report(
1303            &cfg,
1304            &progress,
1305            "stopped past --max-seconds",
1306            std::time::Duration::from_secs(5),
1307            |_| Err("missing API key".to_string()),
1308            &mut err_buf,
1309        )
1310        .expect_err("writing watchdog report to a directory must fail");
1311
1312        assert!(
1313            err.contains(&report_dir.display().to_string()),
1314            "write error must name report path, got: {err}"
1315        );
1316        let warning = String::from_utf8(err_buf).unwrap();
1317        assert!(
1318            warning.contains("missing API key"),
1319            "provider resolution error must be logged, got: {warning}"
1320        );
1321
1322        let ok_report = dir.path().join("ok.report.json");
1323        let ok_cfg = test_task_config(dir.path(), Some(ok_report.clone()), None);
1324        let mut ok_err = Vec::new();
1325        let rec = write_watchdog_report(
1326            &ok_cfg,
1327            &progress,
1328            "stopped past --max-seconds",
1329            std::time::Duration::from_secs(5),
1330            |_| Ok("gemini-3.8-flash-high".to_string()),
1331            &mut ok_err,
1332        )
1333        .expect("writing watchdog report to file must succeed")
1334        .expect("record must be returned");
1335
1336        assert_eq!(rec.model_id.as_deref(), Some("gemini-3.8-flash-high"));
1337        assert!(rec.cost_usd.is_some());
1338
1339        let fallback_report = dir.path().join("fallback.report.json");
1340        let fallback_cfg = test_task_config(dir.path(), Some(fallback_report), None);
1341        let mut fallback_err = Vec::new();
1342        let fallback_rec = write_watchdog_report(
1343            &fallback_cfg,
1344            &progress,
1345            "stopped past --max-seconds",
1346            std::time::Duration::from_secs(5),
1347            |_| Err("no provider".to_string()),
1348            &mut fallback_err,
1349        )
1350        .expect("writing watchdog report must succeed")
1351        .expect("record must be returned");
1352
1353        assert_ne!(fallback_rec.model_id.as_deref(), Some(""));
1354        assert_eq!(fallback_rec.model_id, None);
1355        assert!(String::from_utf8(fallback_err)
1356            .unwrap()
1357            .contains("no provider"));
1358    }
1359
1360    #[test]
1361    fn build_usage_entry_records_surface_env() {
1362        let _guard = crate::usage_log::ENV_LOCK
1363            .lock()
1364            .unwrap_or_else(|e| e.into_inner());
1365        let prev_id = std::env::var_os(crate::usage_log::SURFACE_ID_ENV);
1366        let prev_name = std::env::var_os(crate::usage_log::SURFACE_NAME_ENV);
1367
1368        let dir = tempfile::tempdir().unwrap();
1369        let cfg = test_task_config(dir.path(), None, None);
1370        let usage = blyte_provider::Usage::default();
1371
1372        std::env::set_var(crate::usage_log::SURFACE_ID_ENV, "s1");
1373        std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, "alpha");
1374        let with_surface = build_usage_entry(&cfg, "m", "verified".into(), 1, &usage);
1375
1376        std::env::remove_var(crate::usage_log::SURFACE_ID_ENV);
1377        std::env::remove_var(crate::usage_log::SURFACE_NAME_ENV);
1378        let without_surface = build_usage_entry(&cfg, "m", "verified".into(), 1, &usage);
1379
1380        match prev_id {
1381            Some(v) => std::env::set_var(crate::usage_log::SURFACE_ID_ENV, v),
1382            None => std::env::remove_var(crate::usage_log::SURFACE_ID_ENV),
1383        }
1384        match prev_name {
1385            Some(v) => std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, v),
1386            None => std::env::remove_var(crate::usage_log::SURFACE_NAME_ENV),
1387        }
1388
1389        assert_eq!(with_surface.surface.as_deref(), Some("s1"));
1390        assert_eq!(with_surface.surface_name.as_deref(), Some("alpha"));
1391        assert_eq!(without_surface.surface, None);
1392        assert_eq!(without_surface.surface_name, None);
1393    }
1394}