surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! The diagnostic report (`surject doctor --report`, the app's Copy
//! diagnostic report): what a bug report needs about this installation,
//! as Markdown. Names, counts, sizes and yes/no only: no file contents, no
//! secret or environment values, no URLs of remotes, and folders only as
//! `~` or `<SURJECTION_HOME>`. The whole text goes through the [`Redactor`].

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::Path;

use super::log::{self, LOG_FILE};
use super::redact::Redactor;
use crate::adapters::ADAPTERS;
use crate::adapters::detect::{self, NoRegistry};
use crate::apply::placeholder_path;
use crate::catalog;
use crate::env::Env;
use crate::error::CoreError;
use crate::fs::Fs;
use crate::layering::projects::this_overlay;
use crate::paths::SurjectionHome;
use crate::remote::config::RemotesFile;
use crate::scan::external::skillspector;
use crate::store::{Store, utc_datetime};
use crate::versions::{self, Registry};

/// Log lines the report ends with by default.
pub const DEFAULT_LOG_LINES: usize = 50;

/// Who asks for the report.
#[derive(Debug, Clone, Copy)]
pub struct ReportOptions<'a> {
    /// `surject-cli/0.9.0`, `surjection-app/0.9.0`.
    pub program: &'a str,
    /// How this build was installed (`nsis`, `appimage`, `cargo`), when
    /// known.
    pub channel: Option<&'a str>,
    /// Log lines at the end.
    pub log_lines: usize,
}

/// Files inside `SURJECTION_HOME` the report lists with their size.
const FILES: [&str; 10] = [
    "store/loadout.toml",
    "state/machine.toml",
    "state/ledger.json",
    "state/ledger.key",
    "state/remotes.toml",
    "state/trust.json",
    "state/scan-rules.toml",
    "state/local-settings.toml",
    "state/unmanaged-seen.json",
    "logs/surjection.log",
];

/// Folders inside `SURJECTION_HOME` the report lists with their entry count.
const FOLDERS: [&str; 12] = [
    "store",
    "store/servers",
    "store/skills",
    "state",
    "state/journal",
    "state/applies",
    "state/merge",
    "backups",
    "cache",
    "tools",
    "imports",
    "logs",
];

/// Builds the report. Never fails: a part that cannot be read says so with
/// its error code.
pub fn build(env: &Env, fs: &dyn Fs, home: &SurjectionHome, options: &ReportOptions<'_>) -> String {
    let mut out = String::new();
    let _ = write_report(&mut out, env, fs, home, options);
    Redactor::new(env, &home.path).redact(&out)
}

fn write_report(
    out: &mut String,
    env: &Env,
    fs: &dyn Fs,
    home: &SurjectionHome,
    options: &ReportOptions<'_>,
) -> std::fmt::Result {
    writeln!(out, "# Surjection diagnostic report")?;
    writeln!(out)?;
    writeln!(out, "Generated {}.", utc_datetime(env.now()))?;
    writeln!(
        out,
        "Contains versions, file names, sizes, counts, client detection and recent log lines. \
         No secret values, file contents, remote URLs or full paths. Nothing was sent anywhere."
    )?;

    writeln!(out, "\n## Version\n")?;
    writeln!(out, "- Program: {}", options.program)?;
    writeln!(
        out,
        "- OS: {} ({})",
        env.os().as_str(),
        std::env::consts::ARCH
    )?;
    writeln!(
        out,
        "- Install channel: {}",
        options.channel.unwrap_or("unknown")
    )?;

    writeln!(out, "\n## Data folder\n")?;
    writeln!(
        out,
        "- Location: {} (set by: {})",
        placeholder_path(env, &home.path, None),
        home.source.as_str()
    )?;
    writeln!(
        out,
        "- Inside a sync folder: {}",
        home.sync_root
            .as_ref()
            .map_or("no", |root| root.kind.as_str())
    )?;
    if !fs.is_dir(&home.path) {
        writeln!(out, "- Not created yet.")?;
    } else {
        for folder in FOLDERS {
            let path = home.path.join(folder);
            match fs.read_dir(&path) {
                Ok(entries) => writeln!(out, "- `{folder}/`: {} entries", entries.len())?,
                Err(_) => writeln!(out, "- `{folder}/`: absent")?,
            }
        }
        for file in FILES {
            let path = home.path.join(file);
            if fs.is_regular_file(&path) {
                let size = fs.file_size(&path).unwrap_or(0);
                writeln!(out, "- `{file}`: {}", human_size(size))?;
            } else {
                writeln!(out, "- `{file}`: absent")?;
            }
        }
        for n in 1..=log::Rotation::DEFAULT.keep {
            let file = format!("logs/{LOG_FILE}.{n}");
            let path = home.path.join(&file);
            if fs.is_regular_file(&path) {
                let size = fs.file_size(&path).unwrap_or(0);
                writeln!(out, "- `{file}`: {}", human_size(size))?;
            }
        }
        match newer_file(fs, home) {
            Ok(None) => writeln!(out, "- Written by a newer Surjection: no")?,
            Ok(Some((file, found, supported))) => writeln!(
                out,
                "- Written by a newer Surjection: yes (`{file}` has schema {found}; this build reads up to {supported})"
            )?,
            Err(err) => writeln!(
                out,
                "- Written by a newer Surjection: {}",
                unavailable(&err)
            )?,
        }
    }

    let store = Store::open(env, fs, home, options.program);
    match &store {
        Ok(Some(store)) => {
            writeln!(out, "- Store schema: {}", store.identity().schema)?;
            match store.commit_count() {
                Ok(count) => writeln!(out, "- Store commits: {count}")?,
                Err(err) => writeln!(out, "- Store commits: {}", unavailable(&err))?,
            }
        }
        Ok(None) => writeln!(out, "- Store: not created yet")?,
        Err(err) => writeln!(out, "- Store: {}", unavailable(err))?,
    }

    writeln!(out, "\n## Clients\n")?;
    write_clients(out, env, fs)?;

    writeln!(out, "\n## Counts\n")?;
    write_counts(out, fs, home, &store)?;

    writeln!(out, "\n## Scanners\n")?;
    writeln!(out, "- Built-in scanner: on")?;
    match skillspector::status(env, fs, home) {
        Ok(status) => {
            writeln!(
                out,
                "- SkillSpector: {}, {}{}",
                if status.enabled { "on" } else { "off" },
                status.availability.as_str(),
                status
                    .availability
                    .runtime()
                    .map(|runtime| format!(", runtime {}", runtime.kind.as_str()))
                    .unwrap_or_default()
            )?;
            if let Some(version) = &status.private_uv {
                writeln!(out, "- Private uv: {version}")?;
            }
        }
        Err(err) => writeln!(out, "- SkillSpector: {}", unavailable(&err))?,
    }

    writeln!(out, "\n## Online catalogs\n")?;
    match catalog::online(fs, home) {
        Ok(setting) if !setting.answered => writeln!(out, "- Not answered yet (off)")?,
        Ok(setting) => writeln!(out, "- {}", if setting.on { "On" } else { "Off" })?,
        Err(err) => writeln!(out, "- {}", unavailable(&err))?,
    }

    let lines = log::tail(home, options.log_lines.max(200));
    writeln!(out, "\n## Recent error codes\n")?;
    let codes = log::error_codes(&lines);
    if codes.is_empty() {
        writeln!(out, "- None in the log")?;
    }
    for (code, count) in codes {
        writeln!(out, "- `{code}` ({count}x)")?;
    }

    writeln!(out, "\n## Recent log lines\n")?;
    let skip = lines.len().saturating_sub(options.log_lines);
    if lines.len() == skip {
        writeln!(out, "No log lines.")?;
    } else {
        writeln!(out, "```")?;
        for line in &lines[skip..] {
            writeln!(out, "{line}")?;
        }
        writeln!(out, "```")?;
    }
    Ok(())
}

/// Detected clients and those with a config file, one row each; the
/// others are only counted.
fn write_clients(out: &mut String, env: &Env, fs: &dyn Fs) -> std::fmt::Result {
    writeln!(out, "| Client | Detected | Config file |")?;
    writeln!(out, "|---|---|---|")?;
    let mut others = 0;
    for spec in ADAPTERS {
        let detected = detect::detect(spec, env, fs, &NoRegistry).detected();
        let file = spec.mcp.as_ref().and_then(|mcp| {
            mcp.user
                .iter()
                .filter_map(|location| location.resolve(env, None))
                .find(|path| fs.is_regular_file(path))
        });
        if !detected && file.is_none() {
            others += 1;
            continue;
        }
        let file = file.map_or_else(
            || "absent".to_owned(),
            |path| format!("`{}`", placeholder_path(env, &path, None)),
        );
        writeln!(
            out,
            "| {} | {} | {file} |",
            spec.id,
            if detected { "yes" } else { "no" }
        )?;
    }
    writeln!(
        out,
        "\n{others} other clients: not detected, no config file."
    )
}

fn write_counts(
    out: &mut String,
    fs: &dyn Fs,
    home: &SurjectionHome,
    store: &Result<Option<Store<'_>>, CoreError>,
) -> std::fmt::Result {
    match store {
        Ok(Some(store)) => {
            match store.servers() {
                Ok(servers) => writeln!(out, "- Servers: {}", servers.len())?,
                Err(err) => writeln!(out, "- Servers: {}", unavailable(&err))?,
            }
            writeln!(
                out,
                "- Skills: {}",
                count_dirs(fs, &home.store_dir().join("skills"))
            )?;
            match this_overlay(store, fs, &home.state_dir()) {
                Ok(overlay) => writeln!(
                    out,
                    "- Projects on this machine: {}",
                    overlay
                        .and_then(|overlay| overlay.projects)
                        .map_or(0, |projects| projects.len())
                )?,
                Err(err) => writeln!(out, "- Projects on this machine: {}", unavailable(&err))?,
            }
        }
        _ => writeln!(
            out,
            "- Servers: 0\n- Skills: 0\n- Projects on this machine: 0"
        )?,
    }
    match RemotesFile::load(fs, &home.state_dir()) {
        Ok(file) if file.remotes.is_empty() => writeln!(out, "- Remotes: none")?,
        Ok(file) => {
            let mut kinds: BTreeMap<&str, usize> = BTreeMap::new();
            for remote in &file.remotes {
                *kinds.entry(remote.kind.as_str()).or_default() += 1;
            }
            let kinds: Vec<String> = kinds
                .into_iter()
                .map(|(kind, count)| format!("{kind} {count}"))
                .collect();
            writeln!(out, "- Remotes: {}", kinds.join(", "))?;
        }
        Err(err) => writeln!(out, "- Remotes: {}", unavailable(&err))?,
    }
    Ok(())
}

/// The first data file a newer Surjection wrote, with its schema and the one
/// this build reads (read-only, [`versions::survey`]).
fn newer_file(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<(String, i64, i64)>, CoreError> {
    let registry = Registry::builtin();
    Ok(versions::survey(fs, home, &registry)?
        .into_iter()
        .find_map(|found| {
            let supported = registry.kind(found.kind)?.current();
            (found.version > supported).then(|| (found.file(), found.version, supported))
        }))
}

fn count_dirs(fs: &dyn Fs, dir: &Path) -> usize {
    fs.read_dir(dir)
        .map(|entries| entries.iter().filter(|path| fs.is_dir(path)).count())
        .unwrap_or(0)
}

fn unavailable(err: &CoreError) -> String {
    format!("unavailable ({})", err.code().as_str())
}

/// `512 B`, `1.5 KiB`, `2.0 MiB`.
fn human_size(bytes: u64) -> String {
    const KIB: u64 = 1024;
    if bytes < KIB {
        format!("{bytes} B")
    } else if bytes < KIB * KIB {
        format!("{:.1} KiB", bytes as f64 / KIB as f64)
    } else {
        format!("{:.1} MiB", bytes as f64 / (KIB * KIB) as f64)
    }
}