overbrainer 0.4.0

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

mod complete;
mod config_check;
pub(crate) mod data;
pub(crate) mod front;
mod history;
pub(crate) mod init;
pub(crate) mod migrate;
pub(crate) mod pod;
mod progress;
mod record;
mod reload;
mod runpod_train;
mod skill;
pub(crate) mod train;

use std::io::IsTerminal as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use clap::{Args, Parser, Subcommand, ValueHint};
use clap_complete::engine::ArgValueCandidates;
use secrecy::SecretString;
use tokio::sync::OnceCell;
use tokio::task::JoinHandle;

use self::front::Frontend;
use self::reload::Reloader;
use crate::config::{DotenvKeys, EnvSource, Source};
use crate::events::Observer;
use crate::logging::{LOG_LINES, LogBuffer, LogMode};
use crate::metrics::{Metrics, MetricsServer};
use crate::secrets::{Resolver, SecretError, SecretSource, VaultRef, VaultSettings, VaultSource};
use crate::update::{self, CheckEnv, Newer};

/// How long a command that ended waits for the update check still running.
const CHECK_GRACE: Duration = Duration::from_millis(500);

/// The `overbrainer` command line interface.
#[derive(Debug, Parser)]
#[command(name = "overbrainer", version, about)]
pub struct Cli {
    /// Project directory containing overbrainer.toml.
    #[arg(short = 'C', long, global = true, default_value = ".", value_hint = ValueHint::DirPath)]
    pub project_dir: PathBuf,

    /// The subcommand to run.
    #[command(subcommand)]
    pub command: Command,

    /// Whether `tui` starts in auto mode: set by the init wizard, never
    /// parsed.
    #[arg(skip)]
    pub auto: bool,
}

/// Top-level subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Create an example project (overbrainer.toml, .env.example, prompts/, .gitignore).
    Init {
        /// Target directory. Defaults to the project directory (`-C`).
        #[arg(value_hint = ValueHint::DirPath)]
        dir: Option<PathBuf>,
    },
    /// Inspect the configuration.
    Config {
        /// The configuration subcommand to run.
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Generate the subtopics of each topic into data/subtopics.jsonl.
    Subtopics(StageArgs),
    /// Generate questions for each subtopic into data/questions.jsonl.
    ///
    /// Topics without subtopics get them first, as `overbrainer subtopics` would.
    Questions(StageArgs),
    /// Ask the parent model to answer each question into data/answers.jsonl.
    ///
    /// Resuming skips every question that already has an answer, including answers
    /// excluded from training (truncated, refused, empty, no raw reasoning). Only
    /// `--force` asks the parent again for them.
    Answers(StageArgs),
    /// Split usable answers into data/train.jsonl and data/eval.jsonl.
    ///
    /// Both files are always rewritten from scratch with the usable examples of every
    /// topic: `--topic` only limits the counts printed. Answers whose topic is no longer
    /// in overbrainer.toml, or whose question is no longer in data/questions.jsonl (for
    /// example after the questions were regenerated), are left out and counted as
    /// orphaned; they stay in data/answers.jsonl.
    Split(SplitArgs),
    /// Run subtopics, questions, answers and split in order, then train when
    /// overbrainer.toml has a `[training]` section.
    Run,
    /// Fine-tune the child model on data/train.jsonl, evaluating on data/eval.jsonl.
    ///
    /// The job runs detached on the target and writes to `runs/<run-id>/`. Ctrl-C stops
    /// following it but leaves it running: `overbrainer train attach <run-id>` follows
    /// it again, `overbrainer train cancel <run-id>` stops it.
    Train(TrainArgs),
    /// Inspect training runs.
    Runs {
        /// The runs subcommand to run.
        #[command(subcommand)]
        command: RunsCommand,
    },
    /// Show what the pipeline stages did and spent, from .overbrainer/history.jsonl.
    History(HistoryArgs),
    /// Bring a project from an older overbrainer up to this one's format.
    ///
    /// Adds /.overbrainer/ to .gitignore, rebuilds the answers history from
    /// data/answers.jsonl (tokens per model, cost unknown) unless the history
    /// already has answers, and writes .overbrainer/version. Running it again
    /// changes nothing.
    Migrate(MigrateArgs),
    /// Find and remove the Runpod pods overbrainer created.
    Pod {
        /// The pod subcommand to run.
        #[command(subcommand)]
        command: PodCommand,
    },
    /// Install the agent skill that teaches AI coding agents to drive overbrainer.
    Skill {
        /// The skill subcommand to run.
        #[command(subcommand)]
        command: SkillCommand,
    },
    /// Browse the dataset, run stages and follow training runs in a terminal UI.
    Tui,
}

impl Command {
    /// Where this command's logs go: an in-memory buffer for `tui`, which owns the
    /// terminal, stderr for every other command.
    #[must_use]
    pub fn log_mode(&self) -> LogMode {
        match self {
            Self::Tui => LogMode::Tui(LogBuffer::new(LOG_LINES)),
            _ => LogMode::Stderr,
        }
    }

    /// Whether this command serves the metrics while it holds the project lock:
    /// every command that writes, but `migrate`, which spends nothing.
    #[must_use]
    pub fn serves_metrics(&self) -> bool {
        self.writes_project() && !matches!(self, Self::Migrate(_))
    }

    /// Whether this command writes to the project, and so must hold the project
    /// lock: at most one such overbrainer process per project.
    #[must_use]
    pub fn writes_project(&self) -> bool {
        match self {
            Self::Tui
            | Self::Subtopics(_)
            | Self::Questions(_)
            | Self::Answers(_)
            | Self::Split(_)
            | Self::Run
            | Self::Migrate(_)
            | Self::Train(_) => true,
            Self::Pod { command } => matches!(command, PodCommand::Rm { .. }),
            Self::Init { .. }
            | Self::Config { .. }
            | Self::Runs { .. }
            | Self::History(_)
            | Self::Skill { .. } => false,
        }
    }
}

/// Subcommands of `overbrainer pod`.
#[derive(Debug, Subcommand)]
pub enum PodCommand {
    /// List the pods overbrainer created, with their run and what is known of it.
    Ls,
    /// Delete every pod of a run, and wait until Runpod no longer shows them.
    Rm {
        /// ID of the run, as shown by `overbrainer runs ls` or `overbrainer pod ls`.
        #[arg(add = ArgValueCandidates::new(complete::run_ids))]
        run_id: String,
        /// Delete even when the run's job is still running (the run is then failed).
        #[arg(long)]
        force: bool,
    },
    /// List the Runpod catalog's Secure Cloud GPU types, cheapest first.
    Gpus(GpuArgs),
    /// List the Runpod catalog's data centers, by ID.
    Datacenters,
    /// List the account's network volumes, by name.
    Volumes,
    /// List the account's pod templates, by name.
    Templates,
}

/// Options of `overbrainer pod gpus`.
#[derive(Debug, Default, Args)]
pub struct GpuArgs {
    /// Only GPU types with at least this much VRAM, in GB.
    #[arg(long)]
    pub min_vram: Option<u32>,
    /// Only GPU types priced at or under this, in USD per hour.
    #[arg(long)]
    pub max_price: Option<f64>,
    /// Only GPU types offered in this data center, whose stock there is shown
    /// instead of the overall stock.
    #[arg(long)]
    pub data_center: Option<String>,
    /// Only GPU types with some stock.
    #[arg(long)]
    pub in_stock: bool,
}

/// Subcommands of `overbrainer skill`.
#[derive(Debug, Subcommand)]
pub enum SkillCommand {
    /// Write the skill to `<project>/.claude/skills/overbrainer/SKILL.md`, or with
    /// --global to ~/.claude/skills, or with --dir to another agent's skills directory.
    Install(SkillInstallArgs),
}

/// Options of `overbrainer skill install`.
#[derive(Debug, Args)]
pub struct SkillInstallArgs {
    /// Install for every project, in ~/.claude/skills.
    #[arg(long, conflicts_with = "dir")]
    pub global: bool,
    /// Install into this skills directory instead.
    #[arg(long, value_hint = ValueHint::DirPath)]
    pub dir: Option<PathBuf>,
    /// Replace an installed skill that differs from this version's.
    #[arg(long)]
    pub force: bool,
}

/// Options and subcommands of `overbrainer train`.
#[derive(Debug, Default, Args)]
#[command(args_conflicts_with_subcommands = true)]
pub struct TrainArgs {
    /// Train on this target instead of training.target.
    #[arg(long, add = ArgValueCandidates::new(complete::targets))]
    pub target: Option<String>,
    /// Runpod target only: keep the pod once the run ends, with no time limit.
    /// Nothing deletes it then but `overbrainer pod rm <run-id>`.
    #[arg(long)]
    pub keep_pod: bool,
    /// Follow or stop an existing run instead of starting one.
    #[command(subcommand)]
    pub command: Option<TrainCommand>,
}

/// Subcommands of `overbrainer train`.
#[derive(Debug, Subcommand)]
pub enum TrainCommand {
    /// Follow a run again after Ctrl-C or a lost connection, then retrieve its results.
    Attach {
        /// ID of the run, as shown by `overbrainer runs ls`.
        #[arg(add = ArgValueCandidates::new(complete::run_ids))]
        run_id: String,
    },
    /// Stop the job of a run.
    Cancel {
        /// ID of the run, as shown by `overbrainer runs ls`.
        #[arg(add = ArgValueCandidates::new(complete::run_ids))]
        run_id: String,
    },
}

/// Subcommands of `overbrainer runs`.
#[derive(Debug, Subcommand)]
pub enum RunsCommand {
    /// List the runs in runs/, oldest first: ID, state, target, creation time, and
    /// the pod of a Runpod run.
    Ls,
}

/// Options of `overbrainer history`.
#[derive(Debug, Default, Args)]
pub struct HistoryArgs {
    /// List every execution, oldest first, instead of the totals per stage.
    #[arg(long)]
    pub all: bool,
}

/// Options of `overbrainer migrate`.
#[derive(Debug, Default, Args)]
pub struct MigrateArgs {
    /// Print what would change, and change no project file (the lock is still
    /// taken).
    #[arg(long)]
    pub dry_run: bool,
}

/// Options shared by the pipeline stage commands.
#[derive(Debug, Default, Args)]
pub struct StageArgs {
    /// Only process this topic.
    #[arg(long, add = ArgValueCandidates::new(complete::topics))]
    pub topic: Option<String>,
    /// Regenerate this stage's output for the selected topics instead of resuming.
    #[arg(long)]
    pub force: bool,
}

/// Options of `overbrainer split`.
#[derive(Debug, Default, Args)]
pub struct SplitArgs {
    /// Only count this topic in the printed report. Both files still hold every topic.
    #[arg(long, add = ArgValueCandidates::new(complete::topics))]
    pub topic: Option<String>,
}

/// Subcommands of `overbrainer config`.
#[derive(Debug, Subcommand)]
pub enum ConfigCommand {
    /// Print the resolved configuration with secrets masked.
    Check {
        /// Also resolve every secret, testing Vault access.
        #[arg(long)]
        resolve: bool,
    },
}

/// Runs the init wizard when `cli` is `tui` on a terminal and the project
/// has no `overbrainer.toml`, before anything else: `.env` is loaded after
/// it, which it may write, and the project lock is taken once the files
/// exist. Returns whether the command goes on: not when the wizard was quit.
///
/// # Errors
///
/// Returns an error when the wizard cannot use the terminal.
pub fn wizard(cli: &mut Cli) -> anyhow::Result<bool> {
    if !wants_wizard(cli, std::io::stdout().is_terminal()) {
        return Ok(true);
    }
    // Refused before the first screen, not after the seventh.
    if let Some(refusal) = crate::tui::wizard_refusal(&cli.project_dir) {
        anyhow::bail!(refusal);
    }
    match crate::tui::wizard(&cli.project_dir)? {
        crate::tui::WizardEnded::Open { auto } => {
            cli.auto = auto;
            Ok(true)
        },
        crate::tui::WizardEnded::Quit { written: false } => {
            eprintln!("init wizard quit: nothing was written");
            Ok(false)
        },
        crate::tui::WizardEnded::Quit { written: true } => {
            eprintln!("the project is written: `overbrainer tui` opens it");
            Ok(false)
        },
    }
}

/// Whether `cli` opens the init wizard: `tui`, on a terminal, in a project
/// directory that exists and has no `overbrainer.toml`. A missing directory
/// fails as it did, never created.
fn wants_wizard(cli: &Cli, stdout_is_terminal: bool) -> bool {
    matches!(cli.command, Command::Tui)
        && stdout_is_terminal
        && cli.project_dir.is_dir()
        && cli
            .project_dir
            .join(crate::config::CONFIG_FILE)
            .symlink_metadata()
            .is_err()
}

/// Runs the parsed command line, whose logs were set up with `logs` (see
/// [`Command::log_mode`]); `dotenv` are the keys `.env` set at start, which a
/// reload of the configuration replaces (`tui`, and `run` between stages). Meanwhile it looks for a newer release, told on
/// stderr once the command ended, even with an error (`tui` shows it itself),
/// as is the need to run `overbrainer migrate` on a project from before 0.4.0.
///
/// # Errors
///
/// Returns an error if the selected subcommand fails, or if `tui` is not given the
/// [`LogMode::Tui`] its logs need.
pub async fn run(cli: Cli, logs: LogMode, dotenv: DotenvKeys) -> anyhow::Result<()> {
    let stderr = std::io::stderr().is_terminal();
    let stdout = std::io::stdout().is_terminal();
    // `skill` never checks: it does not even read the environment.
    let env = (!matches!(cli.command, Command::Skill { .. })).then(CheckEnv::from_process);
    let mut check = env
        .filter(|env| should_check(&cli.command, stderr, stdout, env))
        .map(|env| {
            tokio::spawn(async move {
                update::check(&env, update::CRATES_IO_URL, SystemTime::now()).await
            })
        });
    let hint = migrate::hints(&cli.command, &cli.project_dir);
    let result = dispatch(cli, logs, &mut check, dotenv).await;
    if hint {
        eprintln!("{}", migrate::HINT);
    }
    // `tui` took the check, and shows its answer itself.
    if let Some(check) = check
        && let Some(newer) = settle(check).await
    {
        eprintln!("{newer}");
    }
    result
}

/// Whether to look for a newer release beside `command`: not when turned off,
/// not for `skill`, and not when stderr, where the notice goes, is not a
/// terminal, except for `tui`, which shows it on its own screen, and so needs
/// stdout a terminal instead (it refuses to start otherwise).
fn should_check(
    command: &Command,
    stderr_is_terminal: bool,
    stdout_is_terminal: bool,
    env: &CheckEnv,
) -> bool {
    !env.disabled
        && match command {
            Command::Skill { .. } => false,
            Command::Tui => stdout_is_terminal,
            _ => stderr_is_terminal,
        }
}

/// The answer of `check`, waiting for it at most [`CHECK_GRACE`]; a check
/// still running then is dropped.
async fn settle(mut check: JoinHandle<Option<Newer>>) -> Option<Newer> {
    let answer = tokio::time::timeout(CHECK_GRACE, &mut check).await;
    check.abort();
    answer.ok()?.ok()?
}

/// Runs `cli`'s command; `tui` takes `check` to show its answer.
async fn dispatch(
    cli: Cli,
    logs: LogMode,
    check: &mut Option<JoinHandle<Option<Newer>>>,
    dotenv: DotenvKeys,
) -> anyhow::Result<()> {
    let dir = &cli.project_dir;
    let auto = cli.auto;
    // Only a project takes the lock: without `overbrainer.toml` the command fails
    // with its usual error and leaves nothing behind.
    let lock = if cli.command.writes_project() && dir.join(crate::config::CONFIG_FILE).is_file() {
        Some(crate::project_lock::ProjectLock::acquire(dir)?)
    } else {
        None
    };
    // Served while the lock is held: dropped before it.
    let served = served_metrics(&cli.command, dir, lock.is_some()).await;
    // The buses of the command count into the served metrics, if any.
    let observer = served
        .as_ref()
        .map(|(_, metrics)| Arc::clone(metrics) as Arc<dyn Observer>);
    let front = Frontend::Cli(observer.clone());
    match cli.command {
        Command::Init { dir: target } => init::run(target.as_deref().unwrap_or(dir)),
        Command::Config {
            command: ConfigCommand::Check { resolve },
        } => config_check::run(dir, resolve).await,
        Command::Subtopics(args) => stage(dir, &front, data::Command::Subtopics, &args).await,
        Command::Questions(args) => stage(dir, &front, data::Command::Questions, &args).await,
        Command::Answers(args) => stage(dir, &front, data::Command::Answers, &args).await,
        Command::Split(SplitArgs { topic }) => {
            let args = StageArgs {
                topic,
                force: false,
            };
            stage(dir, &front, data::Command::Split, &args).await
        },
        Command::Run => {
            let mut reloader = Reloader::new(dir, dotenv);
            let args = StageArgs::default();
            let load = data::Load::Reload(&mut reloader);
            data::run(dir, data::Command::Run, &args, &front, load).await?;
            train::after_run(dir, &front, &mut reloader).await
        },
        Command::Train(args) => {
            let source = Source::from(EnvSource::Process);
            train::run(dir, &args, &front, &source).await
        },
        Command::Runs {
            command: RunsCommand::Ls,
        } => train::list(dir),
        Command::History(args) => history::run(dir, &args),
        Command::Migrate(args) => migrate::run(dir, args.dry_run),
        Command::Pod { command } => pod::run(dir, &command).await,
        Command::Skill { command } => skill::run(dir, &command),
        Command::Tui => match logs {
            LogMode::Tui(buffer) => {
                let start = crate::tui::Start { dotenv, auto };
                crate::tui::run(dir, buffer, check.take(), start, observer).await
            },
            LogMode::Stderr => anyhow::bail!("overbrainer tui needs the TUI log mode"),
        },
    }
}

/// Runs a pipeline command on the command line, through `front`.
async fn stage(
    dir: &Path,
    front: &Frontend,
    command: data::Command,
    args: &StageArgs,
) -> anyhow::Result<()> {
    let load = data::Load::Source(&Source::from(EnvSource::Process));
    data::run(dir, command, args, front, load).await
}

/// [`serve_metrics`] when `command` holds the lock (`locked`) and serves them.
async fn served_metrics(
    command: &Command,
    dir: &Path,
    locked: bool,
) -> Option<(MetricsServer, Arc<Metrics>)> {
    if locked && command.serves_metrics() {
        serve_metrics(dir).await
    } else {
        None
    }
}

/// Serves the Prometheus metrics of the project in `dir` when `metrics.listen` is
/// set, with the metrics it serves. Nothing here fails the command: a
/// configuration error is the command's to report, and an address that cannot be
/// bound only warns.
async fn serve_metrics(dir: &Path) -> Option<(MetricsServer, Arc<Metrics>)> {
    let settings = crate::config::load(dir, EnvSource::Process).ok()?;
    let address = settings.metrics.listen?;
    if !address.ip().is_loopback() {
        tracing::warn!("metrics on {address} have no authentication");
    }
    let metrics = Arc::new(project_metrics(dir));
    crate::metrics::serve(address, Arc::clone(&metrics))
        .await
        .inspect(|server| tracing::info!("metrics at http://{}/metrics", server.address()))
        .inspect_err(|error| tracing::warn!("cannot serve the metrics on {address}: {error}"))
        .ok()
        .map(|server| (server, metrics))
}

/// The metrics of the project in `dir`, from its stage history and its runs.
fn project_metrics(dir: &Path) -> Metrics {
    let history = crate::history::read(dir).unwrap_or_else(|error| {
        tracing::warn!("cannot read the stage history, the metrics start from zero: {error}");
        Vec::new()
    });
    Metrics::new(&history).with_runs(crate::runs::Runs::new(dir))
}

/// Secret resolver from `VAULT_ADDR`, `VAULT_TOKEN` and `~/.vault-token`. Vault is
/// only set up when a `vault:` reference is first resolved, so literal secrets work
/// even when Vault settings are incomplete. Without `VAULT_ADDR`, references fail
/// when used.
fn resolver() -> Resolver<LazyVault> {
    Resolver::new(Some(LazyVault::default()))
}

/// A [`VaultSource`] built from the environment on the first fetch.
#[derive(Default)]
struct LazyVault {
    source: OnceCell<Option<VaultSource>>,
}

impl LazyVault {
    async fn source(&self) -> Result<Option<&VaultSource>, SecretError> {
        let source = self.source.get_or_try_init(|| async { vault() }).await?;
        Ok(source.as_ref())
    }
}

impl SecretSource for LazyVault {
    async fn fetch(&self, reference: &VaultRef) -> Result<SecretString, SecretError> {
        match self.source().await? {
            Some(source) => source.fetch(reference).await,
            None => Err(SecretError::VaultNotConfigured),
        }
    }
}

fn vault() -> Result<Option<VaultSource>, SecretError> {
    let home = std::env::var_os("HOME").map(PathBuf::from);
    VaultSettings::from_env(|key| std::env::var(key).ok(), home.as_deref())?
        .map(|settings| VaultSource::new(&settings))
        .transpose()
}

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

    fn command(args: &[&str]) -> Result<Command, clap::Error> {
        let cli = Cli::try_parse_from(std::iter::once("overbrainer").chain(args.iter().copied()))?;
        Ok(cli.command)
    }

    #[test]
    fn the_update_check_runs_on_a_terminal_unless_turned_off() -> Result<(), clap::Error> {
        let on = CheckEnv::default();
        let off = CheckEnv {
            disabled: true,
            cache_dir: None,
        };
        // (args, stderr a terminal, stdout a terminal, env, expected)
        for (args, stderr, stdout, env, expected) in [
            (&["run"][..], true, true, &on, true),
            (&["history"], true, false, &on, true),
            (&["run"], false, true, &on, false),
            (&["run"], true, true, &off, false),
            (&["skill", "install"], true, true, &on, false),
            (&["tui"], true, true, &on, true),
            (&["tui"], false, true, &on, true),
            (&["tui"], true, false, &on, false),
            (&["tui"], true, true, &off, false),
        ] {
            assert_eq!(
                should_check(&command(args)?, stderr, stdout, env),
                expected,
                "{args:?}, stderr a terminal: {stderr}, stdout: {stdout}, disabled: {}",
                env.disabled
            );
        }
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn the_notice_waits_at_most_the_grace_period() {
        let check = tokio::spawn(std::future::pending::<Option<Newer>>());
        let start = tokio::time::Instant::now();
        assert_eq!(settle(check).await, None);
        assert_eq!(start.elapsed(), CHECK_GRACE);
    }

    #[tokio::test(start_paused = true)]
    async fn a_finished_check_gives_its_answer() {
        let newer = Newer {
            latest: "9.0.0".into(),
            current: "0.4.0",
        };
        let answer = newer.clone();
        let check = tokio::spawn(async move { Some(answer) });
        assert_eq!(settle(check).await, Some(newer));
    }

    #[test]
    fn the_wizard_opens_only_for_tui_in_an_existing_directory_without_a_config()
    -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile::tempdir()?;
        let path = dir.path().to_string_lossy().into_owned();
        let missing = dir.path().join("missing").to_string_lossy().into_owned();
        let cli = |args: &[&str]| Cli::try_parse_from(args);
        assert!(wants_wizard(
            &cli(&["overbrainer", "-C", &path, "tui"])?,
            true
        ));
        assert!(!wants_wizard(
            &cli(&["overbrainer", "-C", &path, "tui"])?,
            false
        ));
        assert!(!wants_wizard(
            &cli(&["overbrainer", "-C", &path, "run"])?,
            true
        ));
        assert!(!wants_wizard(
            &cli(&["overbrainer", "-C", &missing, "tui"])?,
            true
        ));
        assert!(!dir.path().join("missing").exists());
        std::fs::write(dir.path().join(crate::config::CONFIG_FILE), "")?;
        assert!(!wants_wizard(
            &cli(&["overbrainer", "-C", &path, "tui"])?,
            true
        ));
        Ok(())
    }

    #[test]
    fn only_commands_that_write_take_the_lock() -> Result<(), clap::Error> {
        let writes = |args: &[&str]| -> Result<bool, clap::Error> {
            let cli =
                Cli::try_parse_from(std::iter::once("overbrainer").chain(args.iter().copied()))?;
            Ok(cli.command.writes_project())
        };
        for args in [
            &["tui"][..],
            &["subtopics"],
            &["questions"],
            &["answers"],
            &["split"],
            &["run"],
            &["train"],
            &["train", "attach", "x"],
            &["train", "cancel", "x"],
            &["pod", "rm", "x"],
            &["migrate"],
            &["migrate", "--dry-run"],
        ] {
            assert!(writes(args)?, "{args:?} should lock");
        }
        let serves = |args: &[&str]| -> Result<bool, clap::Error> {
            let cli =
                Cli::try_parse_from(std::iter::once("overbrainer").chain(args.iter().copied()))?;
            Ok(cli.command.serves_metrics())
        };
        assert!(serves(&["run"])? && serves(&["tui"])?);
        assert!(!serves(&["migrate"])? && !serves(&["history"])?);
        for args in [
            &["init"][..],
            &["config", "check"],
            &["runs", "ls"],
            &["history"],
            &["pod", "ls"],
            &["skill", "install"],
        ] {
            assert!(!writes(args)?, "{args:?} should not lock");
        }
        Ok(())
    }
}