#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::manual_assert
)]
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
fn find_repo_root() -> PathBuf {
let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
loop {
if dir.join("Cargo.toml").exists() && dir.join("LICENSE").exists() {
if let Ok(text) = fs::read_to_string(dir.join("Cargo.toml")) {
if text.contains("[workspace]") {
return dir;
}
}
}
if !dir.pop() {
panic!("could not find Mimir repo root walking up from CARGO_MANIFEST_DIR");
}
}
}
fn read_workspace_version(repo_root: &Path) -> String {
let cargo_toml = repo_root.join("Cargo.toml");
let text = fs::read_to_string(&cargo_toml)
.unwrap_or_else(|e| panic!("read {}: {e}", cargo_toml.display()));
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("version") {
if let Some(eq_pos) = rest.find('=') {
let value = rest[eq_pos + 1..].trim();
if let Some(unquoted) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
return unquoted.to_string();
}
}
}
}
panic!(
"could not find `version = \"...\"` in {}",
cargo_toml.display()
);
}
fn parse_major(version: &str) -> Option<u64> {
version.split('.').next()?.parse::<u64>().ok()
}
#[test]
fn status_banner_consistency() {
let repo_root = find_repo_root();
let concepts = repo_root.join("docs").join("concepts");
let entries =
fs::read_dir(&concepts).unwrap_or_else(|e| panic!("read {}: {e}", concepts.display()));
let version = read_workspace_version(&repo_root);
let major = parse_major(&version);
let stable_required = major.unwrap_or(0) >= 1;
let mut violations: Vec<String> = Vec::new();
let mut spec_count = 0;
for entry in entries {
let entry = entry.expect("dir entry");
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("md") {
continue;
}
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("?");
if name.eq_ignore_ascii_case("README.md") {
continue;
}
spec_count += 1;
let text =
fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
let state = parse_status_banner(&text);
match state {
None => {
violations.push(format!(
"{name}: missing or unparseable `> **Status: <state>` banner \
in the first paragraph"
));
}
Some(s) if stable_required && s != "authoritative" => {
violations.push(format!(
"{name}: status `{s}` (project version {version} is stable; \
every spec must be `authoritative`)"
));
}
Some(_) => { }
}
}
assert!(
spec_count > 0,
"no docs/concepts/*.md specs found at {} — directory layout regressed?",
concepts.display()
);
assert!(
violations.is_empty(),
"status banner drift detected ({} violations across {} specs):\n - {}",
violations.len(),
spec_count,
violations.join("\n - "),
);
}
fn parse_status_banner(text: &str) -> Option<String> {
let needle = "Status:";
for line in text.lines().take(20) {
let trimmed = line.trim_start();
if !trimmed.starts_with('>') {
continue;
}
if let Some(idx) = trimmed.find(needle) {
let after = &trimmed[idx + needle.len()..];
let state = after
.trim_start()
.split(|c: char| c.is_whitespace() || c == '*' || c == '.' || c == ',')
.find(|s| !s.is_empty())?
.trim_matches('—');
if state.is_empty() {
return None;
}
return Some(state.to_string());
}
}
None
}
#[test]
fn readme_no_design_phase_lies() {
let repo_root = find_repo_root();
let readme = repo_root.join("README.md");
let text =
fs::read_to_string(&readme).unwrap_or_else(|e| panic!("read {}: {e}", readme.display()));
let total_lines = count_rust_loc_in_crates(&repo_root);
if total_lines < 500 {
return;
}
let forbidden = [
"no production code yet",
"to be authored",
"private while it is design-phase",
];
let lowered = text.to_lowercase();
let mut hits: Vec<&str> = Vec::new();
for needle in forbidden {
if lowered.contains(needle) {
hits.push(needle);
}
}
assert!(
hits.is_empty(),
"README.md contains stale design-phase claim(s) — the v1.1 fresh-assessment doc \
finding F1 ('the single biggest onboarding blocker' the audit identified) has \
regressed.\nForbidden phrases found: {hits:?}\nCrates currently contain {total_lines} \
lines of Rust source — the project is past design phase."
);
}
fn count_rust_loc_in_crates(repo_root: &Path) -> usize {
let crates_dir = repo_root.join("crates");
let mut total: usize = 0;
walk_rs_files(&crates_dir, &mut |path| {
if path.components().any(|c| c.as_os_str() == "target") {
return;
}
if let Ok(text) = fs::read_to_string(path) {
total += text.lines().count();
}
});
total
}
fn walk_rs_files(dir: &Path, visit: &mut impl FnMut(&Path)) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
walk_rs_files(&path, visit);
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
visit(&path);
}
}
}
#[test]
fn version_consistency() {
let repo_root = find_repo_root();
let cargo_version = read_workspace_version(&repo_root);
let output = Command::new("git")
.arg("-C")
.arg(&repo_root)
.arg("describe")
.arg("--tags")
.arg("--abbrev=0")
.output();
let Ok(out) = output else {
return;
};
if !out.status.success() {
return;
}
let tag = String::from_utf8_lossy(&out.stdout).trim().to_string();
let tag_version = tag.strip_prefix('v').unwrap_or(&tag);
assert_eq!(
tag_version, cargo_version,
"Cargo workspace version `{cargo_version}` does not match latest git tag \
`{tag}`. Bump `Cargo.toml [workspace.package].version` and the tag in lockstep \
(the release pipeline at `.github/workflows/release.yml` enforces this same \
invariant on tag push — local enforcement here catches drift before push)."
);
}
#[test]
fn agents_md_table_consistency() {
let repo_root = find_repo_root();
let agents = repo_root.join("AGENTS.md");
let text =
fs::read_to_string(&agents).unwrap_or_else(|e| panic!("read {}: {e}", agents.display()));
let mut violations: Vec<String> = Vec::new();
for (line_no, line) in text.lines().enumerate() {
let trimmed = line.trim();
if !trimmed.starts_with('|') {
continue;
}
let mut search = trimmed;
while let Some(start) = search.find("`docs/") {
let after = &search[start + 1..]; let Some(end) = after.find('`') else {
break;
};
let path_str = &after[..end];
let cleaned = path_str.trim_end_matches('/');
let path = repo_root.join(cleaned);
if path.exists() {
let exists_with_content = if path.is_file() {
fs::metadata(&path).map(|m| m.len() > 64).unwrap_or(false)
} else if path.is_dir() {
fs::read_dir(&path)
.map(|mut d| d.next().is_some())
.unwrap_or(false)
} else {
false
};
if exists_with_content && trimmed.contains("to be authored") {
violations.push(format!(
"AGENTS.md:{} — row references `{}` (which exists with content) \
but says \"to be authored\". Update the row to reflect the \
file's actual status.",
line_no + 1,
cleaned,
));
}
}
search = &after[end + 1..];
}
}
assert!(
violations.is_empty(),
"AGENTS.md `Where to Look` table drift — auto-ingested by every coding-agent \
client (Claude Code, Cursor, Codex, Copilot, Gemini CLI), so stale \"to be \
authored\" entries actively misdirect agents that look at AGENTS.md before \
exploring the spec corpus.\nViolations:\n - {}",
violations.join("\n - "),
);
}
#[test]
fn internal_workspace_dep_versions_consistency() {
let repo_root = find_repo_root();
let workspace_version = read_workspace_version(&repo_root);
for internal_dep in &["mimir-core", "mimir-cli", "mimir-librarian"] {
let dep_version = read_workspace_dep_version(&repo_root, internal_dep)
.unwrap_or_else(|err| panic!("workspace dep `{internal_dep}`: {err}"));
let bare = dep_version.trim_start_matches('=');
assert_eq!(
bare, workspace_version,
"[workspace.dependencies] `{internal_dep}` version `{dep_version}` does not \
match [workspace.package].version `{workspace_version}`. The two must move in \
lockstep — on every workspace version bump, also update each internal dep pin \
under [workspace.dependencies] in the same commit (the `=` exact-match prefix \
is intentional; mimir_core / mimir-cli / mimir-mcp are co-released)."
);
}
}
fn read_workspace_dep_version(repo_root: &Path, dep_name: &str) -> Result<String, String> {
let cargo_toml = repo_root.join("Cargo.toml");
let text = fs::read_to_string(&cargo_toml)
.map_err(|e| format!("read {}: {e}", cargo_toml.display()))?;
let mut in_block = false;
for line in text.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_block = trimmed == "[workspace.dependencies]";
continue;
}
if !in_block {
continue;
}
if let Some(rest) = trimmed.strip_prefix(dep_name) {
if !rest.starts_with([' ', '=']) {
continue;
}
let rest = rest.trim_start_matches([' ', '=']).trim();
if let Some(idx) = rest.find("version") {
let after = &rest[idx + "version".len()..];
let after = after.trim_start_matches([' ', '=']).trim();
if let Some(quoted) = after.strip_prefix('"') {
if let Some(end) = quoted.find('"') {
return Ok(quoted[..end].to_string());
}
}
}
return Err(format!(
"found `{dep_name}` in [workspace.dependencies] but no `version = \"...\"` field"
));
}
}
Err(format!(
"could not find `{dep_name}` in [workspace.dependencies]; expected an entry of the \
form `{dep_name} = {{ path = \"...\", version = \"=X.Y.Z\" }}`"
))
}