stikk 0.13.0

A user-facing history browser and workbench for the prikk version control system.
//! The `stikk` launcher (design `stikk-04` MOD-08, external design CL-01…08).
//!
//! stikk is a history browser and workbench for the prikk version control system. The launcher's job
//! is small: parse the launch contract, run the headless utilities, and open a repository. Opening one
//! on a terminal launches the interactive **TUI** (`stikk-tui`; `ratatui`/`crossterm`, RFC 001) — the
//! primary surface, not a future increment. A GUI frontend remains a later Program-Design decision. Off
//! a TTY (piped, redirected, CI) the launcher instead prints a one-shot orientation — the **non-TTY
//! fallback** (design `CL-06`), not the main path — so scripts and pipelines get a stable, parseable
//! summary instead of raw terminal control sequences.
//!
//! Exit codes: `0` success (headless utilities and a completed interactive session alike); `1` a
//! runtime error (e.g. an unopenable repository, an I/O failure); `2` a usage error (an unknown option
//! or malformed subcommand, detected before any repository work); `3` `config check` found a notice
//! (non-blocking warnings in the config file). External design `CL-05` additionally defines an exit `4`
//! ("environment unsuitable", e.g. no TTY) that this launcher does not use — opening off a TTY falls
//! back to the one-shot print (`CL-06`) instead of refusing. That gap between the design and the code is
//! flagged here, not fixed; see the 0.2.0 release-prep review request.

#![forbid(unsafe_code)]

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use stikk_core::orient;
use stikk_prikk::CliBackend;
use stikk_state::{Config, RepositoryHandle, paths};

const USAGE: &str = "\
stikk — a history browser and workbench for the prikk version control system

USAGE:
    stikk [PATH]            open the repository at PATH (or discovered from the current directory)
    stikk config check [F]  validate the stikk config file (F, or the default location)
    stikk config path       print where stikk's config and state live
    stikk --version         print the stikk version
    stikk --help            print this help

Notes:
    Opening a repository on a terminal launches the interactive TUI; off a TTY (piped, redirected, CI)
    stikk prints a one-shot orientation instead. stikk drives prikk through its public CLI; set
    STIKK_PRIKK_BIN to point at a specific prikk build. stikk reads PRIKK_*_SEED presence only, never
    their values.";

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.split_first() {
        None => run_open(None),
        Some((cmd, rest)) => match cmd.as_str() {
            "--version" | "-V" => {
                println!("stikk {}", env!("CARGO_PKG_VERSION"));
                ExitCode::SUCCESS
            }
            "--help" | "-h" | "help" => {
                println!("{USAGE}");
                ExitCode::SUCCESS
            }
            "config" => run_config(rest),
            other if other.starts_with('-') => {
                eprintln!("error: unknown option: {other}\n\n{USAGE}");
                ExitCode::from(2)
            }
            path => run_open(Some(path)),
        },
    }
}

/// `stikk config check [file]` and `stikk config path`.
fn run_config(rest: &[String]) -> ExitCode {
    match rest.split_first() {
        Some((sub, tail)) if sub == "check" => {
            let file = match tail.first() {
                Some(explicit) => PathBuf::from(explicit),
                None => match paths::config_file() {
                    Ok(path) => path,
                    Err(err) => return fail(&err.to_string()),
                },
            };
            config_check(&file)
        }
        Some((sub, _)) if sub == "path" => config_path(),
        _ => {
            eprintln!("error: expected `config check [file]` or `config path`\n\n{USAGE}");
            ExitCode::from(2)
        }
    }
}

fn config_check(file: &Path) -> ExitCode {
    let text = match std::fs::read_to_string(file) {
        Ok(text) => text,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            // A missing config is not an error: stikk runs on defaults (external design CF-02).
            println!("no config at {} — stikk uses defaults", file.display());
            return ExitCode::SUCCESS;
        }
        Err(err) => return fail(&format!("could not read {}: {err}", file.display())),
    };
    let config = Config::parse(&text);
    if config.warnings.is_empty() {
        println!("config at {} is valid", file.display());
        ExitCode::SUCCESS
    } else {
        // Warnings do not block launch (unknown keys are preserved), but `config check` reports them
        // and exits non-zero so a CI gate can catch a typo (external design CL-08, exit 3).
        println!(
            "config at {} has {} notice(s):",
            file.display(),
            config.warnings.len()
        );
        for warning in &config.warnings {
            println!("  - {warning}");
        }
        ExitCode::from(3)
    }
}

fn config_path() -> ExitCode {
    match (paths::config_file(), paths::state_dir()) {
        (Ok(config), Ok(state)) => {
            println!("config: {}", config.display());
            println!("state:  {}", state.display());
            ExitCode::SUCCESS
        }
        (Err(err), _) | (_, Err(err)) => fail(&err.to_string()),
    }
}

/// Open a repository. On a TTY, launch the interactive TUI (design CL-06); otherwise print a one-shot
/// orientation, which stays the machine-friendly path for pipes and CI.
fn run_open(path: Option<&str>) -> ExitCode {
    let start = match path {
        Some(p) => PathBuf::from(p),
        None => match std::env::current_dir() {
            Ok(dir) => dir,
            Err(err) => return fail(&format!("could not read the current directory: {err}")),
        },
    };
    let handle = match open_handle(&start) {
        Ok(handle) => handle,
        Err(err) => return fail(&err.to_string()),
    };
    let backend = CliBackend::new();

    if stikk_tui::stdout_is_tty() {
        let config = load_config();
        return match stikk_tui::run(handle.root(), &backend, &config) {
            Ok(()) => ExitCode::SUCCESS,
            Err(err) => fail(&err.to_string()),
        };
    }

    // Non-TTY (piped, redirected, CI): the one-shot orientation.
    match orient(&backend, handle.root()) {
        Ok(view) => {
            print_orientation(handle.root(), &view);
            ExitCode::SUCCESS
        }
        Err(err) => fail(&err.to_string()),
    }
}

/// Load the stikk config, falling back to defaults on any problem (design CF-02: a bad config never
/// blocks launch).
fn load_config() -> Config {
    let Ok(path) = paths::config_file() else {
        return Config::default();
    };
    match std::fs::read_to_string(&path) {
        Ok(text) => Config::parse(&text),
        Err(_) => Config::default(),
    }
}

/// If the path is a repository root use it directly; otherwise discover upward.
fn open_handle(start: &Path) -> stikk_model::Result<RepositoryHandle> {
    match RepositoryHandle::open(start) {
        Ok(handle) => Ok(handle),
        Err(_) => RepositoryHandle::discover(start),
    }
}

fn print_orientation(root: &Path, view: &orient::OrientationView) {
    println!("stikk — orientation");
    // **The same two rules as the TUI** (RFC 036 decision 5; RFC 009's M1 is why stdout counts as a
    // terminal here). The root is a local filesystem path, so it may legitimately be non-ASCII —
    // visible non-ASCII stays as itself, and only what does not show as itself is escaped.
    println!(
        "  repository:  {}",
        stikk_tui::text::identifier(&root.display().to_string())
    );
    let support = support_line(
        view.prikk_supported,
        view.prikk_validated,
        &view.validated_through,
    );
    // prikk's own version line, as prose: prikk's sentence, not an identifier.
    println!(
        "  prikk:       {} ({support})",
        stikk_tui::text::inert(&view.prikk_version)
    );
    println!("  capability:  {}", view.capability.name());
    println!(
        "  signing:     author {} · maintainer {}{}",
        role_readiness_word(view.readiness.author),
        role_readiness_word(view.readiness.maintainer),
        if view.readiness.read_only {
            " · read-only"
        } else {
            ""
        }
    );
    println!(
        "{}",
        queued_line(view.queued_patches, view.queued_target.as_deref())
    );
    if view.trailing_partial_wal_bytes != 0 {
        println!(
            "  warning:     {} trailing partial WAL byte(s) — an interrupted commit left a torn tail",
            view.trailing_partial_wal_bytes
        );
    }
    match &view.main_ref_state {
        Some(id) => println!("  heads/main:  {}", stikk_tui::text::identifier(id)),
        None => println!("  heads/main:  <unpublished>"),
    }
    println!(
        "\nRunning without a terminal, so this is the one-shot orientation; open stikk in a \
         terminal for the interactive view."
    );
}

/// Format the `queued:` line. `target` is repository-sourced (prikk's active-ref metadata) and is a
/// ref name, so it is rendered as an **identifier** (RFC 036 decision 3) before it reaches stdout:
/// this one-shot path has no raw terminal mode to rely on, but the output can still land on a real
/// terminal (piped through `less`, or a redirected file `cat`-ed later), so the same rules apply as
/// in the TUI (review finding M1, RFC 009).
fn queued_line(patches: u64, target: Option<&str>) -> String {
    match target {
        Some(target) => format!(
            "  queued:      {patches} · targeting {}",
            stikk_tui::text::identifier(target)
        ),
        None => format!("  queued:      {patches}"),
    }
}

/// Format the `prikk:` line's support/validation clause (design NFR-R03; RFC 009 decisions 6–7).
/// `validated_through` **must** come from [`stikk_prikk::validated_ceiling_display`] — never a literal
/// here: this exact sentence in the TUI's own Orientation view drifted silently for a release (still
/// said "0.30" after RFC 012 F-e raised the real ceiling to 31, caught only in RFC 015) because it was
/// hardcoded instead of reading this field. The launcher is the same user-facing surface and carried an
/// independent copy of the identical bug (RFC 015 C1) — extracted here so a sentinel can test it.
fn support_line(supported: bool, validated: bool, validated_through: &str) -> String {
    if !supported {
        "OUTSIDE stikk's validated range — read-only".to_string()
    } else if !validated {
        format!(
            "validated through {validated_through} — this prikk is newer; its output shapes have not \
             been checked"
        )
    } else {
        "supported".to_string()
    }
}

/// One role's word, matching the TUI Orientation view's wording exactly (RFC 026 §3).
///
/// **The two unknowns say different things**, here as there: `Unknown` is "stikk cannot check this",
/// `Unverifiable` is "stikk cannot see whether there is anything to check". Neither says bare "ready"
/// — `C-T2c′`. Kept in step with `view::orientation::role_words` by hand; they are two renderers of
/// one vocabulary, and a divergence would be the kind this project keeps finding.
fn role_readiness_word(readiness: stikk_model::RoleReadiness) -> &'static str {
    use stikk_model::{Binding, RoleReadiness};
    match readiness {
        RoleReadiness::NotReady | RoleReadiness::Known(Binding::Absent) => "not ready",
        // Matches `view::orientation::role_words`; the author/maintainer split is there too.
        RoleReadiness::Unknown => "present, unverified or adoption unknown",
        RoleReadiness::Unverifiable => "unknown",
        RoleReadiness::Known(Binding::Matches) => "ready",
        RoleReadiness::Known(Binding::Unrecorded) => "ready, not yet bound",
        RoleReadiness::Known(Binding::NotAdopted) => "present, not adopted by this repository",
        RoleReadiness::Known(Binding::Mismatch) => {
            "present, does not match this repository's record"
        }
    }
}

fn fail(message: &str) -> ExitCode {
    eprintln!("error: {message}");
    ExitCode::from(1)
}

#[cfg(test)]
mod tests;