pub(crate) fn strip_line_comment(line: &str) -> &str {
let b = line.as_bytes();
let mut i = 0;
let mut in_str = false;
let mut in_char = false;
while i < b.len() {
match b[i] {
b'\\' if in_str || in_char => {
i += 2;
continue;
}
b'"' if !in_char => in_str = !in_str,
b'\'' if !in_str => {
let looks_like_char = b.get(i + 1) == Some(&b'\\')
|| (b.get(i + 2) == Some(&b'\'') && b.get(i + 1).is_some());
if in_char || looks_like_char {
in_char = !in_char;
}
}
b'/' if !in_str && !in_char && b.get(i + 1) == Some(&b'/') => {
return &line[..i];
}
_ => {}
}
i += 1;
}
line
}
pub(crate) fn source_files() -> Vec<(String, String)> {
fn walk(dir: &std::path::Path, out: &mut Vec<(String, String)>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
walk(&p, out);
} else if p.extension().is_some_and(|x| x == "rs") {
if let Ok(s) = std::fs::read_to_string(&p) {
out.push((p.to_string_lossy().into_owned(), s));
}
}
}
}
let mut out = Vec::new();
walk(std::path::Path::new("src"), &mut out);
assert!(
out.len() > 50,
"source walk found only {} files — the walk is broken, and a guard \
over nothing passes vacuously",
out.len()
);
out
}
pub(crate) fn find_in_production(needle: &str) -> Vec<String> {
let mut hits = Vec::new();
for (path, text) in source_files() {
if is_test_path(&path) {
continue;
}
for (n, line) in text.lines().enumerate() {
if strip_line_comment(line).contains(needle) {
hits.push(format!("{path}:{}", n + 1));
}
}
}
hits
}
pub(crate) fn is_test_path(path: &str) -> bool {
path.contains("/tests/") || path.ends_with("/tests.rs") || path.ends_with("tests.rs")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_url_literal_does_not_truncate_the_line() {
let line = r#" Some(format!("https://{}", host)) "#;
assert_eq!(
strip_line_comment(line),
line,
"a `//` inside a string literal is not a comment"
);
}
#[test]
fn a_real_comment_is_stripped() {
assert_eq!(strip_line_comment("let x = 1; // set x"), "let x = 1; ");
assert_eq!(strip_line_comment("// whole line"), "");
}
#[test]
fn code_after_a_url_literal_survives() {
let line = r#"let u = "https://x"; let c = arboard::Clipboard::new();"#;
assert!(
strip_line_comment(line).contains("arboard::Clipboard"),
"code after a URL literal must remain visible to the guards"
);
}
#[test]
fn a_comment_after_a_literal_is_still_stripped() {
let line = r#"let u = "https://x"; // trailing note"#;
let code = strip_line_comment(line);
assert!(code.contains("https://x"));
assert!(!code.contains("trailing note"));
}
#[test]
fn escaped_quotes_and_lifetimes_do_not_confuse_it() {
let line = r#"let s = "a \" b"; // c"#;
assert!(!strip_line_comment(line).contains("c"));
let lt = "fn f<'a>(x: &'a str) -> &'a str { x } // note";
let code = strip_line_comment(lt);
assert!(code.contains("&'a str"), "a lifetime is not a char literal");
assert!(!code.contains("note"));
}
#[test]
fn the_walk_finds_the_tree() {
let files = source_files();
assert!(files.iter().any(|(p, _)| p.ends_with("util.rs")));
}
#[test]
fn the_detector_finds_something_that_is_there() {
let hits = find_in_production("arboard::");
assert!(
!hits.is_empty(),
"the detector found no `arboard::` anywhere — it is not detecting"
);
assert!(
hits.iter().all(|h| !h.contains("/tests/")),
"test sources must be excluded: {hits:?}"
);
}
#[test]
fn the_detector_finds_nothing_that_is_not_there() {
assert!(find_in_production("ThisIdentifierDoesNotExistAnywhere").is_empty());
}
#[test]
fn test_paths_are_recognised() {
assert!(is_test_path("src/app/tests/safety.rs"));
assert!(is_test_path("src/app/tests.rs"));
assert!(!is_test_path("src/app/safety.rs"));
assert!(!is_test_path("src/util.rs"));
}
}
#[cfg(test)]
mod packaging {
#[test]
fn no_backup_or_scratch_files_are_tracked() {
let out = match std::process::Command::new("git")
.args(["ls-files"])
.env("LC_ALL", "C")
.output()
{
Ok(out) => out,
Err(e) => panic!("could not run git: {e}"),
};
if !out.status.success() {
let no_repo = String::from_utf8_lossy(&out.stderr).contains("not a git repository");
assert!(
no_repo,
"git ls-files failed for a reason other than a missing \
repository: {}",
String::from_utf8_lossy(&out.stderr)
);
return;
}
let files = String::from_utf8_lossy(&out.stdout);
assert!(
files.lines().count() > 50,
"only {} tracked files — the listing failed and this guard \
would pass on an empty result",
files.lines().count()
);
let bad: Vec<&str> = files
.lines()
.filter(|f| {
f.ends_with(".bak")
|| f.ends_with(".orig")
|| f.ends_with(".rej")
|| f.ends_with('~')
|| f.contains("mutants.out/")
})
.collect();
assert!(
bad.is_empty(),
"these are tracked and would be published in the crate \
tarball: {bad:?}"
);
}
}
#[cfg(test)]
mod write_gate_convergence {
const ALLOWED: &[&str] = &["src/write_gate.rs", "src/app/safety.rs", "src/cli/mod.rs"];
fn offenders_among(hits: &[String]) -> Vec<String> {
hits.iter()
.filter(|hit| !ALLOWED.iter().any(|a| hit.starts_with(a)))
.cloned()
.collect()
}
#[test]
fn only_the_gates_consult_the_shared_decision() {
let offenders = offenders_among(&super::find_in_production("write_gate::"));
assert!(
offenders.is_empty(),
"these reach the shared write decision directly instead of \
going through `deny_write` / `write_refusal`, which is how \
the two gates diverged in the first place: {offenders:?}"
);
}
#[test]
fn the_convergence_guard_detects_what_it_looks_for() {
assert!(
super::strip_line_comment("let d = crate::write_gate::decide(&ctx);")
.contains("write_gate::")
);
assert!(
!super::strip_line_comment("// write_gate::decide is fine in a comment")
.contains("write_gate::")
);
assert!(
!super::strip_line_comment("if self.deny_write(&env, \"rollback\") {")
.contains("write_gate::")
);
assert!(
!super::find_in_production("write_gate::").is_empty(),
"no production code references write_gate at all — the scan \
has gone blind"
);
assert_eq!(
offenders_among(&["src/app/cmd_ops.rs:12".to_string()]).len(),
1,
"a path outside the allowlist must be flagged"
);
for ok in ALLOWED {
assert!(
offenders_among(&[format!("{ok}:1")]).is_empty(),
"{ok} is a gate and must not be flagged"
);
}
}
}
pub(crate) fn production_half(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut lines = src.lines().peekable();
while let Some(line) = lines.next() {
let opens_test_mod = line.trim_end() == "#[cfg(test)]"
&& lines.peek().is_some_and(|n| n.starts_with("mod "));
if !opens_test_mod {
out.push_str(line);
out.push('\n');
continue;
}
for body in lines.by_ref() {
if body == "}" {
break;
}
}
}
out
}
#[cfg(test)]
mod production_half_tests {
#[test]
fn an_inline_test_item_does_not_end_the_production_half() {
let src = "fn a() {}\n\
#[cfg(test)]\n\
fn only_for_tests() {}\n\
fn b() {}\n";
let prod = super::production_half(src);
assert!(prod.contains("fn a()"), "{prod}");
assert!(
prod.contains("fn b()"),
"an inline `#[cfg(test)]` item is ONE declaration, not a boundary — \
stopping there is what hid two thirds of three files: {prod}"
);
}
#[test]
fn a_test_module_is_excised_and_code_after_it_survives() {
let src = "fn a() {}\n\
#[cfg(test)]\n\
mod tests {\n\
fn hidden() {}\n\
}\n\
fn b() {}\n";
let prod = super::production_half(src);
assert!(prod.contains("fn a()"));
assert!(
!prod.contains("fn hidden()"),
"the module body is test-only and must not be scanned: {prod}"
);
assert!(
prod.contains("fn b()"),
"production code AFTER a test module survives — `cli/mod.rs` has some, \
so anything treating this as a prefix loses it: {prod}"
);
}
#[test]
fn a_brace_inside_a_string_does_not_end_the_module() {
let src = "fn a() {}\n\
#[cfg(test)]\n\
mod tests {\n\
let s = \"{{\\\"pending\\\":true}}\";\n\
fn hidden() {}\n\
}\n\
fn b() {}\n";
let prod = super::production_half(src);
assert!(
!prod.contains("fn hidden()"),
"a `{{` in a format string must not close the module early — this \
codebase is full of them: {prod}"
);
assert!(prod.contains("fn b()"), "{prod}");
}
#[test]
fn the_real_sources_keep_their_production_code() {
for (path, needle) in [
("src/cli/mcp/mod.rs", "fn call_timeout_secs"),
("src/cli/mcp/writes.rs", "fn dispatch_dlq_batch"),
("src/cli/mcp/tools.rs", "fn tool_doctor"),
] {
let src = std::fs::read_to_string(path).expect("read");
let prod = super::production_half(&src);
assert!(
prod.contains(needle),
"`{needle}` is production code in {path} and a guard scanning it \
must see it — the old splitter did not"
);
assert!(
!prod.contains("#[tokio::test]"),
"{path}: test bodies must be excised"
);
}
}
}