Skip to main content

testing_conventions/
lib.rs

1pub mod agents;
2pub mod co_change;
3pub mod colocated_test;
4pub mod config;
5pub mod coverage;
6pub mod e2e;
7pub mod isolation;
8pub mod lint;
9pub mod mutation;
10pub mod packaging;
11pub mod patch_coverage;
12pub mod ts;
13pub mod violation;
14pub mod workflow;
15
16use std::path::{Path, PathBuf};
17
18use clap::{CommandFactory, Parser, Subcommand};
19
20#[derive(Parser, Debug)]
21#[command(
22    name = "testing-conventions",
23    version,
24    about = "Enforce testing conventions in libraries (Python, TypeScript, and Rust).",
25    long_about = None,
26)]
27pub struct Cli {
28    #[command(subcommand)]
29    command: Option<Command>,
30}
31
32#[derive(Subcommand, Debug)]
33enum Command {
34    /// Check the repository against its testing-conventions config.
35    Check,
36    /// Write the testing contract into the repository's agent context file
37    /// (#232): a marker-delimited, hash-versioned block in `AGENTS.md` that a
38    /// coding agent reads before writing code. Idempotent — re-running
39    /// refreshes the owned region and touches nothing outside it.
40    Install {
41        /// The agent context file to manage.
42        #[arg(default_value = "AGENTS.md")]
43        path: PathBuf,
44    },
45    /// Unit-test conventions.
46    Unit {
47        #[command(subcommand)]
48        rule: UnitRule,
49    },
50    /// Integration-test conventions.
51    Integration {
52        #[command(subcommand)]
53        rule: IntegrationRule,
54    },
55    /// Packaging conventions: test files must not ship in the built artifact.
56    Packaging {
57        /// Root of the built artifact to inspect (e.g. an unpacked wheel or `dist/`).
58        path: PathBuf,
59        /// Language convention to enforce (required).
60        #[arg(long, value_enum)]
61        language: colocated_test::Language,
62    },
63    /// Workflow guard (private — hidden from `--help`, #191): every `testing-conventions`
64    /// invocation in a CI workflow must name a subcommand this binary still exposes
65    /// (guards the `@v0` path, #92). Run from our own CI, not a documented consumer command;
66    /// it stays in the binary because the guard needs the in-process command tree.
67    #[command(hide = true)]
68    Workflow {
69        /// Workflow file (or a directory of them) to scan.
70        path: PathBuf,
71    },
72    /// End-to-end-test conventions.
73    E2e {
74        #[command(subcommand)]
75        command: E2eCommand,
76    },
77}
78
79/// Rules enforced on the unit-test suite (the README's "Unit" taxonomy).
80#[derive(Subcommand, Debug)]
81enum UnitRule {
82    /// Check that every source file has a colocated, matching-named unit test
83    /// (tree-wide presence). With `--base`, additionally run the commit-scoped
84    /// `co-change` check over `<base>...HEAD` (#33): a modified or deleted source
85    /// whose colocated test is not in the diff fails. Presence always runs;
86    /// `--base` *adds* the diff-scoped check.
87    ColocatedTest {
88        /// Directory to scan recursively.
89        path: PathBuf,
90        /// Language convention to enforce (required).
91        #[arg(long, value_enum)]
92        language: colocated_test::Language,
93        /// Opt-in commit-scoped co-change check (#33): diff `<base>...HEAD` and
94        /// also flag a modified or deleted source whose colocated test didn't
95        /// co-change. Absent means presence-only — there is no default. Python /
96        /// TypeScript only: `--base --language rust` is rejected (inline
97        /// `#[cfg(test)]` units have no sibling test to go stale).
98        #[arg(long)]
99        base: Option<String>,
100        /// testing-conventions config file providing the `exempt` list. Optional:
101        /// if the file is absent, no files are exempt.
102        #[arg(long, default_value = "testing-conventions.toml")]
103        config: PathBuf,
104    },
105    /// Check that the unit suite meets the configured coverage floor. With
106    /// `--base`, the same configured floor is measured over the `<base>...HEAD`
107    /// diff (the changed lines) instead of the whole tree (#162) — a changed line
108    /// below the floor fails, no matter how small the diff.
109    Coverage {
110        /// Directory whose unit suite is run and measured.
111        path: PathBuf,
112        /// Language convention to enforce (required).
113        #[arg(long, value_enum)]
114        language: colocated_test::Language,
115        /// Opt-in diff-scoped coverage (#162): diff `<base>...HEAD` and measure the
116        /// configured floor over only the changed lines, instead of the whole tree.
117        /// Absent means whole-tree — there is no default. This is the patch-scoped
118        /// check the old `unit patch-coverage` command did, re-homed onto the floor
119        /// it shares.
120        #[arg(long)]
121        base: Option<String>,
122        /// testing-conventions config file with the coverage thresholds and
123        /// `exempt` list. Optional: if the file — or its `[<language>].coverage`
124        /// table — is absent, the language's sane default floor is used and
125        /// nothing is exempt.
126        #[arg(long, default_value = "testing-conventions.toml")]
127        config: PathBuf,
128    },
129    /// Lint unit test files for isolation: mock every collaborator (Python, TypeScript, Rust).
130    Lint {
131        /// Crate root / source dir to scan recursively.
132        path: PathBuf,
133        /// Language convention to enforce (required).
134        #[arg(long, value_enum)]
135        language: isolation::Language,
136        /// testing-conventions config file providing the `exempt` list (waivers).
137        /// Optional: if the file is absent, nothing is waived.
138        #[arg(long, default_value = "testing-conventions.toml")]
139        config: PathBuf,
140    },
141    /// Run mutation testing over the unit suite and fail on any surviving mutant not
142    /// lifted by a `mutation` exemption — the rung above coverage (#201). The gate is
143    /// on by default (no report-only mode). All three languages (Python, TypeScript,
144    /// Rust) are at parity and wired into the reusable workflow as a diff-scoped,
145    /// PR-only job (#204).
146    Mutation {
147        /// Crate whose unit suite is mutated.
148        path: PathBuf,
149        /// Language convention to enforce (required): `python`, `typescript`, or `rust`.
150        #[arg(long, value_enum)]
151        language: colocated_test::Language,
152        /// Opt-in diff-scoping (#201): restrict to mutants on lines a `<base>...HEAD`
153        /// diff added or modified, via cargo-mutants' `--in-diff`. Absent means the
154        /// whole crate (slower).
155        #[arg(long)]
156        base: Option<String>,
157        /// testing-conventions config file providing the `exempt` list. Optional:
158        /// absent means nothing is exempt (every survivor must be killed).
159        #[arg(long, default_value = "testing-conventions.toml")]
160        config: PathBuf,
161        /// Path to the bundled TypeScript mutation adapter (`dist/mutation/main.js`), used
162        /// only by `--language typescript`. The npm launcher appends it; hidden because a
163        /// consumer never sets it by hand.
164        #[arg(long = "ts-mutation-adapter", hide = true)]
165        ts_adapter: Option<PathBuf>,
166    },
167}
168
169/// Languages the integration-test lints support — its own set (Python,
170/// TypeScript, Rust), distinct from the file-pairing `colocated_test::Language`,
171/// so adding Rust here doesn't touch the colocated-test/coverage rules.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
173pub enum IntegrationLintLanguage {
174    /// Python test files (`*_test.py`, `test_*.py`, `conftest.py`).
175    #[value(name = "python")]
176    Python,
177    /// TypeScript test files (`*.test.{ts,tsx,mts,cts}`).
178    #[value(name = "typescript")]
179    TypeScript,
180    /// Rust integration crates under `tests/`.
181    #[value(name = "rust")]
182    Rust,
183}
184
185/// Lints enforced on integration tests (mocking mechanism & style, and more to
186/// come). The README's "Integration" taxonomy.
187#[derive(Subcommand, Debug)]
188enum IntegrationRule {
189    /// Lint integration test files for mocking mechanism & style (Python, TypeScript, Rust).
190    Lint {
191        /// Directory to scan recursively for test files.
192        path: PathBuf,
193        /// Language convention to enforce (required).
194        #[arg(long, value_enum)]
195        language: IntegrationLintLanguage,
196        /// testing-conventions config file providing the `exempt` list (waivers).
197        /// Optional: if the file is absent, nothing is waived.
198        #[arg(long, default_value = "testing-conventions.toml")]
199        config: PathBuf,
200    },
201}
202
203/// E2E attestation commands (#17): record a local e2e run and (later, #68)
204/// verify in CI that the latest code commit is attested.
205#[derive(Subcommand, Debug)]
206enum E2eCommand {
207    /// Run the e2e suite and write a committed attestation naming the current commit.
208    Attest {
209        /// The e2e command to run (e.g. `pnpm run e2e`), executed via the shell.
210        command: String,
211    },
212    /// Verify the committed attestation names the latest code commit (the CI gate).
213    Verify {
214        /// Directory whose committed e2e-attestation.json is verified (default: current directory).
215        #[arg(default_value = ".")]
216        path: PathBuf,
217        /// Directory the "latest code commit" freshness walk is scoped to, if
218        /// narrower than `path` (default: `path` itself, byte-identical to before
219        /// this flag existed). Must be `path` or a descendant of it.
220        #[arg(long)]
221        scope: Option<PathBuf>,
222    },
223}
224
225pub fn run<I, T>(args: I) -> anyhow::Result<i32>
226where
227    I: IntoIterator<Item = T>,
228    T: Into<std::ffi::OsString> + Clone,
229{
230    let cli = Cli::try_parse_from(args)?;
231    match cli.command {
232        // The config-driven `check` umbrella isn't wired yet; the scaffold
233        // proves the wiring while individual rules land under their test-kind
234        // group (e.g. `unit colocated-test`).
235        Some(Command::Check) | None => Ok(0),
236        Some(Command::Unit { rule }) => match rule {
237            UnitRule::ColocatedTest {
238                path,
239                language,
240                base,
241                config,
242            } => run_unit_colocated_test(&path, language, base.as_deref(), &config),
243            UnitRule::Coverage {
244                path,
245                language,
246                base,
247                config,
248            } => run_unit_coverage(&path, language, base.as_deref(), &config),
249            UnitRule::Lint {
250                path,
251                language,
252                config,
253            } => run_unit_lint(&path, language, &config),
254            UnitRule::Mutation {
255                path,
256                language,
257                base,
258                config,
259                ts_adapter,
260            } => run_unit_mutation(
261                &path,
262                language,
263                base.as_deref(),
264                &config,
265                ts_adapter.as_deref(),
266            ),
267        },
268        Some(Command::Integration { rule }) => match rule {
269            IntegrationRule::Lint {
270                path,
271                language,
272                config,
273            } => run_integration_lint(&path, language, &config),
274        },
275        Some(Command::Packaging { path, language }) => run_packaging(&path, language),
276        Some(Command::Workflow { path }) => run_workflow(&path),
277        Some(Command::E2e { command }) => match command {
278            E2eCommand::Attest { command } => run_e2e_attest(&command),
279            E2eCommand::Verify { path, scope } => run_e2e_verify(&path, scope.as_deref()),
280        },
281        Some(Command::Install { path }) => {
282            agents::install(&path)?;
283            Ok(0)
284        }
285    }
286}
287
288/// The binary's own clap command tree — the source of truth for which subcommands
289/// it exposes. The `workflow` guard (#92) checks a workflow's invocations against
290/// it, so a renamed or removed subcommand is caught the moment they diverge.
291pub fn command() -> clap::Command {
292    Cli::command()
293}
294
295/// Run the unit colocated-test check over `root` for `language`. Always runs the
296/// tree-wide **presence** check (every source file has its colocated test; Rust:
297/// an inline `#[cfg(test)]` module). When `base` is `Some`, *additionally* runs the
298/// commit-scoped **co-change** check (#33) over `<base>...HEAD` — a modified or
299/// deleted source whose colocated test didn't co-change — and the run fails if
300/// either check does. Returns `0` only when both pass.
301///
302/// Presence loads the `colocated-test`-rule exemptions and co-change the
303/// `co-change`-rule exemptions from the config at `config_path` (no config file →
304/// no exemptions). `--base` rejects `--language rust`: Rust units are inline
305/// `#[cfg(test)]` in the same file, so a sibling test can't go stale (presence,
306/// without `--base`, still supports Rust).
307fn run_unit_colocated_test(
308    root: &Path,
309    language: colocated_test::Language,
310    base: Option<&str>,
311    config_path: &Path,
312) -> anyhow::Result<i32> {
313    // `--base` carries the co-change check, which rejects Rust the same way the
314    // standalone `unit co-change` did — before any work, so the message matches.
315    if base.is_some() && language == colocated_test::Language::Rust {
316        anyhow::bail!(
317            "`unit colocated-test --base` supports `--language python` / `typescript`; Rust \
318             units are inline `#[cfg(test)]` in the same file, so a sibling test can't go stale"
319        );
320    }
321    let presence_clean = report_colocated_presence(root, language, config_path)?;
322    let co_change_clean = match base {
323        Some(base) => report_co_change(root, base, language, config_path)?,
324        None => true,
325    };
326    Ok(if presence_clean && co_change_clean {
327        0
328    } else {
329        1
330    })
331}
332
333/// The tree-wide colocated-test **presence** check: every source file under `root`
334/// has its colocated unit test (Rust: an inline `#[cfg(test)]` module). Prints each
335/// orphan to stderr and returns `Ok(false)` when any are found, `Ok(true)` when the
336/// tree is clean. The `colocated-test`-rule exemptions from the config at
337/// `config_path` lift a file (no config file → nothing exempt).
338fn report_colocated_presence(
339    root: &Path,
340    language: colocated_test::Language,
341    config_path: &Path,
342) -> anyhow::Result<bool> {
343    let exempt = colocated_test_exemptions(root, language, config_path)?;
344    let orphans = match language {
345        // Rust units are inline `#[cfg(test)]` modules, so "colocated" means a test
346        // module in the same file, not a sibling file (#40).
347        colocated_test::Language::Rust => colocated_test::missing_inline_tests(root, &exempt)?,
348        _ => colocated_test::missing_unit_tests(root, language, &exempt)?,
349    };
350    if orphans.is_empty() {
351        return Ok(true);
352    }
353    let (label, summary) = match language {
354        colocated_test::Language::Rust => (
355            "missing inline `#[cfg(test)]` tests",
356            "source file(s) with testable code but no inline `#[cfg(test)]` module \
357             (add an inline test module, or an `exempt` entry with a reason)",
358        ),
359        _ => (
360            "missing colocated unit test",
361            "source file(s) missing a colocated unit test \
362             (add a colocated test, or an `exempt` entry with a reason)",
363        ),
364    };
365    for orphan in &orphans {
366        eprintln!("{label}: {}", orphan.display());
367    }
368    eprintln!("error: {} {summary}", orphans.len());
369    Ok(false)
370}
371
372/// The `colocated-test`-rule exempt paths for `language`, resolved (and validated)
373/// from the config at `config_path`. A missing config file means no exemptions —
374/// the check still runs, just with nothing exempted.
375fn colocated_test_exemptions(
376    root: &Path,
377    language: colocated_test::Language,
378    config_path: &Path,
379) -> anyhow::Result<std::collections::BTreeSet<String>> {
380    if !config_path.exists() {
381        return Ok(std::collections::BTreeSet::new());
382    }
383    let config = config::load_config(config_path)?;
384    config::resolve_exempt(
385        root,
386        config.exemptions(language),
387        config::Rule::ColocatedTest,
388    )
389}
390
391/// The commit-scoped **co-change** check (#33) over `root`, diffing `<base>...HEAD`:
392/// every modified or deleted source whose colocated test didn't co-change. Prints
393/// each stale source to stderr and returns `Ok(false)` when any are found,
394/// `Ok(true)` when clean.
395///
396/// Loads the `co-change`-rule exemptions from the config at `config_path` (no
397/// config file → no exemptions); an exempt source needn't co-change. The caller
398/// rejects `--language rust` before this runs: Rust units are inline `#[cfg(test)]`
399/// in the same file, so a sibling test can't go stale.
400fn report_co_change(
401    root: &Path,
402    base: &str,
403    language: colocated_test::Language,
404    config_path: &Path,
405) -> anyhow::Result<bool> {
406    let exempt = co_change_exemptions(root, language, config_path)?;
407    let stale = co_change::stale_sources(root, base, language, &exempt)?;
408    if stale.is_empty() {
409        return Ok(true);
410    }
411    for source in &stale {
412        eprintln!(
413            "source changed without its colocated test: {}",
414            source.display()
415        );
416    }
417    eprintln!(
418        "error: {} source file(s) changed without their colocated test co-changing \
419         (update the test, or add an `exempt` entry with a reason)",
420        stale.len()
421    );
422    Ok(false)
423}
424
425/// The `co-change`-rule exempt paths for `language`, resolved (and validated)
426/// from the config at `config_path`. A missing config file means no exemptions —
427/// every changed source must co-change its test.
428fn co_change_exemptions(
429    root: &Path,
430    language: colocated_test::Language,
431    config_path: &Path,
432) -> anyhow::Result<std::collections::BTreeSet<String>> {
433    if !config_path.exists() {
434        return Ok(std::collections::BTreeSet::new());
435    }
436    let config = config::load_config(config_path)?;
437    config::resolve_exempt(root, config.exemptions(language), config::Rule::CoChange)
438}
439
440/// Split a resolved exempt-scope map (#226) into the whole-file paths and the
441/// line-scoped sets — the two shapes the `coverage` / `mutation` measure functions
442/// take. A [`config::LineScope::WholeFile`] becomes a path in the first vec; a
443/// [`config::LineScope::Lines`] a `path → lines` entry in the second map.
444fn split_scopes(
445    scopes: std::collections::BTreeMap<String, config::LineScope>,
446) -> (
447    Vec<String>,
448    std::collections::BTreeMap<String, std::collections::BTreeSet<u32>>,
449) {
450    let mut whole_file = Vec::new();
451    let mut line_scoped = std::collections::BTreeMap::new();
452    for (path, scope) in scopes {
453        match scope {
454            config::LineScope::WholeFile => whole_file.push(path),
455            config::LineScope::Lines(lines) => {
456                line_scoped.insert(path, lines);
457            }
458        }
459    }
460    (whole_file, line_scoped)
461}
462
463/// Run the unit-test coverage check over `root` for `language`, enforcing the
464/// floor from the config at `config_path`. Returns `0` when the floor is met,
465/// `1` otherwise.
466///
467/// With `base` set, the same configured floor is measured over the
468/// `<base>...HEAD` diff (the changed lines) rather than the whole tree (#162),
469/// via the diff-scoped [`patch_coverage::measure`] / `measure_typescript` /
470/// `measure_rust`; without it, the whole-tree [`coverage::measure`] family runs.
471///
472/// Coverage is zero-config by default for Python and TypeScript (#80): a missing
473/// config file — or a config with no `[<language>].coverage` table — falls back to
474/// the language's sane default floor ([`config::PythonCoverage::default`] /
475/// [`config::TypeScriptCoverage::default`]), the same way `unit colocated-test` and
476/// `integration lint` treat an absent config as "nothing exempt". A present
477/// `coverage` table overrides the default; `coverage`-rule exemptions still apply.
478/// Rust (#206) is zero-config too: a missing `[rust].coverage` table falls back to
479/// [`config::RustCoverage::default`] (`lines = 100`, `regions` opt-in, no branch).
480fn run_unit_coverage(
481    root: &Path,
482    language: colocated_test::Language,
483    base: Option<&str>,
484    config_path: &Path,
485) -> anyhow::Result<i32> {
486    let config = if config_path.exists() {
487        config::load_config(config_path)?
488    } else {
489        config::Config::default()
490    };
491    let outcome = match language {
492        colocated_test::Language::Python => {
493            let python = config.python.unwrap_or_default();
494            let coverage = python.coverage.unwrap_or_default();
495            let thresholds = coverage::Thresholds {
496                fail_under: coverage.fail_under,
497                branch: coverage.branch,
498            };
499            let (omit, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
500                root,
501                &python.exempt,
502                config::Rule::Coverage,
503            )?);
504            match base {
505                Some(base) => {
506                    patch_coverage::measure(root, base, thresholds, &omit, &exempt_lines)?
507                }
508                None if exempt_lines.is_empty() => coverage::measure(root, thresholds, &omit)?,
509                None => {
510                    patch_coverage::measure_line_exempt(root, thresholds, &omit, &exempt_lines)?
511                }
512            }
513        }
514        colocated_test::Language::TypeScript => {
515            let typescript = config.typescript.unwrap_or_default();
516            let coverage = typescript.coverage.unwrap_or_default();
517            let thresholds = coverage::TypeScriptThresholds {
518                lines: coverage.lines,
519                branches: coverage.branches,
520                functions: coverage.functions,
521                statements: coverage.statements,
522            };
523            let (exclude, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
524                root,
525                &typescript.exempt,
526                config::Rule::Coverage,
527            )?);
528            match base {
529                Some(base) => patch_coverage::measure_typescript(
530                    root,
531                    base,
532                    thresholds,
533                    &exclude,
534                    &exempt_lines,
535                )?,
536                None if exempt_lines.is_empty() => {
537                    coverage::measure_typescript(root, thresholds, &exclude)?
538                }
539                None => patch_coverage::measure_line_exempt_typescript(
540                    root,
541                    thresholds,
542                    &exclude,
543                    &exempt_lines,
544                )?,
545            }
546        }
547        colocated_test::Language::Rust => {
548            let rust = config.rust.unwrap_or_default();
549            // Zero-config (#206): a missing `[rust].coverage` table falls back to the
550            // default Rust floor (`lines = 100`, with `regions` opt-in and no branch
551            // component) — matching Python/TypeScript — rather than erroring for a
552            // required table. A present table overrides it.
553            let coverage = rust.coverage.unwrap_or_default();
554            let thresholds = coverage::RustThresholds {
555                regions: coverage.regions,
556                lines: coverage.lines,
557                functions: coverage.functions,
558                branch: coverage.branch,
559            };
560            let (ignore, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
561                root,
562                &rust.exempt,
563                config::Rule::Coverage,
564            )?);
565            match base {
566                Some(base) => patch_coverage::measure_rust(
567                    root,
568                    base,
569                    thresholds,
570                    &ignore,
571                    &exempt_lines,
572                    &rust.features,
573                )?,
574                None if exempt_lines.is_empty() => {
575                    coverage::measure_rust(root, thresholds, &ignore, &rust.features)?
576                }
577                None => patch_coverage::measure_line_exempt_rust(
578                    root,
579                    thresholds,
580                    &ignore,
581                    &exempt_lines,
582                    &rust.features,
583                )?,
584            }
585        }
586    };
587    match outcome {
588        coverage::Outcome::Pass => Ok(0),
589        coverage::Outcome::Fail(reason) => {
590            eprintln!("error: coverage check failed — {reason}");
591            Ok(1)
592        }
593    }
594}
595
596/// Run `unit mutation` over `root` (#201, #202): run the per-language engine and fail
597/// on any surviving mutant not lifted by a `mutation` exemption.
598///
599/// The gate is **on by default and binary** — "no *unexplained* surviving mutant":
600/// every survivor must be killed with an assertion, or lifted by a reason-required
601/// `[[<language>.exempt]] rules = ["mutation"]` for an equivalent / deliberately-defensive
602/// mutation. There is no percentage floor (equivalent mutants make one unreachable)
603/// and no report-only mode — the only loosening is a reasoned, per-file exemption.
604/// All three languages are wired: Rust (cargo-mutants), TypeScript (Stryker), and
605/// Python (cosmic-ray). `--base` scopes the run to the diff.
606fn run_unit_mutation(
607    root: &Path,
608    language: colocated_test::Language,
609    base: Option<&str>,
610    config_path: &Path,
611    ts_adapter: Option<&Path>,
612) -> anyhow::Result<i32> {
613    let config = if config_path.exists() {
614        config::load_config(config_path)?
615    } else {
616        config::Config::default()
617    };
618    let survivors = match language {
619        colocated_test::Language::Rust => {
620            let rust = config.rust.unwrap_or_default();
621            let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
622                root,
623                &rust.exempt,
624                config::Rule::Mutation,
625            )?);
626            mutation::measure_rust(root, &exempt, &exempt_lines, base, &rust.features)?
627        }
628        colocated_test::Language::TypeScript => {
629            let typescript = config.typescript.unwrap_or_default();
630            let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
631                root,
632                &typescript.exempt,
633                config::Rule::Mutation,
634            )?);
635            // The npm launcher appends `--ts-mutation-adapter`; its absence means the binary
636            // was run directly, not through the published CLI.
637            let adapter = ts_adapter.ok_or_else(|| {
638                anyhow::anyhow!(
639                    "the TypeScript mutation adapter path is required: pass \
640                     `--ts-mutation-adapter <path>`. The npm `testing-conventions` CLI appends it \
641                     automatically — run the rule through that CLI, not the raw binary."
642                )
643            })?;
644            mutation::measure_typescript(root, &exempt, &exempt_lines, base, adapter)?
645        }
646        colocated_test::Language::Python => {
647            let python = config.python.unwrap_or_default();
648            let (exempt, exempt_lines) = split_scopes(config::resolve_exempt_scoped(
649                root,
650                &python.exempt,
651                config::Rule::Mutation,
652            )?);
653            mutation::measure_python(root, &exempt, &exempt_lines, base)?
654        }
655    };
656    if survivors.is_empty() {
657        println!("unit mutation: no surviving mutants — every mutation was caught");
658        return Ok(0);
659    }
660
661    eprintln!(
662        "error: {} unexplained surviving mutant(s) — kill each with an assertion, or lift an \
663         equivalent/defensive one with a reason-required `[[<language>.exempt]] rules = [\"mutation\"]`:",
664        survivors.len()
665    );
666    for survivor in &survivors {
667        eprintln!(
668            "  {}:{}: {}",
669            survivor.file, survivor.line, survivor.description
670        );
671    }
672    Ok(1)
673}
674
675/// Run the `unit lint` check over `root` for `language` — the unit-suite
676/// isolation lints (`unmocked-collaborator`, `untyped-mock`, `no-out-of-module-call`,
677/// `no-out-of-module-import`) — printing each violation to stderr as
678/// `path:line: rule — message` and returning `1` when any are found, `0` otherwise.
679fn run_unit_lint(
680    root: &Path,
681    language: isolation::Language,
682    config_path: &Path,
683) -> anyhow::Result<i32> {
684    let (raw, select): (Vec<lint::Violation>, ExemptSelect) = match language {
685        isolation::Language::Rust => (isolation::find_violations(root)?, |c| c.rust_exemptions()),
686        isolation::Language::TypeScript => (ts::find_unit_violations(root)?, |c| {
687            c.exemptions(colocated_test::Language::TypeScript)
688        }),
689        isolation::Language::Python => (lint::find_unit_isolation_violations(root)?, |c| {
690            c.exemptions(colocated_test::Language::Python)
691        }),
692    };
693    let violations = apply_waivers(raw, root, config_path, select)?;
694    if violations.is_empty() {
695        return Ok(0);
696    }
697    for v in &violations {
698        eprintln!(
699            "{}:{}: {} — {}",
700            v.file.display(),
701            v.line,
702            v.rule,
703            v.message
704        );
705    }
706    eprintln!("error: {} isolation violation(s)", violations.len());
707    Ok(1)
708}
709
710/// Run the integration-test lints over `root` for `language`, printing each
711/// violation to stderr as `path:line: rule — message` and returning `1` when any
712/// are found, `0` otherwise.
713fn run_integration_lint(
714    root: &Path,
715    language: IntegrationLintLanguage,
716    config_path: &Path,
717) -> anyhow::Result<i32> {
718    let (raw, select): (Vec<lint::Violation>, ExemptSelect) = match language {
719        IntegrationLintLanguage::Python => (lint::find_violations(root)?, |c| {
720            c.exemptions(colocated_test::Language::Python)
721        }),
722        IntegrationLintLanguage::TypeScript => (ts::find_integration_violations(root)?, |c| {
723            c.exemptions(colocated_test::Language::TypeScript)
724        }),
725        IntegrationLintLanguage::Rust => (isolation::find_integration_violations(root)?, |c| {
726            c.rust_exemptions()
727        }),
728    };
729    let violations = apply_waivers(raw, root, config_path, select)?;
730    if violations.is_empty() {
731        return Ok(0);
732    }
733    for v in &violations {
734        eprintln!(
735            "{}:{}: {} — {}",
736            v.file.display(),
737            v.line,
738            v.rule,
739            v.message
740        );
741    }
742    eprintln!("error: {} lint violation(s)", violations.len());
743    Ok(1)
744}
745
746/// Selects a language's `[[<lang>.exempt]]` table from a loaded config — the one
747/// varying piece between the `unit lint` and `integration lint` waiver paths.
748type ExemptSelect = fn(&config::Config) -> &[config::Exemption];
749
750/// Drop the violations waived by the config's `exempt` list (#32/#102). A
751/// violation is waived when its `rule` is a known [`config::Rule`] and its
752/// `root`-relative path is exempt for that rule. `exemptions` selects the
753/// language's `[[<lang>.exempt]]` table from the loaded config. A missing config
754/// file waives nothing; a reason-less or stale entry errors (via `load_config` /
755/// `resolve_exempt`), so the escape hatch can't silently rot.
756fn apply_waivers(
757    violations: Vec<lint::Violation>,
758    root: &Path,
759    config_path: &Path,
760    exemptions: ExemptSelect,
761) -> anyhow::Result<Vec<lint::Violation>> {
762    use std::collections::hash_map::Entry;
763
764    if !config_path.exists() {
765        return Ok(violations);
766    }
767    let config = config::load_config(config_path)?;
768    let exempt = exemptions(&config);
769    // Resolve each rule's exempt set once (and surface a stale entry as an error).
770    let mut resolved: std::collections::HashMap<config::Rule, std::collections::BTreeSet<String>> =
771        std::collections::HashMap::new();
772    let mut kept = Vec::new();
773    for violation in violations {
774        let waived = match config::Rule::from_id(violation.rule) {
775            Some(rule) => {
776                let exempt_paths = match resolved.entry(rule) {
777                    Entry::Occupied(entry) => entry.into_mut(),
778                    Entry::Vacant(entry) => {
779                        entry.insert(config::resolve_exempt(root, exempt, rule)?)
780                    }
781                };
782                violation
783                    .file
784                    .strip_prefix(root)
785                    .ok()
786                    .map(|rel| rel.to_string_lossy().replace('\\', "/"))
787                    .is_some_and(|rel| exempt_paths.contains(&rel))
788            }
789            None => false,
790        };
791        if !waived {
792            kept.push(violation);
793        }
794    }
795    Ok(kept)
796}
797
798/// Run the packaging check: inspect the built artifact at `artifact` for test
799/// files that must not ship (README "Packaging"), per `language`'s test-file
800/// globs.
801///
802/// `artifact` is either an already-unpacked directory or a packed artifact the
803/// rule unpacks itself — a Python wheel (`.whl`) today; the TypeScript (#73) and
804/// Rust (#74) archives follow. Returns `0` when no test file is present, `1`
805/// otherwise (after printing each offending path, relative to the artifact root).
806fn run_packaging(artifact: &Path, language: colocated_test::Language) -> anyhow::Result<i32> {
807    let globs = match language {
808        colocated_test::Language::Python => vec!["*_test.py".to_string()],
809        colocated_test::Language::TypeScript => vec!["*.test.*".to_string()],
810        // `#[cfg(test)]` units compile out for free; the only thing to keep out of
811        // the `.crate` source tarball is the crate-root integration `tests/` dir.
812        colocated_test::Language::Rust => vec!["tests/".to_string()],
813    };
814    let offenders = packaging::inspect(artifact, &globs)?;
815    if offenders.is_empty() {
816        return Ok(0);
817    }
818    for offender in &offenders {
819        eprintln!("test file in built artifact: {}", offender.display());
820    }
821    eprintln!(
822        "error: {} test file(s) present in the built artifact \
823         (they must be excluded from packaging)",
824        offenders.len()
825    );
826    Ok(1)
827}
828
829/// Run the workflow guard over `path` (a workflow file or directory): flag every
830/// `testing-conventions` invocation that names a subcommand this binary no longer
831/// exposes, printing each as `path:line: rule — message` and returning `1` when any
832/// are found, `0` otherwise.
833fn run_workflow(path: &Path) -> anyhow::Result<i32> {
834    let violations = workflow::check(path, &command())?;
835    if violations.is_empty() {
836        return Ok(0);
837    }
838    for v in &violations {
839        eprintln!(
840            "{}:{}: {} — {}",
841            v.file.display(),
842            v.line,
843            v.rule,
844            v.message
845        );
846    }
847    eprintln!(
848        "error: {} workflow invocation(s) name a subcommand this binary no longer exposes",
849        violations.len()
850    );
851    Ok(1)
852}
853
854/// Run `command` as an e2e suite and write a committed attestation naming the
855/// current commit (#67). Force-runs: the attestation is written regardless of
856/// the command's exit code, so this exits `0` once the attestation is recorded.
857fn run_e2e_attest(command: &str) -> anyhow::Result<i32> {
858    let repo = std::env::current_dir()?;
859    let attestation = e2e::attest(&repo, command)?;
860    println!(
861        "e2e attestation recorded for commit {} (command exited {})",
862        attestation.commit, attestation.exit_code
863    );
864    Ok(0)
865}
866
867/// Verify the committed e2e attestation names the latest code commit (#68) — the
868/// CI side of the nudge. Exits `0` when fresh; otherwise prints the actionable
869/// hint and exits `1`. Never runs e2e, never judges the recorded run.
870///
871/// `path` is the directory whose committed `e2e-attestation.json` is checked
872/// (#281) — the default `.` resolves against the current directory, so a
873/// no-argument call behaves exactly like the pre-#281 `current_dir()` read.
874/// Passing a package subdirectory scopes discovery to it, matching a call made
875/// with that directory as cwd. `scope`, when set, narrows the "latest code
876/// commit" freshness walk to a directory under `path` instead of all of it
877/// (#294) — `None` behaves exactly like passing `path` itself.
878fn run_e2e_verify(path: &Path, scope: Option<&Path>) -> anyhow::Result<i32> {
879    match e2e::verify_scoped(path, scope.unwrap_or(path))? {
880        e2e::Verification::Fresh => Ok(0),
881        e2e::Verification::Missing => {
882            eprintln!(
883                "e2e attestation missing — run `testing-conventions e2e attest '<your e2e command>'`"
884            );
885            Ok(1)
886        }
887        e2e::Verification::Stale { attested, latest } => {
888            eprintln!(
889                "e2e attestation out of date: attested {}, latest code commit {} — \
890                 run `testing-conventions e2e attest '<your e2e command>'`",
891                &attested[..attested.len().min(7)],
892                &latest[..latest.len().min(7)]
893            );
894            Ok(1)
895        }
896    }
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902
903    #[test]
904    fn no_args_returns_ok_zero() {
905        assert_eq!(run(["testing-conventions"]).unwrap(), 0);
906    }
907
908    #[test]
909    fn check_returns_ok_zero() {
910        assert_eq!(run(["testing-conventions", "check"]).unwrap(), 0);
911    }
912
913    #[test]
914    fn unknown_flag_errors() {
915        assert!(run(["testing-conventions", "--bogus"]).is_err());
916    }
917
918    #[test]
919    fn help_flag_returns_clap_display_help() {
920        let err = run(["testing-conventions", "--help"]).expect_err("--help should bubble");
921        let clap_err = err
922            .downcast_ref::<clap::Error>()
923            .expect("error should be a clap::Error");
924        assert_eq!(clap_err.kind(), clap::error::ErrorKind::DisplayHelp);
925    }
926
927    #[test]
928    fn version_flag_returns_clap_display_version() {
929        let err = run(["testing-conventions", "--version"]).expect_err("--version should bubble");
930        let clap_err = err
931            .downcast_ref::<clap::Error>()
932            .expect("error should be a clap::Error");
933        assert_eq!(clap_err.kind(), clap::error::ErrorKind::DisplayVersion);
934    }
935}