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 production_source(suffix: &str) -> String {
let hits: Vec<(String, String)> = source_files()
.into_iter()
.filter(|(p, _)| !is_test_path(p) && p.ends_with(suffix))
.collect();
assert!(
!hits.is_empty(),
"`{suffix}` names no production file — it was renamed, misspelled, or \
is now a test path (test sources are excluded here on purpose)"
);
assert_eq!(
hits.len(),
1,
"`{suffix}` names {} production files ({:?}) — a guard must name exactly one \
subject, so qualify the suffix with enough of its directory to be unique",
hits.len(),
hits.iter().map(|(p, _)| p).collect::<Vec<_>>()
);
production_half(&hits[0].1)
}
pub(crate) fn is_test_path(path: &str) -> bool {
path.contains("/tests/") || path.ends_with("/tests.rs") || path.ends_with("tests.rs")
}
pub(crate) fn tracked_files() -> Option<Vec<String>> {
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 None;
}
let files: Vec<String> = String::from_utf8_lossy(&out.stdout)
.lines()
.map(str::to_owned)
.collect();
assert!(
files.len() > 50,
"only {} tracked files — the listing failed and a guard over it \
would pass on an empty result",
files.len()
);
Some(files)
}
pub(crate) const AWS_DOC_ACCOUNT_IDS: &[&str] = &[
"123456789012",
"111122223333",
"444455556666",
"555555555555",
"777788889999",
];
pub(crate) fn account_id_candidates(text: &str) -> Vec<(usize, &str)> {
let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
let mut hits = Vec::new();
for (idx, line) in text.lines().enumerate() {
let bytes = line.as_bytes();
let mut i = 0;
while i < bytes.len() {
if !bytes[i].is_ascii_digit() {
i += 1;
continue;
}
let start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
let bounded = (start == 0 || !is_word(bytes[start - 1]))
&& (i == bytes.len() || !is_word(bytes[i]));
if i - start != 12 || !bounded {
continue;
}
let run = &line[start..i];
let repdigit = run.bytes().all(|b| b == run.as_bytes()[0]);
if !repdigit && !AWS_DOC_ACCOUNT_IDS.contains(&run) {
hits.push((idx + 1, run));
}
}
}
hits
}
pub(crate) const PROTECTED_NAMES_FILE: &str = ".protected-names";
pub(crate) const PROTECTED_NAMES_ENV: &str = "EBMAN_PROTECTED_NAMES";
const PROTECTED_NAME_MIN_LEN: usize = 4;
pub(crate) fn parse_protected_names(text: &str) -> Result<Vec<String>, String> {
let mut names: Vec<String> = Vec::new();
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
for part in line.split(',') {
let name = part.trim().to_lowercase();
if name.is_empty() {
continue;
}
if name.chars().count() < PROTECTED_NAME_MIN_LEN {
return Err(format!(
"a protected name is shorter than {PROTECTED_NAME_MIN_LEN} characters \
and would match inside ordinary words"
));
}
if !names.contains(&name) {
names.push(name);
}
}
}
Ok(names)
}
pub(crate) fn protected_name_hits(text: &str, names: &[String]) -> Vec<(usize, usize)> {
let mut hits = Vec::new();
for (idx, line) in text.lines().enumerate() {
let lower = line.to_lowercase();
for (k, name) in names.iter().enumerate() {
if lower.contains(name.as_str()) {
hits.push((idx + 1, k));
}
}
}
hits
}
pub(crate) fn protected_names() -> Vec<String> {
let mut text = std::env::var(PROTECTED_NAMES_ENV).unwrap_or_default();
if let Ok(local) = std::fs::read_to_string(PROTECTED_NAMES_FILE) {
text.push('\n');
text.push_str(&local);
}
parse_protected_names(&text).unwrap_or_else(|e| panic!("{e}"))
}
pub(crate) fn mask_account_id(id: &str) -> String {
match (id.get(..2), id.get(id.len().saturating_sub(2)..)) {
(Some(head), Some(tail)) if id.len() > 4 => format!("{head}…{tail}"),
_ => "…".to_owned(),
}
}
#[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 Some(files) = super::tracked_files() else {
return;
};
let bad: Vec<&str> = files
.iter()
.map(String::as_str)
.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:?}"
);
}
#[test]
fn no_published_file_carries_a_real_looking_account_id() {
let Some(files) = super::tracked_files() else {
return;
};
let mut scanned = 0usize;
let mut hits = Vec::new();
for path in &files {
let Ok(bytes) = std::fs::read(path) else {
continue;
};
scanned += 1;
let text = String::from_utf8_lossy(&bytes);
for (line, id) in super::account_id_candidates(&text) {
hits.push(format!("{path}:{line}: {}", super::mask_account_id(id)));
}
}
assert!(
scanned > 50,
"only {scanned} tracked files could be read — a scan over \
nothing passes vacuously"
);
assert!(
hits.is_empty(),
"these look like real AWS account IDs and would be published \
permanently in the crate: {hits:#?}\n\
Replace each with one of AWS's documentation placeholders \
({:?}) or a repdigit. Do NOT add it to the placeholder list: \
that list is AWS's, and widening it to quiet this guard is a \
stop condition in CLAUDE.md. If it is not an account ID at \
all, the detector is wrong for that shape — fix the detector.",
super::AWS_DOC_ACCOUNT_IDS
);
}
}
#[cfg(test)]
mod protected_names {
#[test]
fn no_tracked_file_names_a_protected_client() {
let Some(files) = super::tracked_files() else {
return;
};
assert!(
!files.iter().any(|f| f == super::PROTECTED_NAMES_FILE),
"{} is TRACKED — it would be published in the crate. \
`git rm --cached {}` and keep it local",
super::PROTECTED_NAMES_FILE,
super::PROTECTED_NAMES_FILE
);
let names = super::protected_names();
if names.is_empty() {
assert!(
std::env::var_os("CI").is_none(),
"CI has no protected-names list, so this guard would pass \
vacuously. Set the `{}` repository secret (and the \
Dependabot secret of the same name) and pass it to every \
job that runs `cargo test`",
super::PROTECTED_NAMES_ENV
);
return;
}
let mut hits = Vec::new();
for path in &files {
let Ok(bytes) = std::fs::read(path) else {
continue;
};
for (line, k) in super::protected_name_hits(&String::from_utf8_lossy(&bytes), &names) {
hits.push(format!("{path}:{line}: protected name #{}", k + 1));
}
}
assert!(
hits.is_empty(),
"these name a protected client and would be published \
permanently in the crate: {hits:#?}\n\
Use the `poly-*` placeholder convention, or \"a production \
fleet\" when citing real-world evidence."
);
}
use super::{parse_protected_names, protected_name_hits};
fn names(list: &str) -> Vec<String> {
parse_protected_names(list).expect("valid list")
}
#[test]
fn a_list_parses_lines_commas_comments_and_case() {
assert_eq!(
names("# clients\nZorblax\n\n quuxcorp , Wibbleco\nzorblax"),
vec!["zorblax", "quuxcorp", "wibbleco"]
);
}
#[test]
fn a_name_too_short_to_scan_for_is_an_error_not_a_skip() {
assert!(parse_protected_names("zorblax\nabc").is_err());
assert!(parse_protected_names("abcd").is_ok());
}
#[test]
fn a_name_is_found_inside_words_in_any_case() {
let list = names("zorblax");
let text = "fine\nZorblax-prod\nzORBLAX's setup\neval/zorblax_truth.txt\nfine";
assert_eq!(
protected_name_hits(text, &list),
vec![(2, 0), (3, 0), (4, 0)]
);
}
#[test]
fn nothing_is_found_when_no_name_is_present() {
assert!(protected_name_hits("poly-prod\npoly-batch", &names("zorblax")).is_empty());
}
#[test]
fn each_name_reports_its_own_position_in_the_list() {
let list = names("zorblax\nquuxcorp");
assert_eq!(protected_name_hits("QuuxCorp", &list), vec![(1, 1)]);
}
}
#[cfg(test)]
mod account_ids {
use super::{account_id_candidates, mask_account_id, AWS_DOC_ACCOUNT_IDS};
fn plausible() -> String {
["1234", "5678", "9013"].concat()
}
#[test]
fn a_bare_id_is_found_with_its_line() {
let id = plausible();
let text = format!("first line\naccount = {id}\nlast");
assert_eq!(account_id_candidates(&text), vec![(2, id.as_str())]);
}
#[test]
fn the_account_field_of_an_arn_is_found() {
let id = plausible();
let arn = format!("arn:aws:iam::{id}:role/deploy");
assert_eq!(account_id_candidates(&arn), vec![(1, id.as_str())]);
}
#[test]
fn a_candidate_at_either_end_of_a_line_is_found() {
let id = plausible();
assert_eq!(account_id_candidates(&id), vec![(1, id.as_str())]);
assert_eq!(
account_id_candidates(&format!("\"{id}\"")),
vec![(1, id.as_str())]
);
}
#[test]
fn aws_documentation_placeholders_are_not_candidates() {
for id in AWS_DOC_ACCOUNT_IDS {
let arn = format!("arn:aws:sts::{id}:assumed-role/x/y");
assert!(
account_id_candidates(&arn).is_empty(),
"{id} is an AWS documentation placeholder"
);
}
}
#[test]
fn repdigits_are_not_candidates() {
for d in '0'..='9' {
let rep: String = std::iter::repeat_n(d, 12).collect();
assert!(account_id_candidates(&rep).is_empty(), "{rep}");
}
}
#[test]
fn digits_inside_a_larger_word_are_not_candidates() {
let id = plausible();
for text in [
format!("checksum = \"ab{id}cd\""),
format!("{id}d"),
format!("x_{id}"),
format!("{id}_x"),
format!("{id}4"), format!("4{id}"), id[..11].to_string(), ] {
assert!(account_id_candidates(&text).is_empty(), "{text}");
}
}
#[test]
fn a_masked_id_locates_without_leaking() {
let id = plausible();
let masked = mask_account_id(&id);
assert_eq!(masked, "12…13");
assert!(!masked.contains(&id[2..10]));
}
#[test]
fn a_value_too_short_to_mask_reveals_nothing() {
for short in ["", "1", "1234"] {
assert_eq!(mask_account_id(short), "…", "{short:?}");
}
}
}
#[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 {
fn mod_decl(line: &str) -> Option<&str> {
let rest = line
.strip_prefix("pub(crate) ")
.or_else(|| line.strip_prefix("pub(super) "))
.or_else(|| line.strip_prefix("pub "))
.unwrap_or(line);
rest.starts_with("mod ").then_some(rest)
}
let lines: Vec<&str> = src.lines().collect();
let mut out = String::with_capacity(src.len());
let mut i = 0;
while i < lines.len() {
if lines[i].trim_end() != "#[cfg(test)]" {
out.push_str(lines[i]);
out.push('\n');
i += 1;
continue;
}
let mut j = i + 1;
if lines
.get(j)
.is_some_and(|l| l.trim_start().starts_with("#[path"))
{
j += 1;
}
let Some(decl) = lines.get(j).and_then(|l| mod_decl(l)) else {
out.push_str(lines[i]);
out.push('\n');
i += 1;
continue;
};
if decl.trim_end().ends_with(';') {
i = j + 1;
continue;
}
i = j + 1;
while i < lines.len() {
let closes = lines[i] == "}";
i += 1;
if closes {
break;
}
}
}
out
}
#[cfg(test)]
mod production_source_tests {
use super::*;
#[test]
fn locates_production_not_the_same_named_test_file() {
let src = production_source("cli/mcp/writes.rs");
assert!(
src.contains("pub(super) enum WriteVerb"),
"production writes.rs must carry the write verbs"
);
assert!(
!src.contains("#[test]"),
"the production half must not be the test file"
);
}
#[test]
#[should_panic(expected = "a guard must name exactly one subject")]
fn an_ambiguous_suffix_panics() {
let _ = production_source("mod.rs");
}
#[test]
#[should_panic(expected = "names no production file")]
fn a_missing_subject_panics() {
let _ = production_source("no-such-file-anywhere.rs");
}
}
#[cfg(test)]
mod production_half_tests {
#[test]
fn an_out_of_line_test_module_does_not_eat_what_follows() {
let src = "fn before() {\n}\n\n#[cfg(test)]\nmod tests;\n\n\
pub(crate) struct KeepMe {\n pub a: u8,\n}\n";
let prod = super::production_half(src);
assert!(prod.contains("fn before()"), "{prod}");
assert!(
prod.contains("pub(crate) struct KeepMe"),
"everything after an out-of-line declaration is production: {prod}"
);
assert!(!prod.contains("mod tests;"), "the declaration goes: {prod}");
}
#[test]
fn aws_rs_keeps_the_type_declared_after_its_test_module() {
let prod = super::production_source("aws.rs");
assert!(
prod.contains("pub(crate) struct AwsErrorMeta"),
"`AwsErrorMeta` is declared after `mod tests;` in aws.rs and must \
survive the split"
);
}
#[test]
fn a_path_attributed_test_module_is_excised() {
let src = "fn before() {\n}\n\n#[cfg(test)]\n#[path = \"tests/x.rs\"]\nmod tests;\n\n\
fn after() {\n}\n";
let prod = super::production_half(src);
assert!(prod.contains("fn before()"));
assert!(prod.contains("fn after()"), "{prod}");
assert!(!prod.contains("#[path"), "the declaration goes: {prod}");
assert!(!prod.contains("mod tests;"), "{prod}");
}
#[test]
fn a_visibility_qualified_test_module_is_excised() {
let src = "fn before() {\n}\n\n#[cfg(test)]\npub(crate) mod tests;\n\nfn after() {\n}\n";
let prod = super::production_half(src);
assert!(prod.contains("fn after()"), "{prod}");
assert!(!prod.contains("mod tests;"), "{prod}");
}
#[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"
);
}
}
}