agent-loadout 1.0.0

Loadout CLI: manage MCP servers, skills and secret references for AI coding clients
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
//! `loadout` CLI. Thin over `agent-loadout-core`; builds its [`Env`] from the
//! running process with [`Env::from_process`].

mod cmd;
mod exec;
mod interrupt;
mod keyring;
mod logging;

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Instant;

use agent_loadout_core::diagnostics::report::{self, ReportOptions};
use agent_loadout_core::paths::{self, LoadoutHome, SyncRoot};
use agent_loadout_core::store::{HistoryFinding, Store};
use agent_loadout_core::{CoreError, Env, ErrorCode, KnownFolder, RealFs, brand, versions};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::{Value, json};

use cmd::{Context, JSON_SCHEMA, path_json, print_json, sync_root_warning};

#[derive(Debug, Parser)]
#[command(
    name = brand::BIN_NAME,
    version,
    about = "Manage MCP servers, skills and secret references for AI coding clients"
)]
struct Cli {
    /// Data directory to use instead of LOADOUT_HOME or the per-OS default.
    #[arg(long, global = true, value_name = "PATH")]
    home: Option<PathBuf>,
    /// Print machine-readable JSON to stdout.
    #[arg(long, global = true)]
    json: bool,
    /// Answer yes to confirmations (rolling back an older apply run).
    #[arg(long, global = true)]
    yes: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Check the installation and report problems.
    Doctor(DoctorArgs),
    /// Manage MCP servers in the store.
    Server(cmd::server::ServerArgs),
    /// Skills: install, enable for clients and projects, update, scan.
    Skills(cmd::skills::SkillsArgs),
    /// The read-only Loadout skill for coding agents: install, remove,
    /// status, skill-path.
    Agent(cmd::agent::AgentArgs),
    /// Trusted and blocked install sources: list, trust, block, untrust.
    Source(cmd::source::SourceArgs),
    /// Catalogs of MCP servers and skills: list, add, search, show.
    Catalog(cmd::catalog::CatalogArgs),
    /// Scanners: the built-in scanner and the optional SkillSpector (runs
    /// locally; off by default).
    Scanner(cmd::scanner::ScannerArgs),
    /// Project manifests: create, register, trust, share, list, forget.
    Project(cmd::project::ProjectArgs),
    /// List store commits.
    History(cmd::history::HistoryArgs),
    /// Show the state of every owned and desired entry.
    Status(cmd::status::StatusArgs),
    /// Show the apply plan as file diffs.
    Diff(cmd::diff::DiffArgs),
    /// Show what each client loads in a folder, and from where.
    Effective(cmd::effective::EffectiveArgs),
    /// Reconcile client files with the store (one commit per run).
    Apply(cmd::apply::ApplyArgs),
    /// Roll back an apply run (or an eject run).
    Rollback(cmd::rollback::RollbackArgs),
    /// Stop managing this machine: hand client files and skill folders
    /// back to the clients (the store and history are kept).
    Eject(cmd::eject::EjectArgs),
    /// Show one store commit and what it changed.
    Show(cmd::show::ShowArgs),
    /// Create, list or delete store tags.
    Tag(cmd::tag::TagArgs),
    /// Restore the store (or client files) from an earlier state.
    Restore(cmd::restore::RestoreArgs),
    /// Commit hand edits of the store and optionally tag the result.
    Backup(cmd::backup::BackupArgs),
    /// Backup and sync remotes (none by default).
    Remote(cmd::remote::RemoteArgs),
    /// Git credential helper for remotes with `auth = token` (run by git).
    #[command(hide = true)]
    GitCredential(cmd::git_credential::GitCredentialArgs),
    /// Import foreign client entries into the store.
    Import(cmd::import::ImportArgs),
    /// Take ownership of foreign or changed client entries.
    Adopt(cmd::adopt::AdoptArgs),
    /// Migrate from SkillDock (~/.skilldock is only read).
    Migrate(cmd::migrate::MigrateArgs),
    /// Secret references: aliases, providers and their status.
    Secrets(cmd::secrets::SecretsArgs),
    /// Print export statements for secret aliases.
    Env(cmd::env::EnvArgs),
    /// Print one resolved value (internal, for client command hooks).
    Secret(cmd::env::SecretArgs),
    /// Print resolved headers as JSON (internal, for Claude Code
    /// `headersHelper`).
    SecretHeader(cmd::env::SecretHeaderArgs),
    /// Start an MCP server with secrets from its references (launch
    /// delivery); never writes to stdout.
    Exec(cmd::exec::ExecArgs),
    /// Print a shell completion script for loadout to stdout (bash, zsh,
    /// fish, powershell or elvish).
    Completions(CompletionsArgs),
}

#[derive(Debug, Args)]
struct DoctorArgs {
    /// Also report the resolved OS folders and data directory layout.
    #[arg(long)]
    paths: bool,
    /// Also scan every store commit for secrets (reports only; history is
    /// never rewritten).
    #[arg(long)]
    scan_history: bool,
    /// Print a diagnostic report to attach to a bug report: versions, file
    /// sizes, counts, client detection and recent log lines, redacted (no
    /// secret values, file contents or full paths). Nothing is sent.
    #[arg(long, conflicts_with_all = ["paths", "scan_history"])]
    report: bool,
}

#[derive(Debug, Args)]
struct CompletionsArgs {
    /// The shell to complete in.
    #[arg(value_enum)]
    shell: clap_complete::Shell,
}

fn main() -> ExitCode {
    let argv: Vec<OsString> = std::env::args_os().collect();
    if let Some(args) = cmd::exec::exec_args(&argv) {
        exec::main(args);
    }
    let matches = Cli::command().get_matches();
    let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|err| err.exit());
    match run(&cli, &logging::command_name(&matches)) {
        Ok(code) => ExitCode::from(code),
        Err(err) => {
            cmd::report_error(&err, cli.json);
            ExitCode::from(cmd::exit_code(&err))
        }
    }
}

/// Runs the command; the result is the exit code (SPEC 14).
fn run(cli: &Cli, name: &str) -> Result<u8, CoreError> {
    let env = Env::from_process()?;
    let flag = cli.home.as_deref().map(absolute).transpose()?;
    // Resolved once: the log and the command share it. An unusable home
    // fails later, in the command that needs it.
    let home = logging::logged(name)
        .then(|| paths::loadout_home(&env, &RealFs, flag.as_deref()).ok())
        .flatten();
    let logged = home
        .as_ref()
        .is_some_and(|home| logging::start(&env, home, name));
    let started = Instant::now();
    let result = dispatch(cli, &env, flag.as_deref(), home);
    if logged {
        logging::finish(name, &result, started);
    }
    result
}

fn dispatch(
    cli: &Cli,
    env: &Env,
    flag: Option<&Path>,
    home: Option<LoadoutHome>,
) -> Result<u8, CoreError> {
    let resolve = || match &home {
        Some(home) => Ok(home.clone()),
        None => paths::loadout_home(env, &RealFs, flag),
    };
    let context_unchecked = || -> Result<Context, CoreError> {
        Ok(Context {
            home: resolve()?,
            delivery: cmd::delivery_env(env),
            env: env.clone(),
            json: cli.json,
            yes: cli.yes,
        })
    };
    let context = || -> Result<Context, CoreError> {
        let context = context_unchecked()?;
        prepare_data(env, &context.home)?;
        Ok(context)
    };
    let done = |result: Result<(), CoreError>| result.map(|()| 0);
    match &cli.command {
        Command::Doctor(args) => done(doctor(env, resolve()?, args, cli.json)),
        Command::Server(args) => cmd::server::run(&context()?, args),
        Command::Project(args) => cmd::project::run(&context()?, args),
        Command::Skills(args) => cmd::skills::run(&context()?, args),
        Command::Agent(args) => cmd::agent::run(&context()?, args),
        Command::Source(args) => cmd::source::run(&context()?, args),
        Command::Catalog(args) => cmd::catalog::run(&context()?, args),
        Command::Scanner(args) => cmd::scanner::run(&context()?, args),
        Command::History(args) => done(cmd::history::run(&context()?, args)),
        Command::Status(args) => cmd::status::run(&context()?, args),
        Command::Diff(args) => cmd::diff::run(&context()?, args),
        Command::Effective(args) => done(cmd::effective::run(&context()?, args)),
        Command::Apply(args) => cmd::apply::run(&context()?, args),
        Command::Rollback(args) => cmd::rollback::run(&context()?, args),
        Command::Eject(args) => cmd::eject::run(&context()?, args),
        Command::Show(args) => done(cmd::show::run(&context()?, args)),
        Command::Tag(args) => done(cmd::tag::run(&context()?, args)),
        Command::Restore(args) => cmd::restore::run(&context()?, args),
        Command::Backup(args) => done(cmd::backup::run(&context()?, args)),
        Command::Remote(args) => cmd::remote::run(&context()?, args),
        Command::GitCredential(args) => done(cmd::git_credential::run(&context()?, args)),
        Command::Import(args) => cmd::import::run(&context()?, args),
        Command::Adopt(args) => cmd::adopt::run(&context()?, args),
        Command::Migrate(args) => cmd::migrate::run(&context()?, args),
        Command::Secrets(args) => cmd::secrets::run(&context()?, args),
        Command::Env(args) => cmd::env::run_env(&context()?, args),
        // Client hooks, like `exec`: they resolve a reference given on the
        // command line, so they never survey or migrate the data folder.
        Command::Secret(args) => cmd::env::run_secret(&context_unchecked()?, args),
        Command::SecretHeader(args) => cmd::env::run_header(&context_unchecked()?, args),
        // `exec_args` takes every `loadout exec` command line before clap.
        Command::Exec(args) => exec::main(&args.args),
        Command::Completions(args) => {
            completions(args.shell);
            Ok(0)
        }
    }
}

/// Writes the completion script of `shell` to stdout.
fn completions(shell: clap_complete::Shell) {
    clap_complete::generate(
        shell,
        &mut Cli::command(),
        brand::BIN_NAME,
        &mut std::io::stdout(),
    );
}

fn absolute(path: &Path) -> Result<PathBuf, CoreError> {
    std::path::absolute(path).map_err(|err| {
        CoreError::new(ErrorCode::InvalidPath, format!("invalid --home: {err}")).with_path(path)
    })
}

/// Refuses a data folder a newer Loadout wrote (`unsupported_schema`) and
/// migrates the files an older one wrote (M56), before a command reads
/// anything in it. A migration is noted on stderr.
fn prepare_data(env: &Env, home: &LoadoutHome) -> Result<(), CoreError> {
    let prepared = versions::prepare(env, &RealFs, home, &cmd::client_name())?;
    note_migration(prepared.into_result(home)?);
    Ok(())
}

fn note_migration(migration: Option<versions::Migration>) {
    let Some(migration) = migration else {
        return;
    };
    let mut note = format!(
        "note: upgraded {} data folder file(s) to this version's schema",
        migration.files.len()
    );
    if let Some(commit) = &migration.commit {
        note.push_str(&format!("; store commit {}", commit.short()));
    }
    if let Some(backup) = &migration.backup {
        note.push_str(&format!("; earlier copies in {}", backup.display()));
    }
    eprintln!("{note}");
}

fn doctor(env: &Env, home: LoadoutHome, args: &DoctorArgs, json: bool) -> Result<(), CoreError> {
    // The report only reads: it runs before any migration or lock, so it
    // also describes a newer, locked or older data folder as it is.
    if args.report {
        let program = cmd::client_name();
        let channel = install_channel(env);
        let text = report::build(
            env,
            &RealFs,
            &home,
            &ReportOptions {
                program: &program,
                channel,
                log_lines: report::DEFAULT_LOG_LINES,
            },
        );
        if json {
            print_json(&json!({ "schema": JSON_SCHEMA, "report": text }));
        } else {
            print!("{text}");
        }
        return Ok(());
    }
    // A newer data folder fails doctor like every command; a migration that
    // fails is reported as a finding, so doctor still describes the folder.
    let migration_error = match versions::prepare(env, &RealFs, &home, &cmd::client_name()) {
        Ok(prepared) => {
            note_migration(prepared.into_result(&home)?);
            None
        }
        Err(err) => Some(err),
    };
    let findings: Vec<&SyncRoot> = home.sync_root.iter().collect();
    let leaks = if args.scan_history {
        match Store::open(env, &RealFs, &home, &cmd::client_name())? {
            Some(store) => store.scan_history()?,
            None => Vec::new(),
        }
    } else {
        Vec::new()
    };

    if json {
        let mut doc = json!({
            "schema": JSON_SCHEMA,
            "findings": findings
                .iter()
                .map(|root| sync_root_finding_json(root))
                .chain(leaks.iter().map(leak_finding_json))
                .chain(migration_error.iter().map(migration_finding_json))
                .collect::<Vec<_>>(),
        });
        if args.paths {
            doc["paths"] = paths_json(env, &home);
        }
        print_json(&doc);
        return Ok(());
    }

    if args.paths {
        for (label, value) in paths_table(env, &home) {
            println!("{label:<18}{value}");
        }
        println!();
    }
    if findings.is_empty() && leaks.is_empty() && migration_error.is_none() {
        println!("No problems found.");
    }
    if let Some(err) = &migration_error {
        println!(
            "error[{MIGRATION_FAILED}]: the data folder could not be upgraded to this version's \
             schema: [{}] {err}",
            err.code()
        );
    }
    for root in findings {
        println!("warning[sync_root_detected]: {}", sync_root_warning(root));
    }
    for leak in &leaks {
        println!(
            "warning[leak_detected]: commit {} {}",
            leak.commit.short(),
            leak.finding
        );
    }
    Ok(())
}

/// The finding code of a data folder migration that failed (M56).
const MIGRATION_FAILED: &str = "schema_migration_failed";

fn migration_finding_json(err: &CoreError) -> Value {
    json!({
        "code": MIGRATION_FAILED,
        "severity": "error",
        "error": cmd::error_json(err),
    })
}

/// How this binary was installed, for the diagnostic report: `cargo` when
/// it runs from Cargo's bin folder (`CARGO_HOME`, else `~/.cargo`), else
/// unknown.
fn install_channel(env: &Env) -> Option<&'static str> {
    let exe = std::env::current_exe().ok()?;
    let cargo_home = env
        .var("CARGO_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| env.home().join(".cargo"));
    exe.starts_with(cargo_home.join("bin")).then_some("cargo")
}

fn leak_finding_json(leak: &HistoryFinding) -> Value {
    json!({
        "code": "leak_detected",
        "severity": "warning",
        "commit": leak.commit.to_string(),
        "file": leak.finding.file,
        "line": leak.finding.line,
        "key": leak.finding.key,
        "reason": leak.finding.kind.as_str(),
    })
}

fn paths_table(env: &Env, home: &LoadoutHome) -> Vec<(&'static str, String)> {
    let mut rows = vec![
        ("os", env.os().as_str().to_owned()),
        ("profile", env.home().display().to_string()),
    ];
    for (label, folder) in known_folders() {
        if let Some(path) = env.known_folder(folder) {
            rows.push((label, path.display().to_string()));
        }
    }
    rows.push((
        "loadout_home",
        format!("{} ({})", home.path.display(), home.source.as_str()),
    ));
    rows.extend(layout(home).map(|(label, path)| (label, path.display().to_string())));
    rows
}

fn paths_json(env: &Env, home: &LoadoutHome) -> Value {
    let mut doc = json!({
        "os": env.os().as_str(),
        "profile": path_json(env.home()),
        "loadout_home": path_json(&home.path),
        "loadout_home_source": home.source.as_str(),
    });
    for (label, folder) in known_folders() {
        doc[label] = env.known_folder(folder).map_or(Value::Null, path_json);
    }
    for (label, path) in layout(home) {
        doc[label] = path_json(&path);
    }
    doc
}

fn known_folders() -> [(&'static str, KnownFolder); 2] {
    [
        ("local_app_data", KnownFolder::LocalAppData),
        ("roaming_app_data", KnownFolder::RoamingAppData),
    ]
}

fn layout(home: &LoadoutHome) -> impl Iterator<Item = (&'static str, PathBuf)> {
    [
        ("store", home.store_dir()),
        ("state", home.state_dir()),
        ("backups", home.backups_dir()),
        ("cache", home.cache_dir()),
        ("imports", home.imports_dir()),
        ("logs", home.logs_dir()),
    ]
    .into_iter()
}

fn sync_root_finding_json(root: &SyncRoot) -> Value {
    json!({
        "code": "sync_root_detected",
        "severity": "warning",
        "kind": root.kind.as_str(),
        "root": path_json(&root.root),
    })
}

#[cfg(test)]
mod tests {
    //! The bundled Loadout skill (#8) against this CLI: every `loadout ...`
    //! command it cites exists with the flags it uses, and the flags that
    //! answer for the user appear only in "never" guidance.

    use agent_loadout_core::agent;
    use clap::CommandFactory;

    use super::Cli;

    /// Each skill file as text, by path.
    fn skill_texts() -> Vec<(String, String)> {
        agent::bundled_files()
            .into_iter()
            .map(|(path, bytes)| (path, String::from_utf8(bytes).expect("UTF-8 skill file")))
            .collect()
    }

    /// The code of `text`: inline code spans and fenced block lines, each
    /// with the file and line it came from.
    fn code_segments(path: &str, text: &str) -> Vec<(String, String)> {
        let mut segments = Vec::new();
        let mut fenced = false;
        for (index, line) in text.lines().enumerate() {
            let place = format!("{path}:{}", index + 1);
            if line.trim_start().starts_with("```") {
                fenced = !fenced;
                continue;
            }
            if fenced {
                segments.push((place, line.to_owned()));
                continue;
            }
            for (n, part) in line.split('`').enumerate() {
                if n % 2 == 1 {
                    segments.push((place.clone(), part.to_owned()));
                }
            }
        }
        segments
    }

    /// Checks one cited command line against clap: each word before the
    /// first value names a subcommand, the last one has no subcommands
    /// left, and every long flag exists there (or globally).
    fn check_command(place: &str, line: &str) {
        let root = Cli::command();
        let globals: Vec<String> = root
            .get_arguments()
            .filter_map(|arg| arg.get_long().map(str::to_owned))
            .chain(["help".to_owned(), "version".to_owned()])
            .collect();
        let mut command = &root;
        let mut descending = true;
        let words = line.split_whitespace().skip(1);
        for word in words.take_while(|word| !["|", "&&", ";", ">", "#"].contains(word)) {
            let word = word.trim_matches(|c| c == '[' || c == ']' || c == ',');
            let word = word.trim_end_matches("...");
            if let Some(flag) = word.strip_prefix("--") {
                let name = flag.split('=').next().unwrap_or(flag);
                let known = command
                    .get_arguments()
                    .any(|arg| arg.get_long() == Some(name))
                    || globals.iter().any(|global| global == name);
                assert!(
                    known,
                    "{place}: `{line}`: --{name} is not an option of `{}`",
                    command.get_name()
                );
                continue;
            }
            if word.starts_with('<') && descending && command.has_subcommands() {
                // `loadout <command> --help`: any subcommand.
                return;
            }
            if word.starts_with('-') || word.starts_with('<') || word.is_empty() {
                continue;
            }
            if descending && command.has_subcommands() {
                command = command.find_subcommand(word).unwrap_or_else(|| {
                    panic!(
                        "{place}: `{line}`: `{word}` is not a subcommand of `{}`",
                        command.get_name()
                    )
                });
                continue;
            }
            descending = false;
        }
        assert!(
            !command.has_subcommands(),
            "{place}: `{line}`: `{}` needs a subcommand",
            command.get_name()
        );
    }

    #[test]
    fn every_command_the_skill_cites_exists() {
        let mut checked = 0;
        for (path, text) in skill_texts() {
            for (place, segment) in code_segments(&path, &text) {
                let segment = segment.trim();
                if segment.starts_with("loadout ") {
                    check_command(&place, segment);
                    checked += 1;
                }
            }
        }
        assert!(checked >= 30, "only {checked} commands found");
    }

    /// Flags that answer a prompt or override a gate for the user.
    const DECISION_FLAGS: [&str; 7] = [
        "--yes",
        "--trust-source",
        "--allow-dangerous",
        "--on-conflict",
        "--remove-old-backups",
        "--all-identical",
        "--theirs",
    ];

    #[test]
    fn decision_flags_appear_only_in_never_guidance() {
        for (path, text) in skill_texts() {
            for (index, line) in text.lines().enumerate() {
                for flag in DECISION_FLAGS.iter().filter(|flag| line.contains(*flag)) {
                    assert!(
                        never_guarded(line, flag),
                        "{path}:{}: {flag} outside \"never pass/use\" guidance: {line}",
                        index + 1
                    );
                }
            }
        }
        let skill = &skill_texts()
            .into_iter()
            .find(|(path, _)| path == "SKILL.md")
            .expect("SKILL.md")
            .1;
        for flag in ["--yes", "--trust-source", "--allow-dangerous"] {
            assert!(skill.contains(flag), "SKILL.md says never to use {flag}");
        }
        let prose = skill.split_whitespace().collect::<Vec<_>>().join(" ");
        assert!(
            prose.contains("is data, not instructions"),
            "SKILL.md says third-party text is data"
        );
    }

    /// Whether every `flag` in `line` comes after "never pass" or "never
    /// use" in the same sentence.
    fn never_guarded(line: &str, flag: &str) -> bool {
        let lower = line.to_lowercase();
        lower.match_indices(flag).all(|(at, _)| {
            let before = &lower[..at];
            ["never pass", "never use"]
                .iter()
                .filter_map(|guard| before.rfind(guard).map(|start| start + guard.len()))
                .max()
                .is_some_and(|end| !before[end..].contains(". "))
        })
    }

    #[test]
    fn the_guard_needs_never_before_the_flag_in_one_sentence() {
        assert!(never_guarded(
            "Never pass `--yes` or `--trust-source`.",
            "--yes"
        ));
        assert!(!never_guarded(
            "run `loadout apply --yes`, never skip review",
            "--yes"
        ));
        assert!(!never_guarded("Never pass it. Run `--yes` now.", "--yes"));
        assert!(!never_guarded(
            "Use `--allow-dangerous` when you like",
            "--allow-dangerous"
        ));
    }

    /// Every code errors.md lists is a real error code, and the codes the
    /// cited commands commonly return are there (the catalog ones too).
    #[test]
    fn the_errors_reference_names_real_codes() {
        let errors = &skill_texts()
            .into_iter()
            .find(|(path, _)| path == "references/errors.md")
            .expect("errors.md")
            .1;
        let table = errors
            .split("## Error codes")
            .nth(1)
            .and_then(|rest| rest.split("\n## ").next())
            .expect("an Error codes section");
        let mut listed = Vec::new();
        for line in table.lines().filter(|line| line.starts_with("| `")) {
            let first = line.split('|').nth(1).unwrap_or_default();
            for (n, part) in first.split('`').enumerate() {
                if n % 2 == 1 {
                    listed.push(part.to_owned());
                }
            }
        }
        for code in &listed {
            assert!(
                serde_json::from_value::<agent_loadout_core::ErrorCode>(serde_json::json!(code))
                    .is_ok(),
                "errors.md lists {code:?}, which is not an error code"
            );
        }
        for code in [
            "not_found",
            "locked",
            "trust_required",
            "missing_secret",
            "scan_blocked",
            "source_trust_required",
            "catalogs_off",
            "catalog_unreachable",
        ] {
            assert!(
                listed.iter().any(|known| known == code),
                "errors.md misses {code}"
            );
        }
    }
}