silcrow 0.1.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use regex::Regex;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use crate::parse::{PointerKind, Scan, Target};
use crate::walk;

pub struct MarkerCounts {
    pub code: usize,
    pub doc: usize,
}

pub struct LawMeta {
    pub declared_on: Option<String>,
    pub age: Option<String>,
    pub markers: MarkerCounts,
    pub remints: usize,
    pub accepts: usize,
    pub repins: usize,
    pub past_paths: usize,
}

/// The metadata of one law, with its history counts when `full`.
pub fn for_id(root: &Path, scan: &Scan, id: &str, full: bool) -> LawMeta {
    // § c5watr20f.a@54xzc
    let mut meta = for_ids(root, scan, &[id])
        .remove(id)
        .expect("for_ids holds every id it is asked for");
    if full {
        (meta.remints, meta.accepts, meta.repins) = crate::log::rewrite_counts(root, id)
            .map(|r| (r.remints, r.accepts, r.repins.len()))
            .unwrap_or((0, 0, 0));
        meta.past_paths = past_marker_paths(root, id);
    }
    meta
}

/// The metadata of each of `ids`, without the history counts, from one scan and one walk of
/// the history.
pub fn for_ids(root: &Path, scan: &Scan, ids: &[&str]) -> BTreeMap<String, LawMeta> {
    let mut declared = declared(root, ids);
    let mut markers = current_markers(root, scan);
    ids.iter()
        .map(|id| {
            let (declared_on, age) = declared.remove(*id).unwrap_or_default();
            let markers = markers
                .remove(*id)
                .unwrap_or(MarkerCounts { code: 0, doc: 0 });
            let meta = LawMeta {
                declared_on,
                age,
                markers,
                remints: 0,
                accepts: 0,
                repins: 0,
                past_paths: 0,
            };
            (id.to_string(), meta)
        })
        .collect()
}

/// The date and the age of a commit.
pub type Declared = (Option<String>, Option<String>);

/// The date and age of the earliest commit that adds each id, read in one walk.
pub fn declared(root: &Path, ids: &[&str]) -> BTreeMap<String, Declared> {
    declared_in(ids, || history_patch(root))
}

/// The walk `declared` reads, started on its own thread so it runs beside the caller's work.
pub struct History(std::thread::JoinHandle<Option<String>>);

impl History {
    pub fn start(root: &Path) -> Self {
        let root = root.to_path_buf();
        Self(std::thread::spawn(move || history_patch(&root)))
    }

    pub fn declared(self, ids: &[&str]) -> BTreeMap<String, Declared> {
        declared_in(ids, || {
            self.0
                .join()
                .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
        })
    }
}

fn declared_in(
    ids: &[&str],
    history: impl FnOnce() -> Option<String>,
) -> BTreeMap<String, Declared> {
    // § c5watr20f@02ka8
    let mut found = BTreeMap::new();
    if ids.is_empty() {
        return found;
    }
    let alternation: Vec<String> = ids.iter().map(|id| regex::escape(id)).collect();
    let re = Regex::new(&alternation.join("|")).expect("id alternation");
    let Some(stdout) = history() else {
        return found;
    };
    let mut head: Declared = (None, None);
    for line in stdout.lines() {
        if let Some(rest) = line.strip_prefix('\u{1}') {
            let (date, age) = rest.split_once('\t').unwrap_or((rest, ""));
            let some = |s: &str| (!s.is_empty()).then(|| s.to_string());
            head = (some(date), some(age));
            continue;
        }
        if !line.starts_with('+') || line.starts_with("+++") {
            continue;
        }
        for m in re.find_iter(line) {
            found
                .entry(m.as_str().to_string())
                .or_insert_with(|| head.clone());
        }
        if found.len() == ids.len() {
            break;
        }
    }
    found
}

/// The age of each draft: the date and age of the earliest commit that adds its head or its
/// item line as the tree writes it, `None` for a line no commit adds. `None` outside git.
pub fn draft_ages(root: &Path, drafts: &[crate::list::Draft]) -> Option<Vec<Option<Declared>>> {
    // § pxmeee9ra.f@qc7k3
    let mut notes: BTreeMap<&Path, String> = BTreeMap::new();
    let lines: Vec<String> = drafts
        .iter()
        .map(|draft| {
            let loc = draft.loc();
            let text = notes.entry(loc.path.as_path()).or_insert_with(|| {
                std::fs::read_to_string(root.join(&loc.path)).unwrap_or_default()
            });
            text.lines()
                .nth(loc.line.saturating_sub(1))
                .unwrap_or_default()
                .trim()
                .to_string()
        })
        .collect();
    let history = patch_walk(
        root,
        &[
            "--format=%x01%ad%x09%ar",
            "--date=short",
            "--",
            "*.md",
            "*.markdown",
            "*.mdx",
        ],
    )
    .ok()?;
    let needles: Vec<&str> = lines
        .iter()
        .map(String::as_str)
        .filter(|line| !line.is_empty())
        .collect();
    let found = declared_in(&needles, || Some(history));
    Some(lines.iter().map(|line| found.get(line).cloned()).collect())
}

/// Every commit's patch, oldest first, each opened by its date and age.
fn history_patch(root: &Path) -> Option<String> {
    // No pathspec: the id may first appear bare, or in a file the head has since left.
    patch_walk(root, &["--format=%x01%ad%x09%ar", "--date=short"]).ok()
}

/// The one walk of history every reader of it shares: each commit `args` selects, oldest
/// first, with its patch at no context and no rename.
pub fn patch_walk(root: &Path, args: &[&str]) -> anyhow::Result<String> {
    let out = crate::workspace::git(root)
        .args([
            "-c",
            "core.quotePath=false",
            "log",
            "--reverse",
            "-p",
            "-U0",
            "--no-color",
            "--no-ext-diff",
            "--no-renames",
            "--src-prefix=a/",
            "--dst-prefix=b/",
        ])
        .args(args)
        .output()?;
    if !out.status.success() {
        anyhow::bail!(
            "git log failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

/// The markers of each id by surface: a file the `docs` list matches, or code the `code` list
/// matches outside Markdown. A marker on neither surface pays no duty and counts in neither.
fn current_markers(root: &Path, scan: &Scan) -> BTreeMap<String, MarkerCounts> {
    // § c5watr20f.a@dyhn4
    let policy = crate::policy::ProjectPolicy::from_root(root)
        .expect("the block parsed when the scan was read");
    let project = crate::walk::Project::at(root).expect("the block parsed when the scan was read");
    let mut out: BTreeMap<String, MarkerCounts> = BTreeMap::new();
    for ptr in &scan.pointers {
        if ptr.kind != PointerKind::Implements {
            continue;
        }
        let Target::Stable { id, .. } = &ptr.target else {
            continue;
        };
        let counts = out
            .entry(id.clone())
            .or_insert(MarkerCounts { code: 0, doc: 0 });
        let path = ptr.loc.path.as_path();
        if project.is_note(path) {
            continue;
        }
        if policy.docs.matches(path) {
            counts.doc += 1;
        } else if policy.code.matches(path) && !crate::marker::is_markdown(path) {
            counts.code += 1;
        }
    }
    out
}

/// The distinct files of the project's own walk whose history ever changed the id.
fn past_marker_paths(root: &Path, id: &str) -> usize {
    let out = crate::workspace::git(root)
        .args([
            "log",
            "-S",
            id,
            "--name-only",
            "--relative",
            "--pretty=format:",
            "--",
            ".",
        ])
        .output();
    let Ok(out) = out else {
        return 0;
    };
    if !out.status.success() {
        return 0;
    }
    let Ok(project) = walk::Project::at(root) else {
        return 0;
    };
    let mut paths = BTreeSet::new();
    for line in String::from_utf8_lossy(&out.stdout).lines() {
        let rel = Path::new(line.trim());
        if rel.as_os_str().is_empty() || project.is_note(rel) || !walk::walks_to(&project, rel) {
            continue;
        }
        paths.insert(rel.to_path_buf());
    }
    paths.len()
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    pub(crate) const NOTE: &str = "notes/decisions/x.md";
    pub(crate) const SENTENCE: &str = "The workload fails closed.";

    /// A git tree whose docs base is `notes`, whose code sits in `lib/`, with a README doc
    /// marker and a nested project that carries a marker of the same id.
    pub(crate) fn notes_tree(root: &Path, id: &str) {
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        let block = "<silcrow notes=\"notes/decisions/**/*.md\" default-branch=\"main\" docs=\"README.md\">\n</silcrow>\n";
        for (path, text) in [
            ("AGENTS.md".to_string(), block.to_string()),
            (
                NOTE.to_string(),
                format!("# X\n\n**§ <a id=\"{id}\">{id}</a> {SENTENCE}**\n"),
            ),
            (
                "lib/a.rs".to_string(),
                format!("fn f() {{\n    // § {id}\n    go();\n}}\n"),
            ),
            (
                "README.md".to_string(),
                format!("# Guide\n\n<!-- § {id} -->\n\nProse.\n"),
            ),
            ("sub/AGENTS.md".to_string(), block.to_string()),
            (
                "sub/lib/b.rs".to_string(),
                format!("fn g() {{\n    // § .:{id}\n    go();\n}}\n"),
            ),
        ] {
            let path = root.join(path);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, text).unwrap();
        }
        commit(root, "2026-01-02T12:00:00Z", "declare");
    }

    #[test]
    fn metadata_reads_the_project_walk_and_its_docs_base() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        notes_tree(root, id);
        let scan = crate::parse::scan_root(root).unwrap();
        let meta = for_id(root, &scan, id, true);
        assert_eq!(meta.declared_on.as_deref(), Some("2026-01-02"));
        assert_eq!((meta.markers.code, meta.markers.doc), (1, 1));
        assert_eq!(meta.past_paths, 2);
        let bulk = for_ids(root, &scan, &[id, "abcdefgh2"]);
        assert_eq!(bulk[id].declared_on.as_deref(), Some("2026-01-02"));
        assert_eq!((bulk[id].markers.code, bulk[id].markers.doc), (1, 1));
        assert!(bulk["abcdefgh2"].declared_on.is_none());
    }

    #[test]
    fn a_markdown_marker_counts_as_documentation_only_where_the_docs_list_matches() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        notes_tree(root, id);
        std::fs::write(
            root.join("AGENTS.md"),
            "<silcrow notes=\"notes/decisions/**/*.md\" default-branch=\"main\">\n</silcrow>\n",
        )
        .unwrap();
        let scan = crate::parse::scan_root(root).unwrap();
        let meta = for_ids(root, &scan, &[id]);
        assert_eq!((meta[id].markers.code, meta[id].markers.doc), (1, 0));
    }

    pub(crate) fn commit(dir: &Path, date: &str, msg: &str) {
        for args in [
            vec!["add", "-A"],
            vec!["commit", "-q", "--no-verify", "-m", msg],
        ] {
            let out = crate::test_git()
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args([
                    "-c",
                    "commit.gpgsign=false",
                    "-c",
                    "core.hooksPath=/dev/null",
                ])
                .args(&args)
                .env("GIT_AUTHOR_DATE", date)
                .env("GIT_COMMITTER_DATE", date)
                .current_dir(dir)
                .output()
                .unwrap();
            assert!(out.status.success(), "{out:?}");
        }
    }

    #[test]
    fn declaration_is_the_first_commit_naming_the_id_in_any_form_and_any_file() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let id = "abcdefgh1";
        let init = crate::test_git()
            .args(["init", "-q", "--template="])
            .current_dir(root)
            .status()
            .unwrap();
        assert!(init.success());
        std::fs::create_dir_all(root.join("docs")).unwrap();
        std::fs::write(
            root.join("docs/old.md"),
            format!("§ {id} The workload fails closed.\n"),
        )
        .unwrap();
        commit(root, "2026-01-05T12:00:00Z", "bare form outside the notes");
        std::fs::remove_file(root.join("docs/old.md")).unwrap();
        std::fs::create_dir_all(root.join("docs/decisions")).unwrap();
        std::fs::write(
            root.join("docs/decisions/graph.md"),
            format!("**§ <a id=\"{id}\">{id}</a> The workload fails closed.**\n"),
        )
        .unwrap();
        commit(root, "2026-02-05T12:00:00Z", "anchor wrap in its new note");
        std::fs::write(
            root.join("docs/decisions/other.md"),
            format!("See [{id}](graph.md#{id}).\n"),
        )
        .unwrap();
        commit(root, "2026-03-05T12:00:00Z", "a cite");
        let scan = Scan::default();
        let meta = for_ids(root, &scan, &[id]);
        assert_eq!(meta[id].declared_on.as_deref(), Some("2026-01-05"));
    }
}