crates/knut-tracing/tests/no_phantom_guard_citations.rs
//! **A cited guard must exist.**
//!
//! Comments across this repo justify code by naming the test that covers it —
//! *"(Integration tests against a live FalkorDB instance live in the integration
//! test file.)"*. That sentence is load-bearing: a reader who sees it stops
//! looking for coverage. When the named file does not exist, the comment is a
//! **phantom guard** — and a pointer to an imaginary guard is *indistinguishable
//! from a real one*. It reads as green.
//!
//! That exact citation was live in `crates/graphar-falkordb/src/tests.rs`, naming
//! an integration-test file that has never existed in this repo (the real one is
//! `tests/integration_falkordb.rs`), and it sat directly above a `#[tokio::test]`
//! whose name promised query verification and whose body asserted only that its own
//! fixture had three rows. Two layers of "covered" over nothing.
//!
//! Both the quote above and the placeholder below are written WITHOUT the dead
//! path they describe, on purpose: this guard reads its own source, and it cannot
//! tell a post-mortem from a claim. It is right not to try — the alternative is a
//! rule with an exception for prose, which is a rule that stops holding.
//!
//! ## What this checks
//!
//! Every repo-relative path to a test/source file mentioned **in a comment** must
//! resolve to a tracked file — relative to the citing crate, or to the workspace
//! root, or as a unique path suffix.
//!
//! ## Deliberate limits (so a failure here is always real)
//!
//! * **Comments only.** String literals are skipped: a call that passes a test
//! file's name to a parser as a *fixture* does not claim that file exists.
//! (That distinction is what makes this guard quiet enough to keep.)
//! Unlike the shared `nornir_testmatrix::audit_citations`, this local copy has
//! no placeholder-stem rule, so even `tests/<placeholder>.rs` in prose would
//! red here — one more reason it should become a call to the shared audit.
//! * **Repo-relative only.** A citation is considered only when its first segment
//! is one of this workspace's own top-level dirs. `facett-demo/tests/robot_demo.rs`
//! names another repo and is none of our business.
//! * No network, no cargo metadata, no dev-dependency: `git ls-files` plus std.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
/// A citation is ours to check only if it starts with one of these. Everything
/// else is another repo (or a URL path) and is skipped rather than guessed at.
const OURS: [&str; 5] = ["tests", "src", "crates", "xtask", "benches"];
/// Extensions we treat as "a file a comment can cite as coverage".
const CITED_EXT: [&str; 6] = ["rs", "py", "js", "ts", "go", "sh"];
fn repo_root() -> PathBuf {
// crates/knut-tracing/ -> workspace root
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(Path::parent)
.unwrap()
.to_path_buf()
}
fn tracked(root: &Path) -> Vec<String> {
let out = Command::new("git")
.arg("-C")
.arg(root)
.arg("ls-files")
.output()
.expect("git ls-files must run — this guard needs the tracked file list");
assert!(
out.status.success(),
"git ls-files failed in {}",
root.display()
);
String::from_utf8(out.stdout)
.expect("git ls-files output must be utf-8")
.lines()
.map(str::to_string)
.collect()
}
/// Everything that is a comment in a `.rs` file, with string literals removed so
/// a fixture NAME passed as an argument is never mistaken for a claim of coverage.
fn rust_comments(src: &str) -> String {
let b = src.as_bytes();
let (mut i, mut out) = (0usize, String::with_capacity(src.len() / 4));
let (mut in_str, mut in_raw, mut esc) = (false, false, false);
while i < b.len() {
let c = b[i] as char;
if in_str {
if in_raw {
if c == '"' {
in_str = false;
in_raw = false;
}
} else if esc {
esc = false;
} else if c == '\\' {
esc = true;
} else if c == '"' {
in_str = false;
}
i += 1;
continue;
}
// r"..." / r#"..."# — treat as an opaque string too
if c == 'r' && i + 1 < b.len() && (b[i + 1] == b'"' || b[i + 1] == b'#') {
let mut j = i + 1;
while j < b.len() && b[j] == b'#' {
j += 1;
}
if j < b.len() && b[j] == b'"' {
in_str = true;
in_raw = true;
i = j + 1;
continue;
}
}
if c == '"' {
in_str = true;
i += 1;
continue;
}
if c == '/' && i + 1 < b.len() && b[i + 1] == b'/' {
let end = src[i..].find('\n').map(|n| i + n).unwrap_or(b.len());
out.push_str(&src[i..end]);
out.push('\n');
i = end;
continue;
}
if c == '/' && i + 1 < b.len() && b[i + 1] == b'*' {
let end = src[i + 2..]
.find("*/")
.map(|n| i + 2 + n + 2)
.unwrap_or(b.len());
out.push_str(&src[i..end]);
out.push('\n');
i = end;
continue;
}
i += 1;
}
out
}
/// Pull `a/b/c.rs`-shaped tokens out of prose.
fn citations(text: &str) -> BTreeSet<String> {
let mut found = BTreeSet::new();
let ok = |c: char| c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | '/');
for raw in text.split(|c: char| !ok(c)) {
let tok = raw.trim_matches(|c| c == '.' || c == '/');
if !tok.contains('/') || tok.contains("..") {
continue;
}
let Some((_, ext)) = tok.rsplit_once('.') else {
continue;
};
if !CITED_EXT.contains(&ext) {
continue;
}
let first = tok.split('/').next().unwrap_or("");
if !OURS.contains(&first) {
continue; // another repo, or a URL path
}
found.insert(tok.to_string());
}
found
}
/// The crate directory a file belongs to (nearest ancestor holding a Cargo.toml).
fn crate_dir_of(root: &Path, file: &str) -> Option<String> {
let mut cur = Path::new(file).parent()?;
loop {
if root.join(cur).join("Cargo.toml").is_file() {
let s = cur.to_string_lossy().to_string();
return Some(if s.is_empty() { s } else { format!("{s}/") });
}
cur = cur.parent()?;
}
}
fn resolves(cit: &str, citing: &str, root: &Path, files: &BTreeSet<String>) -> bool {
if files.contains(cit) {
return true; // workspace-root-relative
}
if let Some(dir) = crate_dir_of(root, citing) {
if files.contains(&format!("{dir}{cit}")) {
return true; // relative to the citing crate
}
}
let suffix = format!("/{cit}");
files.iter().any(|f| f.ends_with(&suffix))
}
#[test]
fn every_cited_test_file_exists() {
let root = repo_root();
let all = tracked(&root);
let files: BTreeSet<String> = all.iter().cloned().collect();
let mut phantoms: Vec<String> = Vec::new();
let mut checked = 0usize;
for f in &all {
if f.starts_with("vendor/") {
continue; // not ours to fix
}
let is_rs = f.ends_with(".rs");
let is_prose = f.ends_with(".md") || f.ends_with(".proto");
if !is_rs && !is_prose {
continue;
}
let Ok(src) = std::fs::read_to_string(root.join(f)) else {
continue;
};
let text = if is_rs { rust_comments(&src) } else { src };
for cit in citations(&text) {
checked += 1;
if !resolves(&cit, f, &root, &files) {
phantoms.push(format!(" {f} cites {cit} — NO SUCH FILE"));
}
}
}
assert!(
checked > 0,
"the scanner found zero citations anywhere — it is broken, not the repo clean"
);
assert!(
phantoms.is_empty(),
"PHANTOM GUARD CITATIONS — a comment names a test file that does not exist.\n\
A pointer to an imaginary guard reads exactly like a real one; a reader who \n\
sees it stops looking for coverage.\n\
Fix the path, or delete the claim.\n\n{}\n\n({checked} citations checked)",
phantoms.join("\n")
);
}