surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! Store history (SPEC 9.3, log only): commits with op, entities, scope,
//! machine and time, filtered by entity or scope; and the leak scan of the
//! whole history (SPEC 11.8, `surject doctor --scan-history`).

use std::collections::HashSet;
use std::path::Path;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use git2::{Commit, ObjectType, Oid, Sort, Tree, TreeWalkMode, TreeWalkResult};

use crate::error::CoreError;
use crate::secrets::scanner::{ALLOWLIST_FILE, Allowlist, LeakFinding, scan_text};
use crate::store::trailers::{Scope, Trailers, message_summary};
use crate::store::{CommitId, Store, git_error, utc_datetime};

/// A possible leak in a past commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryFinding {
    /// The newest commit holding the flagged file version (or message).
    pub commit: CommitId,
    pub finding: LeakFinding,
}

/// One store commit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogEntry {
    pub id: CommitId,
    /// Commit time.
    pub time: SystemTime,
    pub author_name: String,
    pub author_email: String,
    /// The first line of the message.
    pub summary: String,
    pub trailers: Trailers,
}

impl LogEntry {
    /// [`Self::time`] as RFC 3339 in UTC (`2026-01-01T00:00:00Z`).
    pub fn time_rfc3339(&self) -> String {
        utc_datetime(self.time).to_string()
    }
}

/// Which commits [`Store::log`] returns. The default is every commit.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LogFilter {
    /// Commits naming this entity in a `Surjection-Entity` trailer, or changing
    /// one of its files (so hand-made commits are found too).
    pub entity: Option<String>,
    /// Commits whose `Surjection-Scope` is this scope.
    pub scope: Option<Scope>,
    /// At most this many commits, newest first.
    pub limit: Option<usize>,
    /// Only commits after this one in the walk (older than it): the cursor
    /// of a paged list, the last commit of the previous page. A commit the
    /// walk never reaches gives no commits.
    pub before: Option<CommitId>,
}

/// Store-relative files and directories holding an entity
/// (`server/github` is `servers/github.toml`). Unknown kinds hold none.
pub fn entity_paths(entity: &str) -> Vec<String> {
    match entity.split_once('/') {
        Some(("server", id)) => vec![format!("servers/{id}.toml")],
        Some(("skill", id)) => vec![format!("skills/{id}"), format!("skill-meta/{id}.toml")],
        Some(("project", id)) => vec![format!("projects/{id}")],
        Some(("machine", id)) => vec![
            format!("machines/{id}.toml"),
            format!("machines/{id}.applied.toml"),
        ],
        None if matches!(entity, "secrets" | "clients" | "settings" | "sources") => {
            vec![format!("{entity}.toml")]
        }
        _ => Vec::new(),
    }
    .into_iter()
    .filter(|path| !path.split('/').any(|part| part.is_empty() || part == ".."))
    .collect()
}

impl Store<'_> {
    /// How many commits HEAD reaches; walks ids only, reads no commit.
    pub fn commit_count(&self) -> Result<usize, CoreError> {
        let mut walk = self.repo.revwalk().map_err(git_error)?;
        walk.push_head().map_err(git_error)?;
        let mut count = 0;
        for oid in walk {
            oid.map_err(git_error)?;
            count += 1;
        }
        Ok(count)
    }

    /// Commits reachable from HEAD, newest first, matching `filter`.
    pub fn log(&self, filter: &LogFilter) -> Result<Vec<LogEntry>, CoreError> {
        let mut walk = self.repo.revwalk().map_err(git_error)?;
        walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
            .map_err(git_error)?;
        walk.push_head().map_err(git_error)?;
        let paths = filter
            .entity
            .as_deref()
            .map(entity_paths)
            .unwrap_or_default();

        let mut entries = Vec::new();
        let mut past_cursor = filter.before.is_none();
        for oid in walk {
            if filter.limit.is_some_and(|limit| entries.len() >= limit) {
                break;
            }
            let oid = oid.map_err(git_error)?;
            if !past_cursor {
                // Skipped commits are not read, only compared by id.
                past_cursor = filter.before.as_ref() == Some(&CommitId::from_oid(oid));
                continue;
            }
            let commit = self.repo.find_commit(oid).map_err(git_error)?;
            let message = String::from_utf8_lossy(commit.message_bytes());
            let trailers = Trailers::parse(&message);
            if filter
                .scope
                .as_ref()
                .is_some_and(|scope| trailers.scope.as_ref() != Some(scope))
            {
                continue;
            }
            if let Some(entity) = &filter.entity
                && !trailers.entities.contains(entity)
                && !touches(&commit, &paths)?
            {
                continue;
            }
            entries.push(log_entry(&commit, trailers));
        }
        Ok(entries)
    }

    /// The commit `id` as a log entry, with its full message.
    pub fn entry(&self, id: &CommitId) -> Result<(LogEntry, String), CoreError> {
        let oid = Oid::from_str(id.as_str()).map_err(git_error)?;
        let commit = self.repo.find_commit(oid).map_err(git_error)?;
        let message = String::from_utf8_lossy(commit.message_bytes()).into_owned();
        let trailers = Trailers::parse(&message);
        Ok((log_entry(&commit, trailers), message))
    }

    /// The leak scanner over every commit message and every file version
    /// reachable from HEAD (SPEC 11.8), for stores imported from
    /// elsewhere. Reports only; history is never rewritten. Each file
    /// version is scanned once, at the newest commit holding it; the
    /// working tree's allowlist applies.
    pub fn scan_history(&self) -> Result<Vec<HistoryFinding>, CoreError> {
        let allow = Allowlist::parse(&self.read_to_string(ALLOWLIST_FILE)?.unwrap_or_default());
        let mut walk = self.repo.revwalk().map_err(git_error)?;
        walk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)
            .map_err(git_error)?;
        walk.push_head().map_err(git_error)?;
        let mut seen = HashSet::new();
        let mut findings = Vec::new();
        for oid in walk {
            let commit = self
                .repo
                .find_commit(oid.map_err(git_error)?)
                .map_err(git_error)?;
            let id = CommitId::from_oid(commit.id());
            let mut found = scan_text(
                "commit message",
                commit.message_bytes(),
                false,
                &self.secrets,
                &allow,
            );
            let mut blobs = Vec::new();
            commit
                .tree()
                .map_err(git_error)?
                .walk(TreeWalkMode::PreOrder, |root, entry| {
                    if entry.kind() == Some(ObjectType::Blob) && seen.insert(entry.id()) {
                        let name = String::from_utf8_lossy(entry.name_bytes());
                        blobs.push((format!("{root}{name}"), entry.id()));
                    }
                    TreeWalkResult::Ok
                })
                .map_err(git_error)?;
            for (path, blob) in blobs {
                let blob = self.repo.find_blob(blob).map_err(git_error)?;
                found.extend(scan_text(
                    &path,
                    blob.content(),
                    path.ends_with(".toml"),
                    &self.secrets,
                    &allow,
                ));
            }
            findings.extend(found.into_iter().map(|finding| HistoryFinding {
                commit: id.clone(),
                finding,
            }));
        }
        Ok(findings)
    }
}

/// Whether `commit` changed any of `paths` relative to its first parent.
pub(crate) fn touches(commit: &Commit<'_>, paths: &[String]) -> Result<bool, CoreError> {
    if paths.is_empty() {
        return Ok(false);
    }
    let tree = commit.tree().map_err(git_error)?;
    let parent_tree = match commit.parent(0) {
        Ok(parent) => Some(parent.tree().map_err(git_error)?),
        Err(_) => None,
    };
    Ok(paths
        .iter()
        .any(|path| entry_id(Some(&tree), path) != entry_id(parent_tree.as_ref(), path)))
}

fn entry_id(tree: Option<&Tree<'_>>, path: &str) -> Option<Oid> {
    tree?.get_path(Path::new(path)).ok().map(|entry| entry.id())
}

pub(crate) fn commit_time(commit: &Commit<'_>) -> SystemTime {
    let seconds = commit.time().seconds();
    match u64::try_from(seconds) {
        Ok(seconds) => UNIX_EPOCH + Duration::from_secs(seconds),
        Err(_) => UNIX_EPOCH,
    }
}

fn log_entry(commit: &Commit<'_>, trailers: Trailers) -> LogEntry {
    let message = String::from_utf8_lossy(commit.message_bytes());
    let author = commit.author();
    LogEntry {
        id: CommitId::from_oid(commit.id()),
        time: commit_time(commit),
        author_name: String::from_utf8_lossy(author.name_bytes()).into_owned(),
        author_email: String::from_utf8_lossy(author.email_bytes()).into_owned(),
        summary: message_summary(&message).to_owned(),
        trailers,
    }
}