use anyhow::{bail, Context, Result};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use crate::check;
use crate::hash;
use crate::log;
use crate::parse;
use crate::resolve;
use crate::workspace::Workspace;
pub fn run(ws: &Workspace, event: &str, args: &[String]) -> Result<()> {
match event {
"pre-commit" => pre_commit(ws),
"post-merge" => post_merge(ws),
"post-rewrite" => post_rewrite(ws, args),
"commit-msg" => commit_msg(&ws.root, args),
"pre-merge-commit" => pre_merge_commit(ws),
"pre-push" => pre_push(ws),
other => bail!("unknown hook event `{other}`"),
}
}
fn pre_merge_commit(ws: &Workspace) -> Result<()> {
let index = IndexTree::export(&ws.root)?;
let outcome = check_index(ws, &index);
index.remove()?;
crate::workspace::git(&ws.root)
.args(["update-index", "-q", "--refresh"])
.status()?;
match outcome? {
Outcome::Passed => Ok(()),
Outcome::Refused => {
println!("\n`pre-merge-commit` refused the merge: repair each error, then commit the merge with `git commit`.");
crate::cache::flush();
std::process::exit(1)
}
Outcome::Warned(branch) => {
let_through("pre-merge-commit", &branch);
Ok(())
}
}
}
fn check_index(ws: &Workspace, index: &IndexTree) -> Result<Outcome> {
let copy = index_workspace(ws, index)?;
let mut report = check::validate(©, ©.local(), true)?;
report.harness = staged_harness(ws, ©)?;
report.errors.extend(stray_markers(©)?);
if report.is_closed() {
check::print_report(&report, false, None, false, &check::Owned::Off);
return Ok(Outcome::Passed);
}
let (outcome, _) = failed(ws)?;
let warned = matches!(outcome, Outcome::Warned(_));
check::print_report(&report, false, None, warned, &check::Owned::Off);
Ok(outcome)
}
fn pre_push(ws: &Workspace) -> Result<()> {
let dirs: Vec<&Path> = ws.local().iter().map(|p| p.dir.as_path()).collect();
let default = format!("refs/heads/{}", crate::published::branch(&dirs)?);
let mut input = String::new();
std::io::Read::read_to_string(&mut std::io::stdin(), &mut input)?;
let absent = |sha: &str| sha.bytes().all(|b| b == b'0');
let mut checked = BTreeSet::new();
let mut refused = Vec::new();
for line in input.lines().filter(|line| !line.trim().is_empty()) {
let [_, local, remote_ref, remote] = line.split_whitespace().collect::<Vec<_>>()[..] else {
bail!("pre-push: git wrote a line that is not `<local ref> <local object> <remote ref> <remote object>`: {line:?}");
};
let held = !absent(remote) || remote_ref == default;
if absent(local) || !remote_ref.starts_with("refs/heads/") || !held {
continue;
}
if checked.insert(local.to_string()) && !commit_passes(ws, local)? {
refused.push(remote_ref.trim_start_matches("refs/heads/").to_string());
}
}
if !refused.is_empty() {
println!(
"\n`pre-push` refused the push: {} would share a commit that fails `check`. Repair each error, commit, then push again.",
refused.join(", ")
);
crate::cache::flush();
std::process::exit(1);
}
Ok(())
}
fn commit_passes(ws: &Workspace, rev: &str) -> Result<bool> {
let dir = std::env::temp_dir().join(format!(
"silcrow-push-{}-{}",
std::process::id(),
crate::published::short(rev)
));
if dir.exists() {
std::fs::remove_dir_all(&dir)?;
}
let report = crate::published::write_tree(&ws.root, rev, &dir).and_then(|()| {
let copy = Workspace::at(dir.clone())?;
let mut report = check::validate(©, ©.local(), true)?;
report.errors.extend(stray_markers(©)?);
Ok(report)
});
std::fs::remove_dir_all(&dir)?;
let report = report?;
if report.is_closed() {
return Ok(true);
}
println!("Commit {} fails `check`:", crate::published::short(rev));
check::print_report(&report, false, None, false, &check::Owned::Off);
Ok(false)
}
fn pre_commit(ws: &Workspace) -> Result<()> {
let staged = staged_paths(&ws.root)?;
let index = IndexTree::export(&ws.root)?;
let outcome = fix_and_check_index(ws, &index, &staged);
index.remove()?;
match outcome? {
Outcome::Passed => Ok(()),
Outcome::Refused => {
crate::cache::flush();
std::process::exit(1)
}
Outcome::Warned(branch) => {
let_through("pre-commit", &branch);
Ok(())
}
}
}
fn let_through(hook: &str, branch: &str) {
println!(
"\nThe branch `{branch}` is not shared: it is not the default branch and no remote-tracking ref bears its name. So `{hook}` reported each error as a warning and let the commit through, writing nothing `fix` rewrote. Once the branch is pushed, they block a commit, and `pre-push` refuses to update a shared branch with them."
);
}
enum Outcome {
Passed,
Refused,
Warned(String),
}
fn failed(ws: &Workspace) -> Result<(Outcome, &'static str)> {
let dirs: Vec<&Path> = ws.local().iter().map(|p| p.dir.as_path()).collect();
Ok(match crate::published::unshared(&ws.root, &dirs)? {
Some(branch) => (Outcome::Warned(branch), "WRN"),
None => (Outcome::Refused, "ERR"),
})
}
fn fix_and_check_index(ws: &Workspace, index: &IndexTree, staged: &[PathBuf]) -> Result<Outcome> {
let copy = index_workspace(ws, index)?;
let unstaged = unstaged_projects(ws, ©);
if !unstaged.is_empty() {
let (outcome, tag) = failed(ws)?;
println!(
" {tag} {} carries a Silcrow block in the worktree but not in the index, so the commit would be checked without its project. Stage it, then commit.",
unstaged.join(", ")
);
return Ok(outcome);
}
let mut rewritten = Vec::new();
let projects: Vec<(&crate::workspace::ProjectRef, Option<Vec<PathBuf>>)> = copy
.local()
.into_iter()
.map(|project| {
let rel = project.dir.strip_prefix(&index.dir).unwrap_or(&project.dir);
let mine: Vec<PathBuf> = staged
.iter()
.filter_map(|path| path.strip_prefix(rel).ok().map(Path::to_path_buf))
.collect();
(project, Some(mine))
})
.collect();
let mut fixed = |project: &crate::workspace::ProjectRef, paths: Option<Vec<PathBuf>>| {
let rel = project.dir.strip_prefix(&index.dir).unwrap_or(&project.dir);
rewritten.extend(paths.into_iter().flatten().map(|path| rel.join(path)));
};
match (projects.len() > 1).then(|| resolve::independent_plans(©, &projects)) {
Some(Some(plans)) => {
let runs = crate::par::map(
projects.iter().zip(plans).collect(),
|_| 1,
|((project, mine), plan)| {
let mine = mine.as_deref().unwrap_or_default();
crate::out::held(|| resolve::resolve_planned(©, project, mine, false, plan))
},
);
for ((project, _), (paths, written)) in projects.iter().zip(runs) {
crate::out::release(&written);
fixed(project, paths?);
}
}
_ => {
for (project, mine) in &projects {
let mine = mine.as_deref().unwrap_or_default();
fixed(
project,
resolve::resolve_staged(©, project, mine, false)?,
);
}
}
}
rewritten.sort();
rewritten.dedup();
let partial: Vec<String> = rewritten
.iter()
.filter(|rel| differs_from_index(&ws.root, rel))
.map(|rel| rel.display().to_string())
.collect();
if !partial.is_empty() {
let (outcome, tag) = failed(ws)?;
println!(
" {tag} {} is partially staged and `silcrow fix` would rewrite it, so the hook writes nothing. Stage each whole, or run `silcrow fix` and stage what it wrote, then commit.",
partial.join(", ")
);
return Ok(outcome);
}
let mut report = check::validate(©, ©.local(), true)?;
report.harness = staged_harness(ws, ©)?;
report.errors.extend(stray_markers(©)?);
if !report.is_closed() {
let (outcome, _) = failed(ws)?;
check::print_report(
&report,
false,
None,
matches!(outcome, Outcome::Warned(_)),
&check::Owned::Off,
);
return Ok(outcome);
}
check::print_report(&report, false, None, false, &check::Owned::Off);
crate::walk::forget();
for rel in &rewritten {
std::fs::copy(index.dir.join(rel), ws.root.join(rel))?;
}
restage(&ws.root, &rewritten)?;
Ok(Outcome::Passed)
}
fn index_workspace(ws: &Workspace, index: &IndexTree) -> Result<Workspace> {
let mut copy = Workspace::discover(&index.dir)?;
for project in ws.projects.iter().filter(|project| project.external) {
if copy.get(&project.key).is_none() {
copy.projects.push(project.clone());
}
}
copy.projects.sort_by(|a, b| a.key.cmp(&b.key));
Ok(copy)
}
fn unstaged_projects(ws: &Workspace, copy: &Workspace) -> Vec<String> {
ws.local()
.into_iter()
.filter(|project| copy.get(&project.key).is_none_or(|staged| staged.external))
.map(|project| {
crate::workspace::in_workspace(&project.key, Path::new("AGENTS.md"))
.display()
.to_string()
})
.collect()
}
fn staged_harness(ws: &Workspace, copy: &Workspace) -> Result<Vec<String>> {
let versioned =
|root: &Path, projects: Vec<&crate::workspace::ProjectRef>| -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
for d in crate::harness::workspace_drift(root)? {
if d.versioned {
out.push(d.path);
}
}
for project in projects {
if let Some(d) = crate::harness::project_drift(&project.dir)? {
out.push(d.path);
}
}
Ok(out
.into_iter()
.map(|path| path.strip_prefix(root).unwrap_or(&path).to_path_buf())
.collect())
};
let worktree = versioned(&ws.root, ws.local())?;
Ok(versioned(©.root, copy.local())?
.into_iter()
.map(|rel| {
if !worktree.contains(&rel) {
format!(
"{} is not staged as `silcrow install` wrote it. Stage it, with `git add -f` when git ignores it.",
rel.display()
)
} else if copy.root.join(&rel).exists() {
format!(
"{} differs from this binary. Run `silcrow install`, then stage it.",
rel.display()
)
} else {
format!(
"{} is missing. Run `silcrow install`, then stage it.",
rel.display()
)
}
})
.collect())
}
pub fn stray_markers(ws: &Workspace) -> Result<Vec<String>> {
let mut out = Vec::new();
if ws.projects.is_empty() {
return Ok(out);
}
for path in crate::walk::files_outside_projects(&ws.root)? {
let text =
std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
if !text.contains('§') {
continue;
}
let dialect = crate::marker::Dialect::of(&path);
let fenced = crate::marker::fenced_lines(dialect.is_markdown(), &text);
let rel = path.strip_prefix(&ws.root).unwrap_or(&path);
for (idx, line) in text.lines().enumerate() {
let line = line.trim();
if fenced[idx] || !crate::marker::opens_like_a_marker(line) || !dialect.opens_with(line)
{
continue;
}
out.push(format!(
"{}:{}: `{line}` is in a file outside every project, so no project checks it. Move it into a project, or give its directory, or one above it, an `AGENTS.md` with a Silcrow block.",
rel.display(),
idx + 1
));
}
}
Ok(out)
}
fn differs_from_index(root: &Path, rel: &Path) -> bool {
!crate::workspace::git(root)
.args(["diff", "--quiet", "--"])
.arg(rel)
.status()
.is_ok_and(|status| status.success())
}
struct IndexTree {
dir: PathBuf,
}
impl IndexTree {
fn export(root: &Path) -> Result<Self> {
let git_dir = git_line(root, &["rev-parse", "--absolute-git-dir"])?;
let dir = PathBuf::from(&git_dir).join("silcrow-index");
write_index(root, &dir, true)?;
crate::walk::forget();
if std::env::var_os("SILCROW_CACHE_VERIFY").is_some() {
let full = PathBuf::from(&git_dir).join("silcrow-index-full");
write_index(root, &full, false)?;
let (fast, all) = (tree_of(&dir)?, tree_of(&full)?);
std::fs::remove_dir_all(&full)?;
if fast != all {
bail!(
"the index written from the worktree differs from the index git writes at {}",
dir.display()
);
}
}
std::fs::write(dir.join(".git"), format!("gitdir: {git_dir}\n"))?;
Ok(Self { dir })
}
fn remove(&self) -> Result<()> {
crate::walk::forget();
remove_tree(&self.dir)
}
}
fn write_index(root: &Path, dir: &Path, from_worktree: bool) -> Result<()> {
if dir.exists() {
remove_tree(dir)?;
}
std::fs::create_dir_all(dir)?;
let mut checkout = crate::workspace::git(root);
checkout
.args(["checkout-index", "--force"])
.arg(format!("--prefix={}/", dir.display()));
let rest = match from_worktree {
true => cloned_from_worktree(root, dir),
false => None,
};
let ok = match rest {
Some(rest) if rest.is_empty() => true,
Some(rest) => {
checkout
.args(["-z", "--stdin"])
.stdin(std::process::Stdio::piped());
let mut child = checkout.spawn()?;
let mut stdin = child.stdin.take().expect("piped stdin");
let paths: Vec<u8> = rest.iter().flat_map(|p| p.bytes().chain([0])).collect();
std::io::Write::write_all(&mut stdin, &paths)?;
drop(stdin);
child.wait()?.success()
}
None => checkout.arg("--all").status()?.success(),
};
if !ok {
bail!(
"git checkout-index could not write the index to {}",
dir.display()
);
}
Ok(())
}
fn remove_tree(dir: &Path) -> Result<()> {
let mut files = Vec::new();
let mut dirs = vec![dir.to_path_buf()];
let mut at = 0;
while at < dirs.len() {
for item in std::fs::read_dir(&dirs[at])? {
let item = item?;
match item.file_type()?.is_dir() {
true => dirs.push(item.path()),
false => files.push(item.path()),
}
}
at += 1;
}
for removed in crate::par::map_many(files, std::fs::remove_file) {
removed?;
}
for dir in dirs.iter().rev() {
std::fs::remove_dir(dir)?;
}
Ok(())
}
fn tree_of(dir: &Path) -> Result<std::collections::BTreeMap<PathBuf, (Vec<u8>, bool)>> {
let mut out = std::collections::BTreeMap::new();
let mut dirs = vec![dir.to_path_buf()];
while let Some(at) = dirs.pop() {
for item in std::fs::read_dir(&at)? {
let path = item?.path();
let meta = std::fs::symlink_metadata(&path)?;
let rel = path.strip_prefix(dir).unwrap_or(&path).to_path_buf();
if meta.is_dir() {
dirs.push(path);
} else if meta.file_type().is_symlink() {
let target = std::fs::read_link(&path)?;
out.insert(rel, (target.to_string_lossy().as_bytes().to_vec(), false));
} else {
out.insert(rel, (std::fs::read(&path)?, runs(&meta)));
}
}
}
Ok(out)
}
fn cloned_from_worktree(root: &Path, dir: &Path) -> Option<Vec<String>> {
let format = git_line(root, &["rev-parse", "--show-object-format"]).ok()?;
let sparse = git_line(root, &["config", "--bool", "core.sparseCheckout"]).ok();
if format != "sha1" || sparse.as_deref() == Some("true") {
return None;
}
let out = crate::workspace::git(root)
.args(["ls-files", "--stage", "-z"])
.output()
.ok()
.filter(|out| out.status.success())?;
let mut entries = Vec::new();
for record in out.stdout.split(|&b| b == 0).filter(|r| !r.is_empty()) {
let record = std::str::from_utf8(record).ok()?;
let (meta, path) = record.split_once('\t')?;
let mut fields = meta.split(' ');
let (mode, blob, stage) = (fields.next()?, fields.next()?, fields.next()?);
if stage != "0" {
return None;
}
entries.push((mode.to_string(), blob.to_string(), path.to_string()));
}
let copied = crate::par::map_many(entries, |(mode, blob, path)| {
let same = matches!(mode.as_str(), "100644" | "100755")
&& copy_if_staged(&root.join(&path), &dir.join(&path), &blob, mode == "100755");
(!same).then_some(path)
});
Some(copied.into_iter().flatten().collect())
}
fn copy_if_staged(from: &Path, to: &Path, blob: &str, executable: bool) -> bool {
let regular = std::fs::symlink_metadata(from).is_ok_and(|m| m.file_type().is_file());
let copied = regular
&& to
.parent()
.is_some_and(|p| std::fs::create_dir_all(p).is_ok())
&& std::fs::copy(from, to).is_ok();
if !copied {
return false;
}
let held = std::fs::read(to).is_ok_and(|bytes| crate::workspace::blob_id(&bytes) == blob);
let mode = std::fs::metadata(to).is_ok_and(|m| runs(&m) == executable);
if held && mode {
return true;
}
let _ = std::fs::remove_file(to);
false
}
#[cfg(unix)]
fn runs(meta: &std::fs::Metadata) -> bool {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
fn runs(_: &std::fs::Metadata) -> bool {
false
}
fn git_line(root: &Path, args: &[&str]) -> Result<String> {
let out = crate::workspace::git(root).args(args).output()?;
if !out.status.success() {
bail!(
"git {}: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn staged_paths(root: &Path) -> Result<Vec<PathBuf>> {
let out = crate::workspace::git(root)
.args(["diff", "--cached", "--name-only"])
.output()?;
if !out.status.success() {
return Ok(Vec::new());
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| !line.is_empty())
.map(PathBuf::from)
.collect())
}
fn restage(root: &Path, paths: &[PathBuf]) -> Result<()> {
for rel in paths {
let Some(path) = rel.to_str() else {
continue;
};
let status = crate::workspace::git(root)
.args(["add", "--", path])
.status()?;
if !status.success() {
bail!("git add failed for {}", rel.display());
}
}
Ok(())
}
fn post_merge(ws: &Workspace) -> Result<()> {
eprintln!("silcrow: post-merge semantic collision check");
let mut report = check::validate(ws, &ws.local(), true)?;
report.errors.extend(stray_markers(ws)?);
let merge_report = crate::merge::parent_conflicts(ws)?;
report.errors.extend(merge_report.errors);
report.warnings.extend(merge_report.warnings);
if !check::print_report(&report, false, None, false, &check::Owned::Off) {
crate::cache::flush();
std::process::exit(1);
}
Ok(())
}
fn post_rewrite(ws: &Workspace, args: &[String]) -> Result<()> {
let before = rewritten_commit(
&ws.root,
args.first().map(String::as_str),
&mut std::io::stdin().lock(),
)?;
let mut report = check::validate(ws, &ws.local(), true)?;
report.errors.extend(stray_markers(ws)?);
for project in ws.local() {
let (genealogy_errors, genealogy_warnings) =
verify_rewrite_genealogy(&project.dir, before.as_deref())?;
report.errors.extend(genealogy_errors);
report.warnings.extend(genealogy_warnings);
}
if !check::print_report(&report, false, None, false, &check::Owned::Off) {
crate::cache::flush();
std::process::exit(1);
}
Ok(())
}
fn rewritten_commit(
root: &Path,
kind: Option<&str>,
stdin: &mut dyn std::io::BufRead,
) -> Result<Option<String>> {
if kind == Some("amend") {
let mut line = String::new();
stdin.read_line(&mut line)?;
let Some(old) = line.split_whitespace().next() else {
bail!("post-rewrite after an amend got no `<old> <new>` line on stdin");
};
return Ok(Some(old.to_string()));
}
let out = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", "ORIG_HEAD"])
.output()?;
Ok(out
.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()))
}
const GENEALOGY_CAP: usize = 50;
fn verify_rewrite_genealogy(
root: &Path,
before: Option<&str>,
) -> Result<(Vec<String>, Vec<String>)> {
let scan = parse::scan_root(root)?;
let live: Vec<(String, PathBuf)> = scan
.laws
.iter()
.filter(|law| !hash::is_provisional_id(&law.id))
.map(|law| (law.id.clone(), law.loc.path.clone()))
.collect();
let (changed, existed_before) = match before {
Some(before) => (
rewrite_changed_paths(root, before)?,
pre_rewrite_law_ids(root, before)?,
),
None => (BTreeSet::new(), BTreeSet::new()),
};
let (ids, capped) = select_genealogy_ids(&live, &changed, GENEALOGY_CAP);
let (errors, mut warnings) = if ids.is_empty() {
(Vec::new(), Vec::new())
} else {
log::genealogy_check(root, &ids, &existed_before)
};
warnings.extend(capped);
Ok((errors, warnings))
}
fn rewrite_changed_paths(root: &Path, before: &str) -> Result<BTreeSet<PathBuf>> {
let out = crate::workspace::git(root)
.args(["diff", "--relative", "--name-only", before, "HEAD"])
.output()?;
if !out.status.success() {
return Ok(BTreeSet::new());
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| !line.is_empty())
.map(PathBuf::from)
.collect())
}
fn pre_rewrite_law_ids(root: &Path, before: &str) -> Result<BTreeSet<String>> {
let mut ids = BTreeSet::new();
let project = crate::walk::Project::at(root)?;
let out = crate::workspace::git(root)
.args(["ls-tree", "-r", "--name-only", before, "--"])
.args(
project
.notes
.roots()
.iter()
.map(|dir| match dir.as_os_str().is_empty() {
true => Path::new("."),
false => dir.as_path(),
}),
)
.output()?;
if !out.status.success() {
return Ok(ids);
}
for rel in String::from_utf8_lossy(&out.stdout).lines() {
if rel.is_empty() || !project.is_note(Path::new(rel)) {
continue;
}
let scan = scan_at_rev(root, before, &PathBuf::from(rel));
for law in scan.laws {
if !hash::is_provisional_id(&law.id) {
ids.insert(law.id);
}
}
}
Ok(ids)
}
fn scan_at_rev(root: &Path, rev: &str, rel: &Path) -> parse::Scan {
let spec = format!("{}:./{}", rev, rel.to_string_lossy());
let out = crate::workspace::git(root)
.args(["show", &spec])
.output()
.ok();
let Some(out) = out else {
return parse::Scan::default();
};
if !out.status.success() {
return parse::Scan::default();
}
let Ok(text) = String::from_utf8(out.stdout) else {
return parse::Scan::default();
};
parse::scan_text(rel, &text)
}
fn select_genealogy_ids(
live: &[(String, PathBuf)],
changed: &BTreeSet<PathBuf>,
cap: usize,
) -> (Vec<String>, Option<String>) {
if live.len() < cap {
return (live.iter().map(|(id, _)| id.clone()).collect(), None);
}
let ids: Vec<String> = live
.iter()
.filter(|(_, path)| changed.contains(path))
.map(|(id, _)| id.clone())
.collect();
let skipped = live.len() - ids.len();
let warning = (skipped > 0).then(|| {
format!(
"genealogy: {} live laws reach GENEALOGY_CAP ({cap}): verified the {} in changed notes, skipped {skipped}",
live.len(),
ids.len()
)
});
(ids, warning)
}
fn commit_msg(root: &Path, args: &[String]) -> Result<()> {
let Some(msg_path) = args.first() else {
return Ok(());
};
let path = PathBuf::from(msg_path);
let mut body = std::fs::read_to_string(&path)?;
let staged = staged_paths(root)?;
if staged.is_empty() {
return Ok(());
}
let index = IndexTree::export(root)?;
let named = staged_law_ids(&index.dir, &staged).and_then(|ids| declared_only(&index.dir, ids));
index.remove()?;
if named?.is_empty() {
return Ok(());
}
let recorded = recorded_scheme(root)?;
let current = crate::scheme::BINARY_VERSION;
let alone = match recorded {
Some(scheme) if scheme != current => {
let alone = only_minted_tokens_staged(root)?;
if !alone {
eprintln!(
"silcrow: the scheme moves from {scheme} to {current} in a change that moves more than digests, ids and alias anchors. A scheme remint travels alone, so this commit records the scheme without `Silcrow-Op: remint`."
);
}
alone
}
_ => false,
};
let trailers = scheme_trailers(recorded, current, alone, &body);
if trailers.is_empty() {
return Ok(());
}
if !body.ends_with('\n') {
body.push('\n');
}
body.push_str(&format!("\n{}\n", trailers.join("\n")));
std::fs::write(path, body)?;
Ok(())
}
fn scheme_trailers(recorded: Option<u32>, current: u32, remint: bool, body: &str) -> Vec<String> {
if body.contains("Silcrow-Scheme:") || recorded == Some(current) {
return Vec::new();
}
let mut out = Vec::new();
if recorded.is_some() && remint && !body.contains("Silcrow-Op:") {
out.push("Silcrow-Op: remint".to_string());
}
out.push(format!("Silcrow-Scheme: {current}"));
out
}
fn only_minted_tokens_staged(root: &Path) -> Result<bool> {
let diff = git_line(
root,
&["diff", "--cached", "--no-color", "--no-ext-diff", "-U0"],
)?;
Ok(only_minted_tokens(&diff))
}
pub fn only_minted_tokens(diff: &str) -> bool {
static TOKEN_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
regex::Regex::new(&format!(
r#"<a id="{id}"></a>|@{digest}(?:{digest})?|\b{id}\b"#,
id = crate::marker::ID,
digest = crate::marker::DIGEST
))
.expect("minted token regex")
});
let blank = |line: &str| {
TOKEN_RE
.replace_all(
line,
|caps: ®ex::Captures| {
if caps[0].starts_with('<') {
""
} else {
"~"
}
},
)
.into_owned()
};
let (mut gone, mut came) = (Vec::new(), Vec::new());
for line in diff.lines() {
if line.starts_with("---") || line.starts_with("+++") {
continue;
}
if let Some(rest) = line.strip_prefix('-') {
gone.push(blank(rest));
} else if let Some(rest) = line.strip_prefix('+') {
came.push(blank(rest));
}
}
gone.sort();
came.sort();
gone == came
}
fn recorded_scheme(root: &Path) -> Result<Option<u32>> {
recorded_scheme_at(root, "HEAD")
}
pub fn recorded_scheme_at(root: &Path, rev: &str) -> Result<Option<u32>> {
let born = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", rev])
.output()?;
if !born.status.success() {
return Ok(None);
}
let out = crate::workspace::git(root)
.args([
"log",
"-1",
"-E",
"--grep=^Silcrow-Scheme: ",
"--format=%B",
rev,
])
.output()?;
if !out.status.success() {
bail!("git log failed while reading Silcrow-Scheme");
}
let text = String::from_utf8_lossy(&out.stdout);
let Some(value) = text
.lines()
.filter_map(|line| line.strip_prefix("Silcrow-Scheme:"))
.next_back()
else {
return Ok(None);
};
let value = value.trim();
match value.parse() {
Ok(n) => Ok(Some(n)),
Err(_) => bail!("Silcrow-Scheme trailer `{value}` is not a scheme number"),
}
}
fn staged_law_ids(index: &Path, staged: &[PathBuf]) -> Result<Vec<String>> {
let mut ids = Vec::new();
for rel in staged {
let Ok(text) = std::fs::read_to_string(index.join(rel)) else {
continue;
};
let mut scan = parse::Scan::default();
if crate::walk::is_note_in(index, rel)? {
parse::parse_note_text(rel, &text, &mut scan);
for law in &scan.laws {
ids.push(law.id.clone());
}
}
for row in crate::span::marker_rows(rel, &text, None) {
ids.extend(row.markers.into_iter().map(|marker| marker.id));
}
}
ids.sort();
ids.dedup();
Ok(ids)
}
fn declared_only(root: &Path, ids: Vec<String>) -> Result<Vec<String>> {
if ids.is_empty() {
return Ok(ids);
}
let mut declared = BTreeSet::new();
for project in Workspace::discover(root)?.local() {
for law in parse::scan_root(&project.dir)?.laws {
declared.extend(law.aliases);
declared.insert(law.id);
}
}
Ok(ids.into_iter().filter(|id| declared.contains(id)).collect())
}
pub fn script(root: &Path, event: &str) -> String {
if is_silcrow_repo(root) {
format!("#!/bin/sh\nset -e\nexec cargo run -q -- hook {event} \"$@\"\n")
} else {
format!("#!/bin/sh\nset -e\nexec silcrow hook {} \"$@\"\n", event)
}
}
pub fn hooks_dir(root: &Path) -> Result<Option<PathBuf>> {
let dot_git = root.join(".git");
if !dot_git.exists() {
return Ok(None);
}
if dot_git.is_file() {
let link = std::fs::read_to_string(&dot_git)?;
let Some(git_dir) = link.trim().strip_prefix("gitdir: ") else {
bail!(
"{} is a file that names no `gitdir:`, so its hooks cannot be found",
dot_git.display()
);
};
if root.starts_with(git_dir) {
return Ok(None);
}
let path = PathBuf::from(git_line(root, &["rev-parse", "--git-path", "hooks"])?);
return Ok(Some(if path.is_absolute() {
path
} else {
root.join(path)
}));
}
let out = crate::workspace::git(root)
.args(["config", "--get", "core.hooksPath"])
.output()?;
let configured = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !out.status.success() || configured.is_empty() {
return Ok(Some(dot_git.join("hooks")));
}
let path = PathBuf::from(configured);
Ok(Some(if path.is_absolute() {
path
} else {
root.join(path)
}))
}
const EVENTS: [&str; 6] = [
"pre-commit",
"post-merge",
"post-rewrite",
"commit-msg",
"pre-merge-commit",
"pre-push",
];
fn call_line(root: &Path, event: &str) -> String {
let script = script(root, event);
let exec = script.lines().last().unwrap_or_default();
exec.replacen("exec ", "", 1)
}
fn is_ours(text: &str, event: &str) -> bool {
let event = regex::escape(event);
regex::Regex::new(&format!(
r#"^#!/bin/sh\nset -e\n(?:cd '[^'\n]*' && )?exec (?:silcrow|cargo run -q --) hook {event} "\$@"\n$"#
))
.expect("hook script regex")
.is_match(text)
}
enum HookState {
Current,
Write(Option<String>),
Foreign,
}
fn executable(path: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
let _ = path;
true
}
}
fn hook_state(root: &Path, path: &Path, event: &str) -> HookState {
match std::fs::read(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => HookState::Write(None),
Ok(bytes) => match String::from_utf8(bytes) {
Ok(old) if old == script(root, event) && executable(path) => HookState::Current,
Ok(old) if is_ours(&old, event) => HookState::Write(Some(old)),
_ => HookState::Foreign,
},
Err(_) => HookState::Foreign,
}
}
pub fn drift(root: &Path) -> Result<Vec<(PathBuf, Option<String>)>> {
let Some(dir) = hooks_dir(root)? else {
return Ok(Vec::new());
};
Ok(EVENTS
.iter()
.filter_map(|event| {
let path = dir.join(event);
match hook_state(root, &path, event) {
HookState::Current => None,
HookState::Write(_) => Some((path, None)),
HookState::Foreign => Some((path, Some(call_line(root, event)))),
}
})
.collect())
}
pub fn installed(root: &Path) -> Result<Vec<PathBuf>> {
let Some(dir) = hooks_dir(root)? else {
return Ok(Vec::new());
};
Ok(EVENTS
.iter()
.map(|event| (dir.join(event), script(root, event)))
.filter(|(path, body)| std::fs::read_to_string(path).ok().as_deref() == Some(body.as_str()))
.map(|(path, _)| path)
.collect())
}
pub fn foreign_origin(root: &Path, path: &Path) -> Option<String> {
let text = std::fs::read(path).ok()?;
let event = path.file_name()?.to_str()?;
if let Some(dir) = template_dir(root) {
if std::fs::read(dir.join("hooks").join(event)).ok().as_deref() == Some(text.as_slice()) {
return Some(format!(
"it is the copy of `{}` that `git init` made from your git template, not a hook of this repository: delete it and run `silcrow install` again to write Silcrow's, or add the line to keep both",
dir.join("hooks").join(event).display()
));
}
}
let text = String::from_utf8_lossy(&text);
let tool = [
("husky", "husky"),
("lefthook", "lefthook"),
("pre-commit.com", "pre-commit"),
("pre_commit", "pre-commit"),
]
.into_iter()
.find(|(needle, _)| text.contains(needle))?
.1;
Some(format!(
"{tool} wrote it: add the line where {tool} runs your hooks"
))
}
fn template_dir(root: &Path) -> Option<PathBuf> {
let dir = match std::env::var("GIT_TEMPLATE_DIR") {
Ok(dir) if !dir.is_empty() => dir,
_ => git_line(root, &["config", "--get", "init.templateDir"])
.ok()
.filter(|dir| !dir.is_empty())?,
};
Some(match dir.strip_prefix("~/") {
Some(rest) => PathBuf::from(std::env::var_os("HOME")?).join(rest),
None => PathBuf::from(dir),
})
}
fn refuse_foreign(root: &Path) -> Result<()> {
let foreign: Vec<String> = drift(root)?
.into_iter()
.filter_map(|(path, line)| {
let line = line?;
Some(match foreign_origin(root, &path) {
Some(origin) => format!(" {}: {origin}, `{line}`", path.display()),
None => format!(" {}: add `{line}` to it", path.display()),
})
})
.collect();
if !foreign.is_empty() {
bail!(
"another tool wrote these git hooks, so `silcrow install` leaves them, writes the others, and does not count them as installed. Silcrow does not read them: add the line to each to run Silcrow there, and let `silcrow check --all` in CI be the gate:\n{}",
foreign.join("\n")
);
}
Ok(())
}
pub fn main_checkout(root: &Path) -> Result<Option<PathBuf>> {
if !root.join(".git").is_file() {
return Ok(None);
}
let dirs = git_line(
root,
&[
"rev-parse",
"--path-format=absolute",
"--git-dir",
"--git-common-dir",
],
)?;
let Some((own, common)) = dirs.split_once('\n') else {
bail!(
"git rev-parse names no common git directory for {}",
root.display()
);
};
if own.trim() == common.trim() {
return Ok(None);
}
let list = git_line(root, &["worktree", "list", "--porcelain"])?;
let Some(main) = list
.lines()
.next()
.and_then(|line| line.strip_prefix("worktree "))
else {
bail!(
"git worktree list names no main checkout for {}",
root.display()
);
};
Ok(Some(PathBuf::from(main)))
}
pub fn install(root: &Path, dry_run: bool) -> Result<()> {
let Some(dir) = hooks_dir(root)? else {
return Ok(());
};
if let Some(main) = main_checkout(root)? {
eprintln!(
"install writes no git hook here: this is a linked worktree, which runs the hooks of the main checkout {}. Run `silcrow install` there to write them.",
main.display()
);
return Ok(());
}
for event in EVENTS {
let path = dir.join(event);
let HookState::Write(old) = hook_state(root, &path, event) else {
continue;
};
let body = script(root, event);
crate::harness::write_file(
root,
&path,
old.as_deref().unwrap_or_default(),
&body,
dry_run,
)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if !dry_run {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
}
}
}
refuse_foreign(root)
}
pub fn is_silcrow_repo(root: &Path) -> bool {
std::fs::read_to_string(root.join("Cargo.toml"))
.is_ok_and(|t| t.lines().any(|line| line.trim() == "name = \"silcrow\""))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dev_hook_script_uses_cargo_run() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("Cargo.toml"), "name = \"silcrow\"\n").unwrap();
let s = script(dir.path(), "pre-commit");
assert!(s.contains("cargo run -q -- hook pre-commit"));
}
#[test]
fn a_marker_line_inside_a_string_names_no_staged_id() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("src")).unwrap();
std::fs::write(
dir.path().join("src/a.rs"),
"fn f() {\n // § abcdefgh1.a\n let s = r\"\n// § abcdefgh2.a@aaaaa\n\";\n}\n",
)
.unwrap();
let ids = staged_law_ids(dir.path(), &[PathBuf::from("src/a.rs")]).unwrap();
assert_eq!(ids, vec!["abcdefgh1"]);
}
#[test]
fn a_pointer_counts_only_for_a_declared_id() {
let dir = tempfile::tempdir().unwrap();
assert!(crate::test_git()
.args(["init", "-q"])
.current_dir(dir.path())
.status()
.unwrap()
.success());
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(
dir.path().join("docs/decisions/a.md"),
"**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
)
.unwrap();
let ids = vec!["wxsgf68fh".to_string(), "abcdefgh1".to_string()];
assert_eq!(declared_only(dir.path(), ids).unwrap(), vec!["wxsgf68fh"]);
}
#[test]
fn remint_trailer_is_not_rewritten_when_already_present() {
let dir = tempfile::tempdir().unwrap();
let msg = dir.path().join("COMMIT_EDITMSG");
std::fs::write(&msg, "upgrade\n\nSilcrow-Op: remint\n").unwrap();
commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
let body = std::fs::read_to_string(&msg).unwrap();
assert_eq!(body.matches("Silcrow-Op: remint").count(), 1);
}
#[test]
fn commit_msg_records_the_scheme_and_no_impact_trailer() {
let dir = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
let out = crate::test_git()
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.current_dir(dir.path())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
};
git(&["init", "-q"]);
std::fs::create_dir_all(dir.path().join("docs/decisions")).unwrap();
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
std::fs::write(
dir.path().join("docs/decisions/a.md"),
"**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
)
.unwrap();
git(&["add", "."]);
let msg = dir.path().join("COMMIT_EDITMSG");
std::fs::write(&msg, "law\n").unwrap();
commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
assert_eq!(
std::fs::read_to_string(&msg).unwrap(),
format!("law\n\nSilcrow-Scheme: {}\n", crate::scheme::BINARY_VERSION)
);
}
#[test]
fn commit_msg_reads_the_index_and_marks_a_remint_only_when_it_travels_alone() {
let dir = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
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)
.current_dir(dir.path())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
};
let write = |rel: &str, text: &str| {
let path = dir.path().join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
let trailers = |msg: &str| {
let path = dir.path().join(".git/COMMIT_EDITMSG");
std::fs::write(&path, msg).unwrap();
commit_msg(dir.path(), &[path.to_string_lossy().into_owned()]).unwrap();
std::fs::read_to_string(&path).unwrap()[msg.len()..].to_string()
};
git(&["init", "-q"]);
write(
"AGENTS.md",
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
);
write(
"docs/decisions/a.md",
"**§ <a id=\"wxsgf68fh\">wxsgf68fh</a> The workload fails open.**\n",
);
git(&["add", "."]);
git(&["commit", "-q", "-m", "law"]);
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@aaaaa\n go();\n}\n",
);
git(&["add", "."]);
write("src/lib.rs", "fn f() {\n go();\n}\n");
let current = crate::scheme::BINARY_VERSION;
assert_eq!(trailers("code\n"), format!("\nSilcrow-Scheme: {current}\n"));
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@aaaaa\n go();\n}\n",
);
git(&["commit", "-q", "-m", "code\n\nSilcrow-Scheme: 1"]);
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@bbbbb\n go();\n}\n",
);
git(&["add", "."]);
assert_eq!(
trailers("remint\n"),
format!("\nSilcrow-Op: remint\nSilcrow-Scheme: {current}\n")
);
write(
"src/lib.rs",
"fn f() {\n // § wxsgf68fh@bbbbb\n stop();\n}\n",
);
git(&["add", "."]);
assert_eq!(trailers("edit\n"), format!("\nSilcrow-Scheme: {current}\n"));
}
#[test]
fn a_scheme_that_differs_from_the_record_is_a_remint() {
assert_eq!(
scheme_trailers(Some(4), 5, true, "upgrade\n"),
vec!["Silcrow-Op: remint", "Silcrow-Scheme: 5"]
);
assert_eq!(
scheme_trailers(Some(4), 5, false, "upgrade and edit\n"),
vec!["Silcrow-Scheme: 5"]
);
assert!(scheme_trailers(Some(5), 5, true, "edit\n").is_empty());
assert_eq!(
scheme_trailers(None, 5, false, "first\n"),
vec!["Silcrow-Scheme: 5"]
);
assert_eq!(
scheme_trailers(Some(4), 5, true, "upgrade\n\nSilcrow-Op: remint\n"),
vec!["Silcrow-Scheme: 5"]
);
assert!(scheme_trailers(Some(4), 5, true, "x\n\nSilcrow-Scheme: 4\n").is_empty());
}
#[test]
fn recorded_scheme_is_the_last_trailer_in_history() {
let dir = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
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)
.current_dir(dir.path())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
};
git(&["init", "-q"]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
git(&["commit", "-q", "--allow-empty", "-m", "start"]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
git(&[
"commit",
"-q",
"--allow-empty",
"-m",
"remint\n\nSilcrow-Op: remint\nSilcrow-Scheme: 4",
]);
git(&["commit", "-q", "--allow-empty", "-m", "edit"]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), Some(4));
git(&[
"commit",
"-q",
"--allow-empty",
"-m",
"remint\n\nSilcrow-Scheme: 5",
]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), Some(5));
}
fn scratch_git(dir: &Path) -> impl Fn(&[&str]) -> String + '_ {
move |args: &[&str]| {
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)
.current_dir(dir)
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
}
#[test]
fn commit_msg_writes_nothing_on_a_first_commit_that_names_no_law() {
let dir = tempfile::tempdir().unwrap();
let git = scratch_git(dir.path());
git(&["init", "-q"]);
std::fs::write(
dir.path().join("AGENTS.md"),
"<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n",
)
.unwrap();
git(&["add", "."]);
assert_eq!(recorded_scheme(dir.path()).unwrap(), None);
let msg = dir.path().join("COMMIT_EDITMSG");
std::fs::write(&msg, "first\n").unwrap();
commit_msg(dir.path(), &[msg.to_string_lossy().into_owned()]).unwrap();
assert_eq!(std::fs::read_to_string(&msg).unwrap(), "first\n");
}
#[test]
fn an_amend_is_compared_against_the_commit_it_replaced_not_a_stale_orig_head() {
let dir = tempfile::tempdir().unwrap();
let git = scratch_git(dir.path());
let write = |rel: &str, text: &str| {
let path = dir.path().join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
git(&["init", "-q"]);
write("a.md", "a\n");
git(&["add", "."]);
git(&["commit", "-q", "-m", "a"]);
write("b.md", "b\n");
git(&["add", "."]);
git(&["commit", "-q", "-m", "b"]);
git(&["reset", "-q", "--soft", "HEAD~1"]);
git(&["commit", "-q", "-m", "b again"]);
let replaced = git(&["rev-parse", "HEAD"]);
write("c.md", "c\n");
git(&["add", "."]);
git(&["commit", "-q", "--amend", "-m", "b and c"]);
let stale = git(&["rev-parse", "ORIG_HEAD"]);
assert_ne!(stale, replaced);
let new = git(&["rev-parse", "HEAD"]);
let stdin = format!("{replaced} {new}\n");
let before = rewritten_commit(dir.path(), Some("amend"), &mut stdin.as_bytes())
.unwrap()
.unwrap();
assert_eq!(before, replaced);
assert_eq!(
rewrite_changed_paths(dir.path(), &before).unwrap(),
BTreeSet::from([PathBuf::from("c.md")])
);
assert_eq!(
rewritten_commit(dir.path(), Some("rebase"), &mut "".as_bytes()).unwrap(),
Some(stale)
);
assert!(rewritten_commit(dir.path(), Some("amend"), &mut "".as_bytes()).is_err());
}
#[test]
fn a_script_silcrow_writes_is_ours_in_every_build_and_path() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let ours = script(root, "pre-commit");
assert!(is_ours(&ours, "pre-commit"));
assert!(!is_ours(&ours, "post-merge"));
assert!(is_ours(
"#!/bin/sh\nset -e\ncd '/x y' && exec cargo run -q -- hook pre-commit \"$@\"\n",
"pre-commit"
));
assert!(!is_ours(
"#!/bin/sh\nset -e\nexec silcrow hook pre-commit \"$@\"\nnpx lint-staged\n",
"pre-commit"
));
}
#[test]
fn select_genealogy_ids_uses_all_when_small() {
let live = vec![
("aaaaaaaab".into(), PathBuf::from("docs/decisions/a.md")),
("bbbbbbbbc".into(), PathBuf::from("docs/decisions/b.md")),
];
let changed = BTreeSet::from([PathBuf::from("docs/decisions/a.md")]);
let (ids, capped) = select_genealogy_ids(&live, &changed, 50);
assert_eq!(ids.len(), 2);
assert!(capped.is_none());
}
#[test]
fn select_genealogy_ids_samples_changed_when_large() {
let mut live = Vec::new();
for i in 0..60 {
live.push((
format!("id{i:07}"),
PathBuf::from(format!("docs/decisions/f{i}.md")),
));
}
let changed = BTreeSet::from([
PathBuf::from("docs/decisions/f0.md"),
PathBuf::from("docs/decisions/f59.md"),
]);
let (ids, capped) = select_genealogy_ids(&live, &changed, 50);
assert_eq!(ids.len(), 2);
assert!(ids.contains(&"id0000000".to_string()));
assert!(ids.contains(&"id0000059".to_string()));
let warning = capped.expect("a capped run warns");
assert!(warning.contains("GENEALOGY_CAP (50)"), "{warning}");
assert!(warning.contains("skipped 58"), "{warning}");
}
}