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