agent-loadout 1.0.0

Loadout CLI: manage MCP servers, skills and secret references for AI coding clients
//! The CLI's lines in `<LOADOUT_HOME>/logs/loadout.log` (SPEC 4.5, M55):
//! `command.start` and `command.end` with the subcommand path, the outcome,
//! the error code and the duration. Never arguments: they may hold search
//! words, paths or values.

use std::time::Instant;

use agent_loadout_core::diagnostics::log::{self, Logger};
use agent_loadout_core::paths::LoadoutHome;
use agent_loadout_core::{CoreError, Env};
use clap::ArgMatches;

/// Commands that write no log lines: `completions` prints a script, and
/// `exec` is taken before clap.
const QUIET: [&str; 2] = ["completions", "exec"];

/// The subcommand path of `matches` (`skills add`).
pub fn command_name(matches: &ArgMatches) -> String {
    let mut words = Vec::new();
    let mut current = matches;
    while let Some((name, sub)) = current.subcommand() {
        words.push(name);
        current = sub;
    }
    words.join(" ")
}

/// Whether the command `name` writes log lines.
pub fn logged(name: &str) -> bool {
    let first = name.split(' ').next().unwrap_or_default();
    !QUIET.contains(&first)
}

/// Installs the log of `home` and writes `command.start`; false when
/// `LOADOUT_LOG` turns the log off.
pub fn start(env: &Env, home: &LoadoutHome, name: &str) -> bool {
    let Some(logger) = Logger::for_home(env, home, "cli") else {
        return false;
    };
    log::install(logger);
    log::event("command.start", &[("name", &name)]);
    true
}

/// Writes `command.end` and waits until every queued line is on disk: the
/// process exits right after.
pub fn finish(name: &str, result: &Result<u8, CoreError>, started: Instant) {
    log::finished(
        "command.end",
        name,
        result.as_ref().err().map(CoreError::code),
        started,
    );
    log::uninstall();
}