Skip to main content

xtask/
greenfield_status.rs

1//! `cargo xtask greenfield-status` — the probe harness (track doc §8, proposal #999).
2//!
3//! Twenty-seven probes measuring the tree against `design/bynk-greenfield-compiler.md`:
4//! the twelve in track doc §8, `emit_abi_shapes` (ADR 0310's probe, #999 Decision E —
5//! this slice measures the emit-ABI enumeration guard but does not wire it; wiring is
6//! packaging-track work), phase 7's own four — `ts_writes`, `ts_any`,
7//! `verbatim_origins`, `verbatim_sites` (P7.0/#1296, P7.5/#1307 — see phase 7's own
8//! closing summary in `design/archive/retired-tracks.md`) — and phase 8's own two,
9//! `incremental_query_types` and `keystroke_latency` (P8.0/#1510, settled by #1509's
10//! Q5/ADR 0414 — see `design/tracks/incrementality.md` §5), plus the IR cutover
11//! track's own adoption probe, `unconsumed_ir_items` (Slice D3 of #1542 — the gate the
12//! 30 August 2026 post-restructuring review's Part 5 §8 asked for), and the
13//! runtime-semantics track's `diagnostic_coverage` (#1662, G2 of #1648), and the
14//! crate-hygiene track's M-3 ratchet, `model_readers_beyond_emit` (B1, #2939), and its H-3 gate,
15//! `unused_deps` (A4, #2976).
16//!
17//! **Thirty-four are gated**, committed and diffed: `workspace_lints`, `fs_below_driver`,
18//! `options_sources`, `hoist_sinks`, `span_keyed_maps`, `emit_diagnostics`,
19//! `ide_emit_edge`, `ast_importers`, `emit_abi_shapes`, `ts_writes`, `ts_any`,
20//! `verbatim_origins`, `verbatim_sites`, `incremental_query_types`,
21//! `unconsumed_ir_items`, `diagnostic_coverage`, `model_readers_beyond_emit`, `unused_deps`, `explained_codes`, `ts_raw_sites_emit`, `ts_raw_sites_testgen`, `ts_text_idents`, `emit_thread_locals`, `emit_silent_fallbacks`, `emit_print_calls`, `testgen_print_calls`, `import_prediction_fns`, `node_builder_defs`, `deploy_kind_accessors`, `env_protocol_literals`, `tool_spawn_sites`, `deploy_ledger_writes`, `binding_kind_homes`, `wrangler_key_literals`, `cloudflare_client_sites`. Ten of these are
22//! zero/closure-shaped — a boolean, or a count pinned at a small, argued floor
23//! (`ast_importers` = 5, `emit_abi_shapes` = 1). Phase 7's own four are the same shape:
24//! each converged toward an argued floor over dozens of slices, the same trajectory
25//! `ast_importers` had throughout phase 6's 59 — retired at `ts_writes` = 809,
26//! `ts_any` = 26, `verbatim_origins` = 1, `verbatim_sites` = 2 (phase 7's own closing
27//! summary, `design/archive/retired-tracks.md`), none the literal 0 first proposed —
28//! gated throughout despite the churn that implies, a deliberate call argued in ADR
29//! 0389/ADR 0390 (review of #1297), not an oversight of #999 Decision D's
30//! churn-avoidance principle. `incremental_query_types` is a different shape again —
31//! phase 8's own probe reads a one-time existence proof, not a count trending toward a
32//! floor (settled §5/Q5, ADR 0414), re-settled by #1537 to certify that the two
33//! levels that never found a consumer stay deleted; see its own doc comment. A
34//! disagreement between a
35//! fresh run and the committed table fails `greenfield_status_table_is_current`
36//! (`xtask/tests/greenfield_status.rs`), which rides both the `test` job (`cargo test
37//! --workspace`, any Rust-touching PR) and the `drift` job's existing `cargo test -p
38//! xtask` (pending/decisions-only PRs) — no new CI wiring (#999 Decision D, which also
39//! explains why a `drift`-job *step* would have been silently skipped on the PRs that
40//! move these probes most).
41//!
42//! **Two kinds of gate** (#3679, amending ADR 0389/0390). Every gated probe is
43//! *exact-match*: a live reading that differs from its committed row fails unless a
44//! pending file names it in `probes:`. The [`GROWTH_PROBES`] (`ts_writes`, `ts_any`,
45//! `emit_abi_shapes`, `verbatim_sites`, `ts_raw_sites_emit`, `ts_raw_sites_testgen`, `ts_text_idents`, `span_keyed_maps`, `emit_thread_locals`, `emit_silent_fallbacks`, `emit_print_calls`, `testgen_print_calls`, `import_prediction_fns`, `node_builder_defs`, `deploy_kind_accessors`, `env_protocol_literals`, `tool_spawn_sites`, `deploy_ledger_writes`, `binding_kind_homes`, `wrangler_key_literals`, `cloudflare_client_sites`) are also *directional*:
46//! `growth_probes_never_rise` (`xtask/tests/greenfield_status.rs`) fails when the
47//! live leading count exceeds the committed one unless a pending file *raises* the
48//! probe with a reason (`raises:`), which the stamp then records in
49//! `design/greenfield-status-raises.md`. A fall needs only `probes:`. In CI the
50//! direction is also checked against the table at the PR's *base* revision
51//! (`greenfield-status --check-growth`, [`check_growth`]), so hand-editing a
52//! committed growth row upward does not launder a rise.
53//!
54//! A disagreement a pending file acknowledges (its `probes` key) does not fail the
55//! gate: the increment leaves the shared table alone and `cargo xtask stamp --apply`
56//! rewrites the gated rows on `main` in merge order ([`refresh_gated_rows`]). The
57//! acknowledgement still has to be written, and reviewed, in the PR — a gated probe
58//! still cannot move silently — but parallel PRs no longer conflict on these rows.
59//!
60//! **Who refreshes which rows.** The stamp rewrites the gated rows only (it never pays
61//! for the trend probes' workspace-wide clippy pass). The trend rows are rewritten by
62//! the weekly `.github/workflows/greenfield-trends.yml`, which runs
63//! `cargo xtask greenfield-status --trend-only --apply` ([`refresh_trend_rows`]) and
64//! opens one rolling PR from the bot branch `bot/greenfield-trends`; a person can run
65//! the same command locally. A full `--apply` still rewrites everything.
66//!
67//! **Six are count/ratio trend probes**, recomputed and printed but never diffed:
68//! `wildcard_arms`, `keep_in_sync`, `test_density`, `fixture_kinds`,
69//! `keystroke_latency`, `module_lines` (production lines per source file, #3683). The first four, and `module_lines` too, move on nearly any ordinary Rust PR with no
70//! slice actively driving them toward a floor (§8 calls two of them "trends, not
71//! gates"); hard-gating them would make the committed table churn, and conflict, on
72//! routine work for no corresponding benefit. `keystroke_latency` moves on nothing
73//! yet — settled (Q3/ADR 0414) as staying "not measured" for phase 8's own whole
74//! lifetime, since no scheduler ships this phase to produce a real number; reported
75//! anyway so the trajectory's own §3.0 baseline has a live, CI-computed row.
76//!
77//! `Closes-Rule:` rule-id provenance (#999 Decision B) is deferred to a follow-on
78//! slice — the committed table below carries no rule-citation column yet.
79
80use std::collections::BTreeSet;
81use std::fmt::Write as _;
82use std::path::{Path, PathBuf};
83use std::process::Command;
84
85use crate::module_lines::{BACK_HALF_CRATES, gated_stems, is_test_only_file};
86
87/// One probe's result. `gated` probes are diffed against the committed table by
88/// [`crate::greenfield_status::gated_disagreements`]; the rest are reported only.
89pub struct Probe {
90    pub name: &'static str,
91    pub gated: bool,
92    pub reads: String,
93}
94
95pub struct Report {
96    pub probes: Vec<Probe>,
97}
98
99impl Report {
100    pub fn get(&self, name: &str) -> &str {
101        self.probes
102            .iter()
103            .find(|p| p.name == name)
104            .map(|p| p.reads.as_str())
105            .unwrap_or_else(|| panic!("no probe named {name:?}"))
106    }
107}
108
109/// Run every probe against the tree rooted at `root` (the repo root). Used by the CLI's
110/// full report; the gating test uses the twenty-one gated probes alone
111/// ([`gated_disagreements`]) so it never pays for a workspace-wide clippy pass
112/// (`wildcard_arms`) just to check the probes that are actually diffed.
113pub fn run(root: &Path) -> Report {
114    let mut probes = run_gated(root);
115    probes.extend(run_trend(root));
116    Report { probes }
117}
118
119/// The gated probes' names, in [`run_gated`]'s order — what a pending file's
120/// `probes` key may cite. `greenfield_status_table_is_current` asserts this
121/// matches the probes [`run_gated`] actually returns, so the two cannot drift.
122pub const GATED_PROBES: [&str; 34] = [
123    "workspace_lints",
124    "fs_below_driver",
125    "options_sources",
126    "hoist_sinks",
127    "span_keyed_maps",
128    "emit_diagnostics",
129    "ide_emit_edge",
130    "ast_importers",
131    "emit_abi_shapes",
132    "ts_writes",
133    "ts_any",
134    "verbatim_origins",
135    "verbatim_sites",
136    "ts_raw_sites_emit",
137    "ts_raw_sites_testgen",
138    "ts_text_idents",
139    "emit_thread_locals",
140    "emit_silent_fallbacks",
141    "emit_print_calls",
142    "import_prediction_fns",
143    "node_builder_defs",
144    "deploy_kind_accessors",
145    "env_protocol_literals",
146    "tool_spawn_sites",
147    "deploy_ledger_writes",
148    "binding_kind_homes",
149    "wrangler_key_literals",
150    "cloudflare_client_sites",
151    "incremental_query_types",
152    "unconsumed_ir_items",
153    "diagnostic_coverage",
154    "model_readers_beyond_emit",
155    "unused_deps",
156    "explained_codes",
157];
158
159/// The gated probes that only a reasoned, recorded `raises:` may increase
160/// (#3679, ADR 0389/0390 amended): `ts_writes`, `ts_any`, `emit_abi_shapes`,
161/// `verbatim_sites`, `ts_raw_sites_emit` and `ts_raw_sites_testgen` (the split of `ts_raw_sites`, #3681), `ts_text_idents` (#3681), `span_keyed_maps`, `emit_thread_locals` (1A.19), `emit_silent_fallbacks` (1A.34), `emit_print_calls` (1A.35b), `testgen_print_calls` (1B.2a), `import_prediction_fns` (1A.36a), `node_builder_defs` (1B.4a), `deploy_kind_accessors` (1D.1a), `env_protocol_literals` (1D.5a), `tool_spawn_sites` (1D.5b), `deploy_ledger_writes` (1D.2a), `binding_kind_homes` (1C.1b), `wrangler_key_literals` (1C.2), `cloudflare_client_sites` (1D.3a). Probes already at a zero or closure
162/// floor are excluded (their exact-match row pins them), as are
163/// `verbatim_origins` (an argued floor of 2) and `model_readers_beyond_emit`
164/// (which has the opposite direction). A subset of [`GATED_PROBES`], pinned by
165/// a unit test.
166pub const GROWTH_PROBES: [&str; 20] = [
167    "ts_writes",
168    "ts_any",
169    "emit_abi_shapes",
170    "verbatim_sites",
171    "ts_raw_sites_emit",
172    "ts_raw_sites_testgen",
173    "ts_text_idents",
174    "span_keyed_maps",
175    "emit_thread_locals",
176    "emit_silent_fallbacks",
177    "emit_print_calls",
178    "import_prediction_fns",
179    "node_builder_defs",
180    "deploy_kind_accessors",
181    "env_protocol_literals",
182    "tool_spawn_sites",
183    "deploy_ledger_writes",
184    "binding_kind_homes",
185    "wrangler_key_literals",
186    "cloudflare_client_sites",
187];
188
189/// The thirty-four gated (zero/closure/ratchet) probes only — what [`gated_disagreements`] diffs.
190pub fn run_gated(root: &Path) -> Vec<Probe> {
191    vec![
192        workspace_lints(root),
193        fs_below_driver(root),
194        options_sources(root),
195        hoist_sinks(root),
196        span_keyed_maps(root),
197        emit_diagnostics(root),
198        ide_emit_edge(root),
199        ast_importers(root),
200        emit_abi_shapes(root),
201        ts_writes(root),
202        ts_any(root),
203        verbatim_origins(root),
204        verbatim_sites(root),
205        ts_raw_sites_emit(root),
206        ts_raw_sites_testgen(root),
207        ts_text_idents(root),
208        emit_thread_locals(root),
209        emit_silent_fallbacks(root),
210        emit_print_calls(root),
211        import_prediction_fns(root),
212        node_builder_defs(root),
213        deploy_kind_accessors(root),
214        env_protocol_literals(root),
215        tool_spawn_sites(root),
216        deploy_ledger_writes(root),
217        binding_kind_homes(root),
218        wrangler_key_literals(root),
219        cloudflare_client_sites(root),
220        incremental_query_types(root),
221        unconsumed_ir_items(root),
222        diagnostic_coverage(root),
223        model_readers_beyond_emit(root),
224        unused_deps(root),
225        explained_codes(root),
226    ]
227}
228
229/// The six reported-only trend probes — never diffed, and notably including the one
230/// (`wildcard_arms`) that shells out to a full `cargo clippy --workspace` pass, which
231/// the gating test must not pay for on every run.
232pub fn run_trend(root: &Path) -> Vec<Probe> {
233    vec![
234        wildcard_arms(root),
235        keep_in_sync(root),
236        test_density(root),
237        fixture_kinds(root),
238        keystroke_latency(root),
239        module_lines(root),
240    ]
241}
242
243/// `design/greenfield-status.md` — the committed table this probe set regenerates.
244pub fn table_path(root: &Path) -> PathBuf {
245    root.join("design/greenfield-status.md")
246}
247
248// --- Filesystem helpers --------------------------------------------------
249
250/// Every `.rs` file under `dir`, recursively, as `(path, contents)`. Unreadable files
251/// (permissions, non-UTF-8) are skipped rather than failing the whole walk — this is a
252/// measurement tool, not a build step.
253pub(crate) fn rust_files(dir: &Path) -> Vec<(PathBuf, String)> {
254    let mut out = Vec::new();
255    walk(dir, &mut out);
256    out
257}
258
259fn walk(dir: &Path, out: &mut Vec<(PathBuf, String)>) {
260    let Ok(entries) = std::fs::read_dir(dir) else {
261        return;
262    };
263    let mut entries: Vec<_> = entries.flatten().collect();
264    entries.sort_by_key(|e| e.file_name());
265    for entry in entries {
266        let path = entry.path();
267        if path.is_dir() {
268            walk(&path, out);
269        } else if path.extension().is_some_and(|e| e == "rs")
270            && let Ok(contents) = std::fs::read_to_string(&path)
271        {
272            out.push((path, contents));
273        }
274    }
275}
276
277/// The inner text of every **standalone** `"bynk.<ident>"` string literal (the
278/// `bynk.*` convention used for diagnostic codes and commons/namespace paths alike).
279///
280/// Standalone, not merely prefix-matching: the identifier run must be immediately
281/// followed by the closing quote, matching the naive `rg -o '"bynk\.[a-zA-Z0-9_.]*"'`
282/// this probe is deliberately more careful than (#999 Decision A). Without that
283/// requirement this would also match the *start* of an unrelated, longer message that
284/// merely happens to begin with "bynk." — e.g. a panic string
285/// `"bynk.map itself uses bynk.list, so list must be injected too: {paths:?}"` is prose
286/// beginning with a namespace-shaped word, not a `"bynk.map"` code literal, and a
287/// dev-only compile-time error message split across lines with a `\`-continuation
288/// (`"bynk.emit.unresolved_cross_context_signature: no signature for \` ...) is one
289/// string, not a diagnostic-code literal, even though its first segment matches the
290/// identifier charset. Both were found — and wrongly counted — by an earlier,
291/// less careful version of this scan; the fix is requiring the closing quote.
292fn bynk_dotted_literals(src: &str) -> Vec<&str> {
293    let mut out = Vec::new();
294    let bytes = src.as_bytes();
295    let mut i = 0;
296    while let Some(rel) = src[i..].find("\"bynk.") {
297        let start = i + rel + 1; // skip the opening quote
298        let mut end = start;
299        while end < bytes.len()
300            && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_' || bytes[end] == b'.')
301        {
302            end += 1;
303        }
304        if end < bytes.len() && bytes[end] == b'"' {
305            out.push(&src[start..end]);
306        }
307        i = end.max(start + 1);
308    }
309    out
310}
311
312/// True if `line`, trimmed, is a `//` or `///` or `//!` line comment. Doesn't attempt
313/// block comments (`/* */`) — none of this codebase's `bynk.*`/dead-identifier
314/// mentions live in one.
315fn is_line_comment(line: &str) -> bool {
316    line.trim_start().starts_with("//")
317}
318
319// --- Gated probe 1: workspace_lints --------------------------------------
320
321/// True when `manifest` has a `[lints]` table containing `workspace = true` — the
322/// crate inherits the root `[workspace.lints]`. A `[lints]` table that sets its own
323/// levels (and no `workspace = true`), or a `[lints.clippy]` sub-table, does not count.
324fn opts_into_workspace_lints(manifest: &str) -> bool {
325    // `None` before the first `[header]`: the root table, where the dotted form
326    // `lints.workspace = true` is valid.
327    let mut table: Option<&str> = None;
328    for line in manifest.lines() {
329        // A TOML comment runs from `#` to the end of the line; none of the keys or
330        // headers read here contain a `#` inside a string.
331        let t = line.split('#').next().unwrap_or("").trim();
332        if t.starts_with('[') {
333            table = Some(t);
334            continue;
335        }
336        let compact: String = t.chars().filter(|c| !c.is_whitespace()).collect();
337        match (table, compact.as_str()) {
338            (Some("[lints]"), "workspace=true") | (None, "lints.workspace=true") => return true,
339            _ => {}
340        }
341    }
342    false
343}
344
345/// The crates that opt into the workspace lints, from `(crate name, manifest)`
346/// pairs, sorted by name.
347fn opted_in_crates(manifests: &[(String, String)]) -> Vec<String> {
348    let mut names: Vec<String> = manifests
349        .iter()
350        .filter(|(_, m)| opts_into_workspace_lints(m))
351        .map(|(n, _)| n.clone())
352        .collect();
353    names.sort();
354    names
355}
356
357/// R2.12. `[workspace.lints]` presence and `clippy::wildcard_enum_match_arm`'s level in
358/// the root `Cargo.toml`, then the top-level crates that opt in with `[lints]
359/// workspace = true` (P0.4, #3685). Not a count: gated because the exact-match gate
360/// makes a later opt-out, or a new opt-in, a visible and acknowledged move.
361fn workspace_lints(root: &Path) -> Probe {
362    let cargo_toml = std::fs::read_to_string(root.join("Cargo.toml")).unwrap_or_default();
363    let has_section = cargo_toml
364        .lines()
365        .any(|l| l.trim() == "[workspace.lints.clippy]" || l.trim() == "[workspace.lints]");
366    let level = cargo_toml
367        .lines()
368        .find(|l| l.contains("wildcard_enum_match_arm"))
369        .map(|l| l.trim().to_string());
370    let manifests: Vec<(String, String)> = top_level_crate_dirs(root)
371        .into_iter()
372        .map(|dir| {
373            let name = dir.file_name().unwrap().to_string_lossy().to_string();
374            let manifest = std::fs::read_to_string(dir.join("Cargo.toml")).unwrap_or_default();
375            (name, manifest)
376        })
377        .collect();
378    let opted_in = opted_in_crates(&manifests);
379    let opted_in = if opted_in.is_empty() {
380        "none".to_string()
381    } else {
382        opted_in.join(", ")
383    };
384    let reads = match (has_section, level) {
385        (true, Some(l)) => format!("present — {l}; opted in: {opted_in}"),
386        (true, None) => {
387            format!("present, wildcard_enum_match_arm not set; opted in: {opted_in}")
388        }
389        (false, _) => "absent".to_string(),
390    };
391    Probe {
392        name: "workspace_lints",
393        gated: true,
394        reads,
395    }
396}
397
398// --- Gated probe 2: fs_below_driver --------------------------------------
399
400/// R2.3. Files under `bynk-emit/src`, `bynk-ide/src`, `bynk-fmt/src` (the crates below
401/// the `bynk` driver, which owns disk I/O) that touch `std::fs` in **production** code.
402///
403/// Excludes usage inside a trailing `#[cfg(test)] mod tests { ... }` block — the
404/// convention every file in this codebase uses, always the last item in the file. A
405/// line is production-scope unless it falls at or after the line following a
406/// `#[cfg(test)]` attribute whose very next non-empty line opens a `mod ... {` block
407/// (as opposed to a `mod name;` external-file declaration, which is not a scope at
408/// all). This mirrors the comment-exclusion discipline elsewhere in this probe set:
409/// tests writing fixtures to a tempdir are not "the driver's job" bypassed, and
410/// counting them would report a rule open that the production code has already closed.
411///
412/// A file counts if its own text names `std::fs` ([`has_production_std_fs`]), **or** if
413/// a bare `fs::`-style call site in it resolves to `std::fs` through its imports
414/// ([`production_std_fs_files`]) — a module-level `use std::fs;` in a parent module is
415/// visible to a child through `use super::*;` (module privacy is ancestor-scoped), so
416/// `project/discovery.rs` (then in `bynk-emit/src`; since D1, #2982, in `bynk-driver/src`, where
417/// this probe no longer counts it) reads and walks the filesystem while never
418/// spelling `std::fs` itself. The literal text scan alone missed exactly that file,
419/// so a probe reading `bynk-emit=0` would have asserted R2.3 closed on a false
420/// premise (#1013).
421///
422/// #1104 (a content-ownership (#1086) probe-precision follow-on): a flagged *count*
423/// alone can't tell a residual R2.3 violation from a documented, permanent exception —
424/// `bynk-emit` read 3 that way from the track's retirement (`design/archive/
425/// retired-tracks.md`'s closing summary) until P4.0 moved all three named files out of
426/// `bynk-emit` entirely, leaving [`NAMED_FS_EXCEPTIONS`] empty (#1561) — the mechanism
427/// stays live for whatever named exception is decided next. So each flagged file is
428/// additionally classified as a **named floor** file — every
429/// production-scope touch it has is either inside one of those named functions, or is
430/// a bare import declaration (no fn encloses it — [`enclosing_fn`] returns `None`) that
431/// performs no I/O of its own, existing only so a *descendant* module's bare `fs::`
432/// call can resolve (the motivating case, #1013: `project.rs`'s own `use std::fs;`,
433/// which `discovery.rs` and `paths.rs` glob-imported via `use super::*;` before P4.0
434/// moved both files out) — or a **residual** file: any other file
435/// touching `std::fs` in production scope, which still reads as a real R2.3 violation
436/// ([`file_is_named_fs_floor`]).
437fn fs_below_driver(root: &Path) -> Probe {
438    let crates = ["bynk-emit", "bynk-ide", "bynk-fmt"];
439    let mut per_crate = Vec::new();
440    let mut total = 0usize;
441    let mut total_floor = 0usize;
442    for krate in crates {
443        let dir = root.join(krate).join("src");
444        let files: Vec<(PathBuf, String)> = rust_files(&dir)
445            .into_iter()
446            .map(|(path, contents)| {
447                let rel = path.strip_prefix(&dir).unwrap_or(&path).to_path_buf();
448                (rel, contents)
449            })
450            .collect();
451        let flagged = production_std_fs_files(&files);
452        let count = flagged.len();
453        total += count;
454        let facts: Vec<FsImportFacts> = files.iter().map(|(_, s)| fs_import_facts(s)).collect();
455        let parents: Vec<Option<usize>> = files
456            .iter()
457            .map(|(p, _)| module_parent(p, &files))
458            .collect();
459        let floor = flagged
460            .iter()
461            .filter(|&&i| {
462                file_is_named_fs_floor(krate, &files, &facts, &parents, i, NAMED_FS_EXCEPTIONS)
463            })
464            .count();
465        total_floor += floor;
466        let residual = count - floor;
467        per_crate.push(if floor > 0 {
468            format!("{krate}={count} ({floor} named floor, {residual} residual)")
469        } else {
470            format!("{krate}={count}")
471        });
472    }
473    Probe {
474        name: "fs_below_driver",
475        gated: true,
476        reads: format!(
477            "{total} files ({}) — {total_floor} named floor, {} residual total",
478            per_crate.join(", "),
479            total - total_floor
480        ),
481    }
482}
483
484/// #1104: the specific, permanently-carved-out production functions whose
485/// `std::fs` touch is a *named* exception, not evidence of unfinished R2.3
486/// migration — settled in `design/tracks/content-ownership.md` §3.2 (retired) and
487/// its closing summary in `design/archive/retired-tracks.md`. `(crate, file path
488/// relative to that crate's `src/`, enclosing production fn name)`. A future
489/// carve-out decided the same deliberate way joins this list; anything touching
490/// `std::fs` in production scope that isn't listed here reads as a residual R2.3
491/// violation, per [`file_is_named_fs_floor`].
492///
493/// Empty since #1561: these three entries were real when #1104 (`769a60a3`,
494/// 6 Aug 2026) added them, but P4.0 (`69af8f2d`, the very next day) moved
495/// `discover_bynk_files`/`read_adapter_binding` (`project/discovery.rs`) and
496/// `try_read_project_paths` (`project/paths.rs`) out of `bynk-emit` into
497/// `bynk-project` entirely — dead from that point on, unnoticed for weeks.
498/// `fs_below_driver`'s `bynk-emit` reading was already 0 with them present
499/// (nothing in the tree matched the dead tuples), confirmed unchanged with
500/// them gone.
501const NAMED_FS_EXCEPTIONS: &[(&str, &str, &str)] = &[];
502
503/// Is flagged file `files[i]` (already known, by [`production_std_fs_files`], to touch
504/// `std::fs` in production scope) a **named floor** file — every production-scope touch
505/// it has is either inside a [`NAMED_FS_EXCEPTIONS`] function for this exact
506/// `(krate, file)`, or a bare `use` import declaration (which reads but performs no
507/// filesystem operation by itself, unlike a module-scope `static`/`const` initialiser or
508/// macro invocation that might)? `facts`/`parents` are the caller's already-computed
509/// [`fs_import_facts`]/[`module_parent`] vectors for `files`, threaded through rather
510/// than recomputed per flagged file.
511///
512/// A single disallowed touch — inside an unlisted fn, inside a listed fn's *file* but
513/// wrong *name*, or outside every fn and not a plain import — makes the whole file
514/// residual: partial credit isn't meaningful here, since the point is "can a reader stop
515/// cross-referencing track docs for this file," not a ratio. Likewise, a file this
516/// function attributes *no* touch line to at all (despite the caller already knowing it's
517/// flagged — [`line_touches_std_fs`]'s re-implementation of the file-level detection
518/// disagreeing with it) reads as residual, not floor: an unattributable touch means this
519/// classifier doesn't understand the file, which must fail loud, not quiet.
520///
521/// `exceptions` is [`NAMED_FS_EXCEPTIONS`] at the one production call site
522/// ([`fs_below_driver`]) — parameterised (#1561) so a test can exercise the
523/// matching logic against a synthetic tuple instead of real, currently-empty
524/// production data, the same way `facts`/`parents` are caller-supplied rather
525/// than recomputed.
526fn file_is_named_fs_floor(
527    krate: &str,
528    files: &[(PathBuf, String)],
529    facts: &[FsImportFacts],
530    parents: &[Option<usize>],
531    i: usize,
532    exceptions: &[(&str, &str, &str)],
533) -> bool {
534    let (path, _) = &files[i];
535    let rel = path.to_string_lossy().replace('\\', "/");
536    let lines: Vec<&str> = files[i].1.lines().collect();
537    let ranges = test_mod_ranges(&lines);
538    let fn_ranges = production_fn_ranges(&lines, &ranges);
539
540    let mut saw_touch = false;
541    for (li, line) in lines.iter().enumerate() {
542        if in_test_range(li, &ranges) {
543            continue;
544        }
545        if !line_touches_std_fs(i, line, facts, parents, files) {
546            continue;
547        }
548        saw_touch = true;
549        let Some(fn_name) = enclosing_fn(li, &fn_ranges) else {
550            // No enclosing fn is harmless only when the line is literally an import
551            // declaration. A module-scope `static`/`const` initialiser, a macro
552            // invocation, or a fn shape `fn_name_on_line` can't parse (`extern "C" fn`)
553            // does real I/O outside every known range and must read as residual.
554            if use_declaration(line).is_some() {
555                continue;
556            }
557            return false;
558        };
559        let named = exceptions
560            .iter()
561            .any(|&(c, f, func)| c == krate && f == rel && func == fn_name);
562        if !named {
563            return false;
564        }
565    }
566    saw_touch
567}
568
569/// Does `line` (already known to be production-scope) itself touch `std::fs` — by the
570/// same two means [`production_std_fs_files`] checks at file granularity, applied here
571/// to one line: a literal `std::fs` substring, or a bare/qualified path this line spells
572/// that resolves to `std::fs` through file `i`'s visible import bindings.
573fn line_touches_std_fs(
574    i: usize,
575    line: &str,
576    facts: &[FsImportFacts],
577    parents: &[Option<usize>],
578    files: &[(PathBuf, String)],
579) -> bool {
580    if line.contains("std::fs") {
581        return true;
582    }
583    let mut roots = BTreeSet::new();
584    collect_bare_path_roots(line, &mut roots);
585    if roots.iter().any(|name| {
586        matches!(
587            resolve_name_in_module(i, name, facts, parents),
588            NameResolution::StdFs
589        )
590    }) {
591        return true;
592    }
593    let mut chains = BTreeSet::new();
594    collect_qualified_paths(line, &mut chains);
595    chains
596        .iter()
597        .any(|chain| qualified_chain_reaches_std_fs(chain, i, facts, parents, files))
598}
599
600/// The name and inclusive body line-range of every production-scope `fn` in `lines`
601/// (`test_ranges` excluded, same as everywhere else in this probe) — used by
602/// [`file_is_named_fs_floor`] to attribute a flagged touch line to its enclosing
603/// function. A wrapped signature (the `{` arriving lines after the `fn` line, past a
604/// multi-line parameter list) is handled the same way [`test_mod_ranges`] handles a
605/// `mod` line: brace depth is tracked starting at the `fn` line itself, but a parameter
606/// list has no `{`/`}` in it, so `started` only flips true once the real body-opening
607/// brace arrives, however many lines later.
608fn production_fn_ranges(
609    lines: &[&str],
610    test_ranges: &[(usize, usize)],
611) -> Vec<(String, usize, usize)> {
612    let mut out = Vec::new();
613    for (i, line) in lines.iter().enumerate() {
614        if in_test_range(i, test_ranges) {
615            continue;
616        }
617        let Some(name) = fn_name_on_line(line) else {
618            continue;
619        };
620        let mut state = BraceScanState::Normal;
621        let mut depth = 0i32;
622        let mut started = false;
623        let mut end = lines.len() - 1;
624        for (j, l) in lines[i..].iter().enumerate() {
625            let (delta, new_state) = brace_delta(l, state);
626            state = new_state;
627            depth += delta;
628            if depth != 0 {
629                started = true;
630            }
631            if started && depth == 0 {
632                end = i + j;
633                break;
634            }
635        }
636        out.push((name, i, end));
637    }
638    out
639}
640
641/// The leading `fn NAME` on `line`, past an optional `pub`/`pub(...)`, `async`,
642/// `unsafe`, `const` modifier run (in any order/repetition, mirroring
643/// [`collect_declared_type_name`]'s `pub`-stripping) — `None` if `line` doesn't open a
644/// function at all (a call site, a doc comment mentioning "fn", a closure). Doesn't
645/// require a trailing `{` or even `(` on this same line — a wrapped signature's `fn`
646/// line can end right at the name.
647fn fn_name_on_line(line: &str) -> Option<String> {
648    let mut t = line.trim();
649    loop {
650        if let Some(rest) = t.strip_prefix("pub") {
651            let rest = rest.trim_start();
652            t = if let Some(after_paren) = rest.strip_prefix('(') {
653                after_paren.split_once(')')?.1.trim_start()
654            } else {
655                rest
656            };
657            continue;
658        }
659        let mut advanced = false;
660        for kw in ["async ", "unsafe ", "const "] {
661            if let Some(rest) = t.strip_prefix(kw) {
662                t = rest.trim_start();
663                advanced = true;
664                break;
665            }
666        }
667        if !advanced {
668            break;
669        }
670    }
671    let rest = t.strip_prefix("fn ")?;
672    let end = rest
673        .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
674        .unwrap_or(rest.len());
675    if end == 0 {
676        return None;
677    }
678    Some(rest[..end].to_string())
679}
680
681/// The innermost [`production_fn_ranges`] entry containing `line_idx`, by name — `None`
682/// if `line_idx` sits outside every production fn (module scope: a `use` declaration,
683/// a `const`/`static`, or a `struct`/`enum` body).
684fn enclosing_fn(line_idx: usize, fn_ranges: &[(String, usize, usize)]) -> Option<String> {
685    fn_ranges
686        .iter()
687        .filter(|(_, start, end)| line_idx >= *start && line_idx <= *end)
688        .min_by_key(|(_, start, end)| end - start)
689        .map(|(name, _, _)| name.clone())
690}
691
692/// The literal text component of [`fs_below_driver`]: some production-scope line names
693/// `std::fs`. Necessary but not sufficient (#1013) — a file can touch `std::fs`
694/// through a glob-imported parent binding without ever spelling it; that resolution
695/// lives in [`production_std_fs_files`], which layers on top of this scan.
696fn has_production_std_fs(src: &str) -> bool {
697    let lines: Vec<&str> = src.lines().collect();
698    let ranges = test_mod_ranges(&lines);
699    for (i, line) in lines.iter().enumerate() {
700        if in_test_range(i, &ranges) {
701            continue;
702        }
703        if line.contains("std::fs") {
704            return true;
705        }
706    }
707    false
708}
709
710/// Indices (into `files`, whose paths are relative to the crate's `src/` root) of the
711/// files that touch `std::fs` in production code — the union of the literal text scan
712/// ([`has_production_std_fs`]) and import resolution: a path whose leading module
713/// segment a production `use` declaration binds to `std::fs` (or an item under it),
714/// either a bare `NAME::` root resolved in the file itself (`use std::{fs, io};` — a
715/// form the substring scan can't see) or in an ancestor module reached through
716/// `use super::*;`, transitively (#1013), or a `super::`/`self::`/`crate::`-qualified
717/// path walked through the module tree to the same bindings (#1016 review — a
718/// descendant may spell `super::fs::read_to_string(p)` with no glob import at all,
719/// one disambiguating edit away from a currently-flagged bare call).
720///
721/// Resolution is Rust-shaped, not hand-tracked (#1013 rejects a special-case list):
722/// a private `use std::fs;` in a parent is visible to descendants because module
723/// privacy is ancestor-scoped, a chain of `use super::*;` globs re-reaches it from
724/// any depth, and a nearer binding of the same name shadows a farther one — whether
725/// that binding is another `use` or a locally-declared type-namespace item (`mod fs;`,
726/// `struct File`, …; value-namespace items like `fn` can't head a `NAME::` path, so
727/// they don't shadow one) — so a child that binds `fs` to something else keeps its
728/// bare `fs::` calls unflagged. Visibility is *not* modelled: a path that names a
729/// too-private binding wouldn't compile anyway, so over-approximating is safe.
730///
731/// Known remaining gaps, accepted as out of reach for a text-level scanner: an
732/// ancestor's `use std::fs::read_to_string;` item import called bare (`read_to_string(p)`)
733/// presents no `::` path segment to resolve — the same import used as a path root
734/// (`File::open`) **is** caught, since item bindings under `std::fs` participate in
735/// the same resolution — and a `use` declaration rustfmt has split across lines is
736/// not parsed. #1013 grepped the three scanned crates for the item-import form, and
737/// the #1016 review for the qualified-path and split-declaration forms — zero hits.
738fn production_std_fs_files(files: &[(PathBuf, String)]) -> Vec<usize> {
739    let facts: Vec<FsImportFacts> = files.iter().map(|(_, src)| fs_import_facts(src)).collect();
740    let parents: Vec<Option<usize>> = files
741        .iter()
742        .map(|(path, _)| module_parent(path, files))
743        .collect();
744    (0..files.len())
745        .filter(|&i| {
746            has_production_std_fs(&files[i].1)
747                || resolves_bare_std_fs(i, &facts, &parents)
748                || resolves_qualified_std_fs(i, &facts, &parents, files)
749        })
750        .collect()
751}
752
753/// Per-file production-scope import facts for [`production_std_fs_files`]'s
754/// resolution. All fields exclude `#[cfg(test)] mod` ranges — a test module's
755/// `use super::*;` or tempdir `fs::write` must not make the file, or its children,
756/// read as production `std::fs` (the `bynk-ide` files' shape).
757#[derive(Default)]
758struct FsImportFacts {
759    /// A production `use super::*;` (optionally `pub`-qualified) — the edge that lets
760    /// this file see its parent module's `use` bindings, and (chained) its ancestors'.
761    glob_imports_super: bool,
762    /// Names production `use` declarations bind to `std::fs` or an item under it:
763    /// `use std::fs;` → `fs`, `use std::fs as x;` → `x`, `use std::{fs, io};` → `fs`,
764    /// `use std::fs::File;` → `File`.
765    std_fs_bindings: BTreeSet<String>,
766    /// Every name a production `use` declaration binds, whatever the target — the
767    /// shadow set: a nearer non-`std::fs` binding of a candidate name stops resolution.
768    use_bound_names: BTreeSet<String>,
769    /// Type-namespace items the file declares (`mod fs;`, `struct File`, `enum`,
770    /// `trait`, `type`, `union`) — these beat a glob-imported name in real Rust, so
771    /// they join [`Self::use_bound_names`] on the shadow side of resolution (#1016
772    /// review). Value-namespace items (`fn`, `const`, `static`) can't head a `NAME::`
773    /// module path and are deliberately not collected.
774    declared_type_names: BTreeSet<String>,
775    /// Identifiers appearing as a bare path root `NAME::` (not preceded by another
776    /// path segment) on a production line — the call-site side of the resolution.
777    bare_path_roots: BTreeSet<String>,
778    /// Segment chains of `super::`/`self::`/`crate::`-qualified paths on production
779    /// lines — `super::fs::read_to_string` records `["super", "fs", "read_to_string"]`.
780    /// These need no glob import to reach an ancestor's binding (#1016 review).
781    qualified_paths: BTreeSet<Vec<String>>,
782}
783
784fn fs_import_facts(src: &str) -> FsImportFacts {
785    let lines: Vec<&str> = src.lines().collect();
786    let ranges = test_mod_ranges(&lines);
787    let mut facts = FsImportFacts::default();
788    for (i, line) in lines.iter().enumerate() {
789        if in_test_range(i, &ranges) {
790            continue;
791        }
792        if let Some(decl) = use_declaration(line) {
793            if decl == "super::*" {
794                facts.glob_imports_super = true;
795            }
796            collect_use_bindings("", decl, &mut facts);
797        }
798        collect_declared_type_name(line, &mut facts.declared_type_names);
799        collect_bare_path_roots(line, &mut facts.bare_path_roots);
800        collect_qualified_paths(line, &mut facts.qualified_paths);
801    }
802    facts
803}
804
805/// The path text of a single-line `use` declaration — `use std::fs;` → `std::fs`,
806/// with an optional `pub`/`pub(crate)`/`pub(in …)` prefix stripped and a trailing
807/// `//` comment tolerated (`use super::*; // parent's fs` must not silently sever
808/// the glob edge for a whole subtree — #1016 review; safe to split on `//` because
809/// a `use` path can contain neither a comment marker nor a string). A declaration
810/// rustfmt has split across lines has no trailing `;` here and is not recognised —
811/// none of the `std::fs` forms in the scanned crates are long enough to split.
812fn use_declaration(line: &str) -> Option<&str> {
813    let mut t = line.trim();
814    if let Some(rest) = t.strip_prefix("pub") {
815        let rest = rest.trim_start();
816        t = if let Some(after_paren) = rest.strip_prefix('(') {
817            after_paren.split_once(')')?.1.trim_start()
818        } else {
819            rest
820        };
821    }
822    let body = t.strip_prefix("use ")?;
823    let body = body.split("//").next().unwrap_or(body);
824    body.trim().strip_suffix(';').map(str::trim)
825}
826
827/// If `line` declares a type-namespace item — `mod`/`struct`/`enum`/`trait`/`type`/
828/// `union`, optionally `pub`-qualified, optionally `unsafe` (traits) — record its
829/// name. Field/variable positions can't start a trimmed line with these keywords, so
830/// a leading-keyword scan is enough for rustfmt-shaped code.
831fn collect_declared_type_name(line: &str, out: &mut BTreeSet<String>) {
832    let mut t = line.trim();
833    if let Some(rest) = t.strip_prefix("pub") {
834        let rest = rest.trim_start();
835        t = if let Some(after_paren) = rest.strip_prefix('(') {
836            match after_paren.split_once(')') {
837                Some((_, after)) => after.trim_start(),
838                None => return,
839            }
840        } else {
841            rest
842        };
843    }
844    if let Some(rest) = t.strip_prefix("unsafe ") {
845        t = rest.trim_start();
846    }
847    for kw in ["mod ", "struct ", "enum ", "trait ", "type ", "union "] {
848        if let Some(rest) = t.strip_prefix(kw) {
849            let rest = rest.trim_start();
850            let end = rest
851                .find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
852                .unwrap_or(rest.len());
853            if end > 0 {
854                out.insert(rest[..end].to_string());
855            }
856            return;
857        }
858    }
859}
860
861/// Record the name(s) a `use` path binds into `facts` — `path::to::name`,
862/// `path as alias`, and brace groups (`std::{fs, path::PathBuf}`, nested one level
863/// per recursion). `prefix` is the already-consumed leading path (empty at the top).
864fn collect_use_bindings(prefix: &str, entry: &str, facts: &mut FsImportFacts) {
865    let entry = entry.trim();
866    if entry.is_empty() {
867        return;
868    }
869    if let Some((path_part, group)) = entry.split_once('{') {
870        let inner_prefix = join_use_path(prefix, path_part.trim().trim_end_matches("::"));
871        let group = group.strip_suffix('}').unwrap_or(group);
872        for part in split_group_entries(group) {
873            collect_use_bindings(&inner_prefix, part, facts);
874        }
875        return;
876    }
877    let (path_part, alias) = match entry.split_once(" as ") {
878        Some((p, a)) => (p.trim(), Some(a.trim())),
879        None => (entry, None),
880    };
881    let full = join_use_path(prefix, path_part);
882    // `use std::fs::{self};` binds `fs` — normalise the `self` leaf away.
883    let full = full.strip_suffix("::self").unwrap_or(&full);
884    let last = full.rsplit("::").next().unwrap_or(full);
885    let name = alias.unwrap_or(last);
886    if name.is_empty() || name == "*" {
887        return; // globs bind no single name; `super::*` is tracked separately
888    }
889    facts.use_bound_names.insert(name.to_string());
890    if full == "std::fs" || full.starts_with("std::fs::") {
891        facts.std_fs_bindings.insert(name.to_string());
892    }
893}
894
895fn join_use_path(prefix: &str, part: &str) -> String {
896    if prefix.is_empty() {
897        part.to_string()
898    } else {
899        format!("{prefix}::{part}")
900    }
901}
902
903/// Split a brace group's contents on top-level commas only — `fs::{self, File}, io`
904/// is two entries, not three.
905fn split_group_entries(s: &str) -> Vec<&str> {
906    let mut out = Vec::new();
907    let mut depth = 0i32;
908    let mut start = 0;
909    for (i, c) in s.char_indices() {
910        match c {
911            '{' => depth += 1,
912            '}' => depth -= 1,
913            ',' if depth == 0 => {
914                out.push(&s[start..i]);
915                start = i + 1;
916            }
917            _ => {}
918        }
919    }
920    out.push(&s[start..]);
921    out
922}
923
924/// Every identifier `NAME` occurring as `NAME::` where the character before `NAME` is
925/// not `:` — i.e. a path *root*, so `std::fs::read` contributes `std`, never `fs`.
926/// Same line discipline as the text scan: comments included, production scope only
927/// (the caller has already excluded test ranges).
928fn collect_bare_path_roots(line: &str, out: &mut BTreeSet<String>) {
929    let bytes = line.as_bytes();
930    let mut search_from = 0;
931    while let Some(rel) = line[search_from..].find("::") {
932        let pos = search_from + rel;
933        let mut start = pos;
934        while start > 0 && (bytes[start - 1].is_ascii_alphanumeric() || bytes[start - 1] == b'_') {
935            start -= 1;
936        }
937        if start < pos && (start == 0 || bytes[start - 1] != b':') {
938            out.insert(line[start..pos].to_string());
939        }
940        search_from = pos + 2;
941    }
942}
943
944/// Every `super::`/`self::`/`crate::`-rooted path on `line`, as its segment chain —
945/// `super::fs::read_to_string(p)` yields `["super", "fs", "read_to_string"]`. The
946/// root must sit at a bare word boundary (not `a_super::` or `a::super::`), so only
947/// genuine path roots are collected; `Self::` (capital) never matches, and `self.x`
948/// has no `::` to match.
949fn collect_qualified_paths(line: &str, out: &mut BTreeSet<Vec<String>>) {
950    let bytes = line.as_bytes();
951    for root in ["super", "self", "crate"] {
952        let mut from = 0;
953        while let Some(rel) = line[from..].find(root) {
954            let start = from + rel;
955            let root_end = start + root.len();
956            from = root_end;
957            let boundary_ok = start == 0 || {
958                let c = bytes[start - 1];
959                !(c.is_ascii_alphanumeric() || c == b'_' || c == b':')
960            };
961            if !boundary_ok || !line[root_end..].starts_with("::") {
962                continue;
963            }
964            let mut segments = vec![root.to_string()];
965            let mut pos = root_end;
966            while line[pos..].starts_with("::") {
967                let seg_start = pos + 2;
968                let mut seg_end = seg_start;
969                while seg_end < bytes.len()
970                    && (bytes[seg_end].is_ascii_alphanumeric() || bytes[seg_end] == b'_')
971                {
972                    seg_end += 1;
973                }
974                if seg_end == seg_start {
975                    break; // `super::*` and friends — no further identifier
976                }
977                segments.push(line[seg_start..seg_end].to_string());
978                pos = seg_end;
979            }
980            if segments.len() >= 2 {
981                out.insert(segments);
982            }
983        }
984    }
985}
986
987/// The file defining `path`'s parent module, by the standard layout: `a/b.rs`'s parent
988/// is `a.rs` (or `a/mod.rs`), `a/mod.rs`'s parent is the crate root, and the roots
989/// (`lib.rs`/`main.rs`) have none. `#[path]`-remapped modules are not handled — none
990/// exist below the driver, and a text-level probe can't chase them anyway.
991fn module_parent(path: &Path, files: &[(PathBuf, String)]) -> Option<usize> {
992    let stem = path.file_stem()?.to_str()?;
993    let dir = path.parent().filter(|d| !d.as_os_str().is_empty());
994    let parent_module: PathBuf = if stem == "mod" {
995        dir?.parent().map(Path::to_path_buf).unwrap_or_default()
996    } else if let Some(dir) = dir {
997        dir.to_path_buf()
998    } else {
999        if stem == "lib" || stem == "main" {
1000            return None;
1001        }
1002        PathBuf::new()
1003    };
1004    let candidates = if parent_module.as_os_str().is_empty() {
1005        vec![PathBuf::from("lib.rs"), PathBuf::from("main.rs")]
1006    } else {
1007        vec![
1008            parent_module.with_extension("rs"),
1009            parent_module.join("mod.rs"),
1010        ]
1011    };
1012    candidates
1013        .iter()
1014        .find_map(|c| files.iter().position(|(p, _)| p == c))
1015}
1016
1017/// The scopes whose bindings a name used in module `i` can see: the module itself,
1018/// then each ancestor reachable while every module below it glob-imports `super::*`.
1019fn visible_scopes(i: usize, facts: &[FsImportFacts], parents: &[Option<usize>]) -> Vec<usize> {
1020    let mut scopes = vec![i];
1021    let mut cur = i;
1022    loop {
1023        if !facts[cur].glob_imports_super {
1024            break;
1025        }
1026        let Some(parent) = parents[cur] else { break };
1027        scopes.push(parent);
1028        cur = parent;
1029    }
1030    scopes
1031}
1032
1033/// How `name` resolves in module `m`'s namespace, walking [`visible_scopes`] with
1034/// nearest binding winning — a closer non-`std::fs` `use` binding *or* locally
1035/// declared type-namespace item shadows a farther `std::fs` binding, as in Rust.
1036enum NameResolution {
1037    StdFs,
1038    Other,
1039    Unbound,
1040}
1041
1042fn resolve_name_in_module(
1043    m: usize,
1044    name: &str,
1045    facts: &[FsImportFacts],
1046    parents: &[Option<usize>],
1047) -> NameResolution {
1048    for s in visible_scopes(m, facts, parents) {
1049        if facts[s].std_fs_bindings.contains(name) {
1050            return NameResolution::StdFs;
1051        }
1052        if facts[s].use_bound_names.contains(name) || facts[s].declared_type_names.contains(name) {
1053            return NameResolution::Other;
1054        }
1055    }
1056    NameResolution::Unbound
1057}
1058
1059/// Does a bare path root in file `i` resolve to `std::fs` through the bindings it
1060/// can see? Candidates are the names any visible scope binds to `std::fs`; each is
1061/// then resolved from `i` with nearest-binding-wins shadowing.
1062fn resolves_bare_std_fs(i: usize, facts: &[FsImportFacts], parents: &[Option<usize>]) -> bool {
1063    let scopes = visible_scopes(i, facts, parents);
1064    let mut candidates: BTreeSet<&str> = BTreeSet::new();
1065    for &s in &scopes {
1066        candidates.extend(facts[s].std_fs_bindings.iter().map(String::as_str));
1067    }
1068    candidates.into_iter().any(|name| {
1069        facts[i].bare_path_roots.contains(name)
1070            && matches!(
1071                resolve_name_in_module(i, name, facts, parents),
1072                NameResolution::StdFs
1073            )
1074    })
1075}
1076
1077/// Does a `super::`/`self::`/`crate::`-qualified path in file `i` reach a `std::fs`
1078/// binding (#1016 review)? Unlike the bare-root case these need no glob import: the
1079/// root picks the starting module directly (`super`-hops up the parent chain, `self`
1080/// the file itself, `crate` the crate root), then each further segment either
1081/// resolves in that module's namespace — `std::fs` flags, anything else stops — or
1082/// descends into a child module file and continues. Inline `mod name { … }` blocks
1083/// are not modelled (their `use` bindings live in the same file, which the text scan
1084/// and bare-root resolution already cover).
1085fn resolves_qualified_std_fs(
1086    i: usize,
1087    facts: &[FsImportFacts],
1088    parents: &[Option<usize>],
1089    files: &[(PathBuf, String)],
1090) -> bool {
1091    facts[i]
1092        .qualified_paths
1093        .iter()
1094        .any(|chain| qualified_chain_reaches_std_fs(chain, i, facts, parents, files))
1095}
1096
1097fn qualified_chain_reaches_std_fs(
1098    chain: &[String],
1099    i: usize,
1100    facts: &[FsImportFacts],
1101    parents: &[Option<usize>],
1102    files: &[(PathBuf, String)],
1103) -> bool {
1104    let mut idx = 1;
1105    let mut m = match chain[0].as_str() {
1106        "self" => i,
1107        "crate" => {
1108            let root = files
1109                .iter()
1110                .position(|(p, _)| p == Path::new("lib.rs") || p == Path::new("main.rs"));
1111            match root {
1112                Some(root) => root,
1113                None => return false,
1114            }
1115        }
1116        "super" => {
1117            let mut m = i;
1118            idx = 0;
1119            while idx < chain.len() && chain[idx] == "super" {
1120                let Some(parent) = parents[m] else {
1121                    return false;
1122                };
1123                m = parent;
1124                idx += 1;
1125            }
1126            m
1127        }
1128        _ => return false,
1129    };
1130    while idx < chain.len() {
1131        let seg = chain[idx].as_str();
1132        // Resolve `seg` in `m`, nearest scope first. Within a scope, a child module
1133        // file for `seg` is checked *before* the shadow set: a declared `mod seg;`
1134        // lands `seg` in `declared_type_names`, but that declaration IS the child
1135        // module — it's the path's next hop, not a shadow over it. (In valid Rust a
1136        // module and another same-name type-namespace item can't coexist in one
1137        // scope, so the ordering costs nothing.)
1138        let mut next = None;
1139        for s in visible_scopes(m, facts, parents) {
1140            if facts[s].std_fs_bindings.contains(seg) {
1141                return true;
1142            }
1143            if let Some(child) = child_module_file(s, seg, files) {
1144                next = Some(child);
1145                break;
1146            }
1147            if facts[s].use_bound_names.contains(seg) || facts[s].declared_type_names.contains(seg)
1148            {
1149                return false; // bound to something that is neither std::fs nor a module
1150            }
1151        }
1152        let Some(child) = next else {
1153            return false;
1154        };
1155        m = child;
1156        idx += 1;
1157    }
1158    false
1159}
1160
1161/// The file defining module `m`'s child module `seg`, if it exists as a file:
1162/// `lib.rs` + `a` → `a.rs`/`a/mod.rs`, `a.rs` + `b` → `a/b.rs`/`a/b/mod.rs`,
1163/// `a/mod.rs` + `b` → `a/b.rs`/`a/b/mod.rs`.
1164fn child_module_file(m: usize, seg: &str, files: &[(PathBuf, String)]) -> Option<usize> {
1165    let m_path = &files[m].0;
1166    let module_dir: PathBuf = match m_path.file_stem().and_then(|s| s.to_str()) {
1167        Some("mod") => m_path.parent().unwrap_or(Path::new("")).to_path_buf(),
1168        Some("lib") | Some("main") if m_path.parent().is_none_or(|p| p.as_os_str().is_empty()) => {
1169            PathBuf::new()
1170        }
1171        _ => m_path.with_extension(""),
1172    };
1173    let candidates = [
1174        module_dir.join(format!("{seg}.rs")),
1175        module_dir.join(seg).join("mod.rs"),
1176    ];
1177    candidates
1178        .iter()
1179        .find_map(|c| files.iter().position(|(p, _)| p == c))
1180}
1181
1182/// `t` without a leading `pub`, `pub(crate)`, `pub(super)`, `pub(in path)` visibility.
1183pub(crate) fn strip_visibility(t: &str) -> &str {
1184    match t.strip_prefix("pub") {
1185        Some(rest) if rest.starts_with(char::is_whitespace) => rest.trim_start(),
1186        Some(rest) => match rest.strip_prefix('(') {
1187            Some(r) => r.split_once(')').map_or(t, |(_, after)| after.trim_start()),
1188            None => t,
1189        },
1190        None => t,
1191    }
1192}
1193
1194/// Every `#[cfg(test)] mod <ident> { ... }` block in `lines`, as inclusive
1195/// `(start_line, end_line)` line-index ranges — every occurrence, not just a single
1196/// trailing block. A file in this codebase can carry several test modules scattered
1197/// through it with production code between them — `bynk-emit/src/emitter/lower.rs` has
1198/// two, 1031 lines apart, and treating "everything after the first (or last)
1199/// `#[cfg(test)]`" as one cutoff silently misclassifies that intervening production
1200/// code as test-scope (caught in review: it made `fs_below_driver`, a *gated* probe,
1201/// blind over that span, and inflated `test_density`'s ratio by up to 39%).
1202///
1203/// A block's end is found by real brace-depth counting via [`brace_delta`], not a
1204/// "first column-0 `}`" shortcut: an earlier version of this fix tried exactly that
1205/// shortcut (reasoning that rustfmt always dedents a closing brace back to column 0)
1206/// and it broke on files like `bynk-ide/src/sequence.rs`, whose test module embeds
1207/// multi-line `.bynk`/TypeScript fixture source as string literals — source that
1208/// itself contains a column-0 `}` closing a top-level construct *inside the string*,
1209/// which the shortcut mistook for the end of the Rust `mod` block, truncating it by
1210/// hundreds of lines. `brace_delta` skips characters inside Rust string/char literals
1211/// and comments, so embedded fixture text can't be mistaken for real Rust braces.
1212///
1213/// Only matches a brace-opening `mod` line, with an optional `pub`/`pub(…)` visibility
1214/// (`#[cfg(test)] pub(crate) mod tests {`) — `#[cfg(test)] mod foo;` (an external-file
1215/// declaration, not an inline scope) does not open a range. `#[cfg(all(test, …))]` is not
1216/// recognised (one 840-line front-half module, `bynk-check/src/d1_sql.rs`).
1217pub(crate) fn test_mod_ranges(lines: &[&str]) -> Vec<(usize, usize)> {
1218    let mut ranges = Vec::new();
1219    let mut i = 0;
1220    while i < lines.len() {
1221        if lines[i].trim() == "#[cfg(test)]"
1222            && let Some(off) = lines[i + 1..].iter().position(|l| !l.trim().is_empty())
1223        {
1224            let mod_line = i + 1 + off;
1225            let t = strip_visibility(lines[mod_line].trim());
1226            if t.starts_with("mod ") && t.ends_with('{') {
1227                let mut depth = 0i32;
1228                let mut state = BraceScanState::Normal;
1229                let mut started = false;
1230                let mut end = lines.len() - 1;
1231                for (j, line) in lines[mod_line..].iter().enumerate() {
1232                    let (delta, new_state) = brace_delta(line, state);
1233                    state = new_state;
1234                    depth += delta;
1235                    if depth != 0 {
1236                        started = true;
1237                    }
1238                    if started && depth == 0 {
1239                        end = mod_line + j;
1240                        break;
1241                    }
1242                }
1243                ranges.push((mod_line, end));
1244                i = end + 1;
1245                continue;
1246            }
1247        }
1248        i += 1;
1249    }
1250    ranges
1251}
1252
1253pub(crate) fn in_test_range(line_idx: usize, ranges: &[(usize, usize)]) -> bool {
1254    ranges
1255        .iter()
1256        .any(|(start, end)| line_idx >= *start && line_idx <= *end)
1257}
1258
1259/// Scanner state carried across lines for [`brace_delta`]: whether the cursor is
1260/// inside a string literal, a raw string (with its `#`-count), or a block comment
1261/// (with nesting depth — Rust block comments nest).
1262#[derive(Clone, Copy, PartialEq)]
1263pub(crate) enum BraceScanState {
1264    Normal,
1265    InString,
1266    InRawString(u8),
1267    InBlockComment(u32),
1268}
1269
1270/// The net `{`/`}` depth change in `line`, skipping characters inside Rust string/char
1271/// literals, raw strings, and line/block comments — a naive per-character brace count
1272/// breaks the moment a line contains a fixture string like `"fn f() { \"{\" }"` or a
1273/// doc comment mentioning a brace. Returns the depth delta and the state to carry into
1274/// the next line (a string or block comment can span line boundaries).
1275pub(crate) fn brace_delta(line: &str, mut state: BraceScanState) -> (i32, BraceScanState) {
1276    let mut delta = 0i32;
1277    let chars: Vec<char> = line.chars().collect();
1278    let mut i = 0;
1279    while i < chars.len() {
1280        match state {
1281            BraceScanState::Normal => {
1282                if chars[i] == '/' && chars.get(i + 1) == Some(&'/') {
1283                    break; // rest of the line is a line comment
1284                }
1285                if chars[i] == '/' && chars.get(i + 1) == Some(&'*') {
1286                    state = BraceScanState::InBlockComment(1);
1287                    i += 2;
1288                    continue;
1289                }
1290                if chars[i] == '"' {
1291                    state = BraceScanState::InString;
1292                    i += 1;
1293                    continue;
1294                }
1295                if chars[i] == 'r' && matches!(chars.get(i + 1), Some('"') | Some('#')) {
1296                    let mut j = i + 1;
1297                    let mut hashes = 0u8;
1298                    while chars.get(j) == Some(&'#') {
1299                        hashes += 1;
1300                        j += 1;
1301                    }
1302                    if chars.get(j) == Some(&'"') {
1303                        state = BraceScanState::InRawString(hashes);
1304                        i = j + 1;
1305                        continue;
1306                    }
1307                }
1308                if chars[i] == '\'' {
1309                    // A `'\x'`/`'\\'`-style escaped char literal, or a plain `'x'` —
1310                    // skip past it so its contents can't be mistaken for braces.
1311                    // Anything else (no closing `'` within a couple of chars) is a
1312                    // lifetime, which owns no closing quote to skip.
1313                    if chars.get(i + 1) == Some(&'\\') {
1314                        let mut j = i + 2;
1315                        while j < chars.len() && chars[j] != '\'' {
1316                            j += 1;
1317                        }
1318                        i = (j + 1).min(chars.len());
1319                        continue;
1320                    } else if chars.get(i + 2) == Some(&'\'') {
1321                        i += 3;
1322                        continue;
1323                    }
1324                }
1325                match chars[i] {
1326                    '{' => delta += 1,
1327                    '}' => delta -= 1,
1328                    _ => {}
1329                }
1330                i += 1;
1331            }
1332            BraceScanState::InString => {
1333                if chars[i] == '\\' {
1334                    i += 2;
1335                    continue;
1336                }
1337                if chars[i] == '"' {
1338                    state = BraceScanState::Normal;
1339                }
1340                i += 1;
1341            }
1342            BraceScanState::InRawString(hashes) => {
1343                if chars[i] == '"' {
1344                    let mut j = i + 1;
1345                    let mut h = 0u8;
1346                    while chars.get(j) == Some(&'#') && h < hashes {
1347                        h += 1;
1348                        j += 1;
1349                    }
1350                    if h == hashes {
1351                        state = BraceScanState::Normal;
1352                        i = j;
1353                        continue;
1354                    }
1355                }
1356                i += 1;
1357            }
1358            BraceScanState::InBlockComment(depth) => {
1359                if chars[i] == '/' && chars.get(i + 1) == Some(&'*') {
1360                    state = BraceScanState::InBlockComment(depth + 1);
1361                    i += 2;
1362                    continue;
1363                }
1364                if chars[i] == '*' && chars.get(i + 1) == Some(&'/') {
1365                    state = if depth <= 1 {
1366                        BraceScanState::Normal
1367                    } else {
1368                        BraceScanState::InBlockComment(depth - 1)
1369                    };
1370                    i += 2;
1371                    continue;
1372                }
1373                i += 1;
1374            }
1375        }
1376    }
1377    (delta, state)
1378}
1379
1380// --- Gated probe 3: options_sources --------------------------------------
1381
1382/// R2.3. `CompileOptions` (in `bynk-driver/src/project/options.rs`; it was `bynk-emit/src/project.rs`
1383/// until crate-hygiene D1, #2982) has a `sources` field.
1384fn options_sources(root: &Path) -> Probe {
1385    let src = std::fs::read_to_string(root.join("bynk-driver/src/project/options.rs"))
1386        .unwrap_or_default();
1387    let present = struct_body(&src, "CompileOptions").is_some_and(|body| body.contains("sources"));
1388    Probe {
1389        name: "options_sources",
1390        gated: true,
1391        reads: if present {
1392            "present".to_string()
1393        } else {
1394            "absent".to_string()
1395        },
1396    }
1397}
1398
1399/// The `{ ... }` body text of `struct <name>` in `src`, brace-matched from the struct's
1400/// own opening brace to its close.
1401fn struct_body<'a>(src: &'a str, name: &str) -> Option<&'a str> {
1402    let needle = format!("struct {name}");
1403    let start = src.find(&needle)?;
1404    let open = start + src[start..].find('{')?;
1405    let mut depth = 0i32;
1406    for (offset, ch) in src[open..].char_indices() {
1407        match ch {
1408            '{' => depth += 1,
1409            '}' => {
1410                depth -= 1;
1411                if depth == 0 {
1412                    return Some(&src[open..open + offset + 1]);
1413                }
1414            }
1415            _ => {}
1416        }
1417    }
1418    None
1419}
1420
1421// --- Gated probe 4: hoist_sinks -------------------------------------------
1422
1423/// R6.2. Live (non-comment) occurrences of the sink-passing signature
1424/// `stmts: &mut Vec<String>` in `bynk-emit`. Tier B (T2.1) deletes it entirely.
1425fn hoist_sinks(root: &Path) -> Probe {
1426    let dir = root.join("bynk-emit/src");
1427    let needle = "stmts: &mut Vec<String>";
1428    let mut count = 0usize;
1429    for (_, contents) in rust_files(&dir) {
1430        for line in contents.lines() {
1431            if !is_line_comment(line) && line.contains(needle) {
1432                count += 1;
1433            }
1434        }
1435    }
1436    Probe {
1437        name: "hoist_sinks",
1438        gated: true,
1439        reads: count.to_string(),
1440    }
1441}
1442
1443// --- Gated probe 5: span_keyed_maps ---------------------------------------
1444
1445/// R2.4. Whole-repo occurrences of `HashMap<Span` (comments included — the phase-3
1446/// migration target is every mention, not just live call sites), **excluding
1447/// `xtask` itself**: this probe's own doc comment and source both name the search
1448/// string, which would otherwise self-count every time this file is touched — the
1449/// same self-reference hazard flagged for the dead-identifier probes below, caught
1450/// here by running the probe against itself before committing the first table.
1451fn span_keyed_maps(root: &Path) -> Probe {
1452    let count = count_repo_wide(root, "HashMap<Span", &["xtask"]);
1453    Probe {
1454        name: "span_keyed_maps",
1455        gated: true,
1456        reads: count.to_string(),
1457    }
1458}
1459
1460fn count_repo_wide(root: &Path, needle: &str, exclude_crates: &[&str]) -> usize {
1461    let mut total = 0usize;
1462    for entry in top_level_crate_dirs(root) {
1463        if exclude_crates
1464            .iter()
1465            .any(|c| entry.file_name().is_some_and(|n| n == *c))
1466        {
1467            continue;
1468        }
1469        for (_, contents) in rust_files(&entry.join("src")) {
1470            total += contents.matches(needle).count();
1471        }
1472    }
1473    total
1474}
1475
1476/// Every workspace member crate directory (anything at the repo root with a
1477/// `Cargo.toml` and a `src/` dir), excluding `target` and non-crate directories.
1478pub(crate) fn top_level_crate_dirs(root: &Path) -> Vec<PathBuf> {
1479    let mut out = Vec::new();
1480    let Ok(entries) = std::fs::read_dir(root) else {
1481        return out;
1482    };
1483    for entry in entries.flatten() {
1484        let path = entry.path();
1485        if path.is_dir() && path.join("Cargo.toml").is_file() && path.join("src").is_dir() {
1486            out.push(path);
1487        }
1488    }
1489    out.sort();
1490    out
1491}
1492
1493// --- Gated probe 6: emit_diagnostics --------------------------------------
1494
1495/// R3.5. `bynk.*` string literals in `bynk-emit`/`bynk-check` source, cross-referenced
1496/// against `bynk_syntax::diagnostics::REGISTRY` — not pattern-matched. A literal not in
1497/// `REGISTRY` is a commons/namespace path (e.g. `bynk.locale`, the compiled first-party
1498/// source module name), not a diagnostic code, and must not inflate the count (#999
1499/// Decision A: this cross-reference is what makes the exclusion correct by
1500/// construction rather than a second hand-maintained list).
1501fn emit_diagnostics(root: &Path) -> Probe {
1502    let registry: BTreeSet<&str> = bynk_syntax::diagnostics::REGISTRY
1503        .iter()
1504        .map(|d| d.code)
1505        .collect();
1506    let mut parts = Vec::new();
1507    for (label, dir) in [
1508        ("bynk-emit", "bynk-emit/src"),
1509        // `project` moved here from `bynk-emit` (crate-hygiene D1, #2982): its diagnostics
1510        // are still the code generator's orchestration, so they stay in the reading.
1511        ("bynk-driver", "bynk-driver/src"),
1512        ("bynk-check", "bynk-check/src"),
1513    ] {
1514        let mut naive: BTreeSet<String> = BTreeSet::new();
1515        let src_dir = root.join(dir);
1516        for (path, contents) in rust_files(&src_dir) {
1517            // Only the moved `project` module counts for the driver, not its other files.
1518            // Compared component-wise on the path relative to `src/`, so neither the
1519            // checkout's own location nor a lookalike such as `project_lock.rs` matters.
1520            if label == "bynk-driver"
1521                && !is_moved_project_file(path.strip_prefix(&src_dir).unwrap_or(&path))
1522            {
1523                continue;
1524            }
1525            for lit in bynk_dotted_literals(&contents) {
1526                naive.insert(lit.to_string());
1527            }
1528        }
1529        let true_count = naive
1530            .iter()
1531            .filter(|l| registry.contains(l.as_str()))
1532            .count();
1533        parts.push(format!("{label}={true_count}/{}", naive.len()));
1534    }
1535    Probe {
1536        name: "emit_diagnostics",
1537        gated: true,
1538        reads: format!("{} (true/naive)", parts.join(", ")),
1539    }
1540}
1541
1542// --- Gated probe 7: ide_emit_edge -----------------------------------------
1543
1544/// R10.2. `bynk-ide` → `bynk-emit` in the manifest (`bynk-emit.workspace = true` or an
1545/// equivalent path/version dependency line).
1546fn ide_emit_edge(root: &Path) -> Probe {
1547    let manifest = std::fs::read_to_string(root.join("bynk-ide/Cargo.toml")).unwrap_or_default();
1548    let present = manifest
1549        .lines()
1550        .any(|l| l.trim_start().starts_with("bynk-emit"));
1551    Probe {
1552        name: "ide_emit_edge",
1553        gated: true,
1554        reads: if present {
1555            "present".to_string()
1556        } else {
1557            "absent".to_string()
1558        },
1559    }
1560}
1561
1562// --- Gated probe 8: ast_importers -----------------------------------------
1563
1564/// #1176: `bynk-emit::ir`'s own two files — named exactly, not by path prefix, the same
1565/// permanent-carve-out discipline [`NAMED_FS_EXCEPTIONS`] and [`emit_diagnostics`]'s
1566/// registry cross-reference already use. An `Ast → Ir` lowering pass importing
1567/// `bynk_syntax::ast` is that pass's entire job, not the AST-walking this track is
1568/// closing (phase 6's own P6.9 correction, #1167 — see the retired `the-ir.md`'s
1569/// closing summary, `design/archive/retired-tracks.md`) — but `project.rs` also
1570/// imports `bynk_syntax::ast` today (`EmitProjectCtx` holding `ActorDecl`/`AgentDecl`
1571/// fields directly), and that *is* exactly the still-open R6.13 defect this probe
1572/// tracks (P6.6: "closes the emitter reading AST declarations directly"). A
1573/// path-prefix rule scoped to `emitter/**` would exclude that file right along with
1574/// `ir/`'s legitimate ones, silently undercounting real remaining work — see
1575/// [`is_named_ast_importer`].
1576///
1577/// #1184 review: this exclusion is necessary but not sufficient for R6.13. `bynk-ir`
1578/// still embeds AST types directly in IR struct fields (`TypeShape::Refined`'s
1579/// `BaseType`/`Refinement`, ADR 0366) rather than IR-native equivalents — an emitter
1580/// reading such a field touches the AST without ever spelling `bynk_syntax::ast`
1581/// itself, so it is invisible to this probe by construction. `ast_importers` reading
1582/// its retired floor (5 — `design/archive/retired-tracks.md`'s own closing summary
1583/// has the per-file argument) proves no *remaining* file outside these two and the
1584/// five-file rendering subtree imports the AST module directly; it does not by
1585/// itself prove every `bynk-ir` field is AST-free.
1586///
1587/// #1187's own closing scoping pass adds one more, on different grounds than the
1588/// `ir.rs`/`ir/lower.rs` pair above: `project/tests_emit.rs` was deliberately *not*
1589/// added alongside `project.rs` when this list was first cut (the
1590/// `ast_importer_exclusion_is_named_not_prefixed` test below used to assert exactly
1591/// that) — #1187's own scoping pass found new evidence changing that: its test/suite
1592/// case bodies call `emitter::lower_block_to_async_body`/`lower_test_case_body`/
1593/// `lower_integration_case_body` directly (the Q7-settled body-rendering pass —
1594/// `emitter/lower.rs` keeps hand-writing TypeScript source text after phase 6's
1595/// cutover, the printer that would change that is phase 7's), and
1596/// its own `driver_param_ty`/`strip_effect_httpresult` read a handler's *declared*
1597/// param/return `TypeRef` with no corresponding `TyId` available at that call site
1598/// (the same caller-reads-callee's-raw-declared-shape pattern #661 established for
1599/// cross-context codec generation). Both are the Q7/printer kind of unreachable, not
1600/// the "still open, real work" kind the original exclusion list deliberately left this
1601/// file out of — the correction is new evidence, not a reversal of that reasoning.
1602///
1603/// Review of #1210: `emitter.rs`/`emitter/lower.rs` themselves were considered for
1604/// this same exclusion and **rejected** — Q7 settles that these files' *body-rendering*
1605/// surface stays AST-parameter-driven, but both files also hold live, currently
1606/// untouched AST-*declaration* reads with no such gate: `emitter.rs`'s own
1607/// `CommonsItem::Service`/`svc.protocol` walk (consumed-event-root collection) and
1608/// `emitter/lower.rs`'s own `cap_op_param_names` (`CommonsItem::Capability`/`c.ops`)
1609/// were exactly the P6.2/P6.6-class conversions phase 6's own slice decomposition
1610/// still listed as in scope at the time, not body-rendering. Excluding either file
1611/// would have hidden that real, fixable surface from this probe the same way a
1612/// path-prefix rule would — the harm the named-not-prefixed discipline above exists
1613/// to prevent, just at file granularity instead of directory granularity. (Both
1614/// converted their own reachable surface later, without joining this list — phase 6's
1615/// closing summary, `design/archive/retired-tracks.md`, has the account.)
1616///
1617/// P6.33 (phase 6's own §6a.D re-settling, 19 August 2026): `emitter/serialisation.rs`
1618/// joins the list, on grounds distinct from every entry above — not Q7 body-rendering,
1619/// not test-only reach, but a phase boundary. Unlike `emitter.rs`/`emitter/lower.rs`,
1620/// this file holds no `CommonsItem`-declaration-read surface at all (confirmed:
1621/// `grep -c bynk_syntax::ast` finds only its one `use` line and its `#[cfg(test)]`
1622/// module) — its entire AST surface, ~120 sites, *is* the `TypeRef`-driven JSON/wire
1623/// codec renderer (`emit_record_codec`/`emit_sum_codec`/`serialise_expr`/
1624/// `deserialise_expr`/`ts_inner_type` and siblings). Rendering a checker type as TS
1625/// codec source text is the same class of question Q7 already settled belongs to the
1626/// eventual printer (phase 7, `bynk-ts`) — this file has no `use crate::ir` at all, so
1627/// nothing here has been resisting an available IR-native alternative; none exists. The
1628/// re-settling found no clean way to shrink this file's AST surface further without
1629/// building printer infrastructure phase 6's own scope already excluded.
1630///
1631/// P6.49 (phase 6's own §6b, 19 August 2026): `project.rs` — R6.13's own still-open
1632/// declaration-read surface named at the top of this doc block, above — cleared
1633/// **without joining this list**. Nine slices (P6.42–P6.49) relocated its remaining
1634/// declaration reads to the `bynk-check`/`bynk-project` crates that already own the
1635/// data (`SourceUnit::name()`, `own_contract_hashes`, `discover_event_subscribers`,
1636/// `combined_types_for_unit_info`, two owner-side accessors,
1637/// `lower_event_subscriber_shapes_ir`, `walk_unit_table_bodies`) or re-exported a type
1638/// from a `bynk-check` module whose own public API was already parameterised by it
1639/// (`TypeDecl`/`FnDecl`/`Visibility` from `project_model`, `ActorDecl` from `actors` —
1640/// the P6.27 `ExprId` precedent, applied four more times). This is the evidence this
1641/// exclusion list's own entries above are real, earned exclusions and not a standing
1642/// habit: the harder file cleared its own way, on its own schedule, with zero new
1643/// entries here.
1644///
1645/// **P6.58/P6.59, 19 August 2026: phase 6 (`the-ir.md`, spine #1137) retired at this
1646/// probe reading 5, not 0.** *(Historical: the live reading is the committed one in
1647/// `design/greenfield-status.md`, 13 at 1A.3. `bynk-emit/src` has since grown past the
1648/// five files named next, which were the whole floor only at that retirement.)* The
1649/// floor then was `bynk-emit/src/emitter{,/**}` —
1650/// `emitter.rs`, `emitter/emit.rs`, `emitter/lower.rs`, `emitter/workers.rs`,
1651/// `emitter/workers_entry.rs` — the TypeScript-rendering subtree phase 7's own printer
1652/// inherits; each file's own structural reason, and the full slice history behind
1653/// every correction this doc block narrates, live in `design/archive/retired-tracks.md`
1654/// now that `the-ir.md` itself is gone. This exclusion list does **not** grow to
1655/// reach that floor — the floor is a fact about `AST_IMPORTER_EXCEPTIONS`'s own
1656/// four entries staying exactly these four, not a fifth argument for adding to them.
1657/// The probe itself stays gated, unchanged, reading 5: a regression ratchet phase 7
1658/// inherits and drives down as it builds the printer this floor's own residue names.
1659///
1660/// **Arc D, P7.12 (crate carve): `ir.rs`/`ir/lower.rs` drop out of this list
1661/// entirely — not because they stopped importing the AST (unchanged, still
1662/// do), but because they left `bynk-emit/src` altogether, carved into the new
1663/// `bynk-ir`/`bynk-lower` crates ADR 0332 deferred and ADR 0385 triggered.**
1664/// This probe was never scoped to those crates (`ast_importer_files` walks
1665/// `bynk-emit/src` only), so the pair is simply outside its universe now,
1666/// the same way a file moving to `bynk-check`/`bynk-project` already leaves
1667/// silently rather than needing its own exclusion-list removal step. Two
1668/// named exclusions remain.
1669///
1670/// **Crate-hygiene D1 (#2982, PR 3):** `project/tests_emit.rs` (and the ten modules PR 2
1671/// split it into) left `bynk-emit/src` for `bynk-driver/src/project/`, so the exception
1672/// that named it is gone with the files; the probe's reading is unchanged because those
1673/// files were never counted.
1674const AST_IMPORTER_EXCEPTIONS: &[&str] = &["emitter/serialisation.rs"];
1675
1676/// Is `rel_path` (relative to `bynk-emit/src`) one of [`AST_IMPORTER_EXCEPTIONS`], or a file
1677/// split out of one (an [`AST_IMPORTER_ORIGINS`] child whose origin is an exception)? P6.33's
1678/// grounds cover the codec renderer however it is filed, so `serialisation/expr.rs` is excluded
1679/// because `serialisation.rs` is, and a new file in the directory that is not in the origin table
1680/// is still counted (named, not prefixed).
1681fn is_named_ast_importer(rel_path: &Path) -> bool {
1682    let rel = rel_path.to_string_lossy().replace('\\', "/");
1683    let origin = AST_IMPORTER_ORIGINS
1684        .iter()
1685        .find(|(child, _)| *child == rel)
1686        .map_or(rel.as_str(), |(_, origin)| *origin);
1687    AST_IMPORTER_EXCEPTIONS.contains(&origin)
1688}
1689
1690/// Is `contents` a module (not a nested block) that glob-imports its parent —
1691/// i.e. does it carry a top-level (column-0) `use super::*;`? Rust's own privacy
1692/// rule makes a parent module's private `use` visible to descendant modules, so a
1693/// file matching this can expose `bynk_syntax::ast` names it never spells itself
1694/// (P6.26 review, #1259) — deliberately column-0 only, so a `use super::*;`
1695/// *inside* a nested `#[cfg(test)] mod tests { .. }` block (glob-importing its own
1696/// immediately-enclosing module, not the grandparent file on disk) doesn't
1697/// false-positive this check.
1698fn has_module_level_super_glob(contents: &str) -> bool {
1699    contents.lines().any(|line| line == "use super::*;")
1700}
1701
1702/// For `rel_path` = `<dir>/<file>.rs`, does the sibling module file `<dir>.rs`
1703/// (the parent module a top-level `use super::*;` in `rel_path` would inherit
1704/// from) itself contain `bynk_syntax::ast`? `None` if `rel_path` has no such
1705/// parent (a file directly under `bynk-emit/src`, e.g. `emitter.rs` itself).
1706fn super_glob_parent_imports_ast(dir: &Path, rel_path: &Path) -> Option<bool> {
1707    let parent_dir = rel_path.parent()?;
1708    if parent_dir.as_os_str().is_empty() {
1709        return None;
1710    }
1711    let parent_file = dir.join(parent_dir).with_extension("rs");
1712    Some(
1713        std::fs::read_to_string(&parent_file)
1714            .is_ok_and(|contents| contents.contains("bynk_syntax::ast")),
1715    )
1716}
1717
1718/// The files [`ast_importers`] counts: `bynk-emit/src` files whose contents match
1719/// `bynk_syntax::ast` **or** that inherit it from an AST-importing parent through a
1720/// top-level `use super::*;` (P6.26 review, #1259 — a file that stops spelling the
1721/// AST module directly by deleting its own explicit import, while a live `use
1722/// super::*;` still channels a still-AST-importing parent's names in, must stay
1723/// counted; otherwise a future partial conversion could silently drop this probe
1724/// without the underlying AST dependency actually being gone), excluding
1725/// [`AST_IMPORTER_EXCEPTIONS`]. Split out from [`ast_importers`] so a test can
1726/// assert on the actual survivor set, not just its length (#1184 review).
1727fn ast_importer_files(root: &Path) -> Vec<PathBuf> {
1728    let dir = root.join("bynk-emit/src");
1729    rust_files(&dir)
1730        .into_iter()
1731        .filter(|(path, contents)| {
1732            contents.contains("bynk_syntax::ast")
1733                || (has_module_level_super_glob(contents)
1734                    && super_glob_parent_imports_ast(&dir, path.strip_prefix(&dir).unwrap_or(path))
1735                        .unwrap_or(false))
1736        })
1737        .filter(|(path, _)| !is_named_ast_importer(path.strip_prefix(&dir).unwrap_or(path)))
1738        // 1B.2a (Decision D of #4028): the harness is not production emission.
1739        .filter(|(path, _)| !is_testgen_path(path.strip_prefix(&dir).unwrap_or(path)))
1740        .map(|(path, _)| path)
1741        .collect()
1742}
1743
1744/// R6.13. Files in `bynk-emit/src` that import `bynk_syntax::ast`, excluding
1745/// [`AST_IMPORTER_EXCEPTIONS`] — phase 6's own remaining AST import surface (retired,
1746/// spine #1137; `design/archive/retired-tracks.md` has the closing summary). #1176:
1747/// the unexcluded, crate-wide count could never reach 0 while `bynk-emit::ir`'s
1748/// lowering pass exists at all; this exclusion is what let the probe track phase 6's
1749/// real completion criterion instead of a floor its own IR module structurally could
1750/// not clear. Gated at phase 6's retired floor of 5 when it was set; the live reading is
1751/// the committed one in `design/greenfield-status.md`.
1752fn ast_importers(root: &Path) -> Probe {
1753    let dir = root.join("bynk-emit/src");
1754    let rels: Vec<String> = ast_importer_files(root)
1755        .iter()
1756        .map(|p| {
1757            p.strip_prefix(&dir)
1758                .unwrap_or(p)
1759                .to_string_lossy()
1760                .replace('\\', "/")
1761        })
1762        .collect();
1763    Probe {
1764        name: "ast_importers",
1765        gated: true,
1766        reads: distinct_ast_importer_origins(&rels, AST_IMPORTER_ORIGINS).to_string(),
1767    }
1768}
1769
1770/// Phase 2 of the back-half paydown track (#4085): the split-out files of a pure move, each
1771/// mapped to the file it came from, as `(file, origin)` with both paths relative to
1772/// `bynk-emit/src` and `/`-separated. [`ast_importers`] counts each *origin* once, so a split
1773/// that carries `bynk_syntax::ast` imports into several children leaves the reading where it
1774/// was: the probe measures how much of the crate reads the AST, not how many files it is
1775/// written across. Rows are added by the splits (`emit.rs` first, in 2.1a). **Each Phase 2
1776/// split of a `bynk-emit` file that imports the AST adds one `(child, origin)` row per new file
1777/// that does too, in the same PR** (an origin that is itself a split child maps to its own
1778/// origin, not to the intermediate file). A row whose child is not an importer is inert, so a
1779/// row never needs deleting while the track runs.
1780const AST_IMPORTER_ORIGINS: &[(&str, &str)] = &[
1781    // emitter/workers_entry.rs (2.4, #4089)
1782    ("emitter/workers_entry/call.rs", "emitter/workers_entry.rs"),
1783    (
1784        "emitter/workers_entry/events.rs",
1785        "emitter/workers_entry.rs",
1786    ),
1787    ("emitter/workers_entry/queue.rs", "emitter/workers_entry.rs"),
1788    (
1789        "emitter/workers_entry/websocket.rs",
1790        "emitter/workers_entry.rs",
1791    ),
1792    ("emitter/workers_entry/wire.rs", "emitter/workers_entry.rs"),
1793    (
1794        "emitter/workers_entry/field_specs.rs",
1795        "emitter/workers_entry.rs",
1796    ),
1797    ("emitter/workers_entry/http.rs", "emitter/workers_entry.rs"),
1798    (
1799        "emitter/workers_entry/http_policy.rs",
1800        "emitter/workers_entry.rs",
1801    ),
1802    // emitter.rs (2.5, #4090)
1803    ("emitter/boundary.rs", "emitter.rs"),
1804    ("emitter/consumed.rs", "emitter.rs"),
1805    ("emitter/imports.rs", "emitter.rs"),
1806    ("emitter/project.rs", "emitter.rs"),
1807    // 2.2a (#4087): `lower.rs` split.
1808    ("emitter/lower/pattern.rs", "emitter/lower.rs"),
1809    ("emitter/lower/is.rs", "emitter/lower.rs"),
1810    // 2.2b (#4087).
1811    ("emitter/lower/mock.rs", "emitter/lower.rs"),
1812    ("emitter/lower/expect.rs", "emitter/lower.rs"),
1813    ("emitter/lower/claims.rs", "emitter/lower.rs"),
1814    ("emitter/lower/control.rs", "emitter/lower.rs"),
1815    ("emitter/lower/operator.rs", "emitter/lower.rs"),
1816    ("emitter/lower/literal.rs", "emitter/lower.rs"),
1817    ("emitter/lower/ident.rs", "emitter/lower.rs"),
1818    ("emitter/lower/calls.rs", "emitter/lower.rs"),
1819    // emitter/emit.rs (2.1, #4086), in path order.
1820    ("emitter/emit/agent.rs", "emitter/emit.rs"),
1821    ("emitter/emit/agent_dispatch.rs", "emitter/emit.rs"),
1822    ("emitter/emit/agent_history.rs", "emitter/emit.rs"),
1823    ("emitter/emit/agent_migrate.rs", "emitter/emit.rs"),
1824    ("emitter/emit/agent_state.rs", "emitter/emit.rs"),
1825    ("emitter/emit/agent_store.rs", "emitter/emit.rs"),
1826    ("emitter/emit/capability.rs", "emitter/emit.rs"),
1827    ("emitter/emit/functions.rs", "emitter/emit.rs"),
1828    ("emitter/emit/handlers.rs", "emitter/emit.rs"),
1829    ("emitter/emit/messages.rs", "emitter/emit.rs"),
1830    ("emitter/emit/service.rs", "emitter/emit.rs"),
1831    ("emitter/emit/suite.rs", "emitter/emit.rs"),
1832    ("emitter/emit/types.rs", "emitter/emit.rs"),
1833    ("emitter/emit/websocket.rs", "emitter/emit.rs"),
1834    // emitter/serialisation.rs (an AST_IMPORTER_EXCEPTIONS entry: its children are excluded too)
1835    ("emitter/serialisation/expr.rs", "emitter/serialisation.rs"),
1836    (
1837        "emitter/serialisation/factory.rs",
1838        "emitter/serialisation.rs",
1839    ),
1840    ("emitter/serialisation/field.rs", "emitter/serialisation.rs"),
1841    (
1842        "emitter/serialisation/generics.rs",
1843        "emitter/serialisation.rs",
1844    ),
1845    (
1846        "emitter/serialisation/record_sum.rs",
1847        "emitter/serialisation.rs",
1848    ),
1849    (
1850        "emitter/serialisation/refined.rs",
1851        "emitter/serialisation.rs",
1852    ),
1853    (
1854        "emitter/serialisation/support.rs",
1855        "emitter/serialisation.rs",
1856    ),
1857];
1858
1859/// How many distinct origins the importing files `rels` come from: a file named as a child in
1860/// `origins` counts as its origin, any other file as itself.
1861fn distinct_ast_importer_origins(rels: &[String], origins: &[(&str, &str)]) -> usize {
1862    rels.iter()
1863        .map(|rel| {
1864            origins
1865                .iter()
1866                .find(|(child, _)| child == rel)
1867                .map_or(rel.as_str(), |(_, origin)| origin)
1868        })
1869        .collect::<BTreeSet<&str>>()
1870        .len()
1871}
1872
1873// --- Gated probe 9: emit_abi_shapes ---------------------------------------
1874
1875/// ADR 0310 D1's four emit-ABI shapes, as they surface as import names in the vendored
1876/// bindings — the `Result`/`Option` tag layout plus `DecodeError`, `Uuid`, `FetchError`.
1877const EMIT_ABI: &[&str] = &[
1878    "Result",
1879    "Option",
1880    "Ok",
1881    "Err",
1882    "Some",
1883    "None",
1884    "DecodeError",
1885    "Uuid",
1886    "FetchError",
1887];
1888
1889/// The capability interfaces a vendored binding legitimately imports to implement what
1890/// it declares — governed by language-stability rules, not ADR 0310's codegen-freeze
1891/// concern. See [`emit_abi_shapes`] and #999 Decision E for the two-list rationale.
1892const CAPABILITY_SURFACE: &[&str] = &[
1893    "Clock",
1894    "Fetch",
1895    "Idempotency",
1896    "Locale",
1897    "Logger",
1898    "Random",
1899    "Secrets",
1900    "Request",
1901    "Response",
1902    "LocaleTag",
1903    "Kv",
1904    "KVNamespace",
1905    // Interop I5 (#1972): `bynk.cloudflare`'s `Service`, and the Cloudflare
1906    // `Fetch` provider its binding sends through, so the two share one set of
1907    // header and response rules. Binding-to-binding, not a codegen shape.
1908    "Service",
1909    "FetchProvider",
1910];
1911
1912/// Is `ident` one of ADR 0310's enumerated emit-ABI shapes, or part of the capability
1913/// surface a binding is required to import? If neither, it's a leak `emit_abi_shapes`
1914/// flags — this is the single predicate both the probe and its tests use, so a test
1915/// asserting "no leak" can't silently pass against a list the test itself redefined.
1916fn is_enumerated_emit_abi_or_capability_surface(ident: &str) -> bool {
1917    EMIT_ABI.contains(&ident) || CAPABILITY_SURFACE.contains(&ident)
1918}
1919
1920/// The directories holding the vendored first-party TypeScript bindings, relative to
1921/// the repo root (standard-library track, #1940): the `bynk` surface's per-platform
1922/// bindings in `bynk-std`'s portable layer, and the Cloudflare platform adapter's
1923/// binding in its own subtree. [`emit_abi_shapes`] reads every `.ts` file in each,
1924/// non-recursively, so a binding added to a new subtree must be listed here.
1925const EMIT_ABI_BINDING_DIRS: &[&str] = &["bynk-std/lib/core/bindings", "bynk-std/lib/cloudflare"];
1926
1927/// ADR 0310's probe (#999 Decision E). The vendored first-party bindings under
1928/// [`EMIT_ABI_BINDING_DIRS`] must reference only [`EMIT_ABI`]'s nine names.
1929///
1930/// This does NOT count every non-enumerated import: a binding legitimately imports the
1931/// [`CAPABILITY_SURFACE`] interfaces it implements — that surface is governed by
1932/// language-stability rules, not ADR 0310's codegen-freeze concern, and a probe that
1933/// flagged it would read non-zero on every binding by construction. See #999 Decision
1934/// E for the two-list rationale and its falsifier.
1935///
1936/// A listed directory that is missing, or holds no `.ts` file, reads as a failure
1937/// rather than as zero leaks: a binding moved out of the probe's sight must not pass
1938/// it vacuously (#1940 Decision D).
1939fn emit_abi_shapes(root: &Path) -> Probe {
1940    let mut files: Vec<std::path::PathBuf> = Vec::new();
1941    for rel in EMIT_ABI_BINDING_DIRS {
1942        let Ok(entries) = std::fs::read_dir(root.join(rel)) else {
1943            return Probe {
1944                name: "emit_abi_shapes",
1945                gated: true,
1946                reads: format!("bindings directory not found: {rel}"),
1947            };
1948        };
1949        let before = files.len();
1950        files.extend(
1951            entries
1952                .flatten()
1953                .map(|e| e.path())
1954                .filter(|path| path.extension().is_some_and(|e| e == "ts")),
1955        );
1956        if files.len() == before {
1957            return Probe {
1958                name: "emit_abi_shapes",
1959                gated: true,
1960                reads: format!("no bindings found in {rel}"),
1961            };
1962        }
1963    }
1964    // By file name, so the reading does not depend on which directory a binding sits in.
1965    files.sort_by_key(|path| path.file_name().map(|n| n.to_os_string()));
1966    let mut leaks: Vec<String> = Vec::new();
1967    for path in files {
1968        let Ok(contents) = std::fs::read_to_string(&path) else {
1969            continue;
1970        };
1971        let name = path.file_name().unwrap().to_string_lossy().to_string();
1972        for ident in ts_named_imports_from_runtime_modules(&contents) {
1973            if !is_enumerated_emit_abi_or_capability_surface(&ident) {
1974                leaks.push(format!("{name}:{ident}"));
1975            }
1976        }
1977    }
1978    Probe {
1979        name: "emit_abi_shapes",
1980        gated: true,
1981        reads: format!("{} ({})", leaks.len(), leaks.join(", ")),
1982    }
1983}
1984
1985// --- Gated probe 10: ts_writes ---------------------------------------------
1986
1987/// Files under `bynk-emit/src` that contain `write!`/`writeln!`/`format!` calls but
1988/// produce no TypeScript at all — excluded from both [`ts_writes`] and [`ts_any`], each
1989/// argued individually the same way [`AST_IMPORTER_EXCEPTIONS`] is, not assumed from a
1990/// path prefix: `emitter/wrangler.rs` writes `wrangler.toml`; `emitter/secrets.rs`
1991/// writes `bynk-secrets.json`; `emitter/contracts.rs` writes `bynk-contracts.json`;
1992/// `testkit.rs` built a `.bynk` source fixture — a compiler *input* for tests, not
1993/// output — until 1B.2b (#4028) moved that helper to `bynk-tests` and the file stopped
1994/// having a `format!` to exclude. P7.3 (#1303): `emitter/toml_doc.rs` writes `wrangler.toml` text too —
1995/// `emitter/wrangler.rs`'s own writes moved here when it stopped building the TOML text
1996/// directly and started building a typed `TomlDocument` for this module to print — same
1997/// rationale, same exclusion.
1998///
1999/// (`ir/lower.rs` — Rust-internal `String` values stored on `Ir*` struct fields during
2000/// the checker→IR lowering pass, never emitted syntax — was excluded here for the same
2001/// reason until Arc D's P7.12 crate carve moved it to `bynk-lower` entirely, outside
2002/// this probe's own `bynk-emit/src` universe; no exclusion needed for a file this probe
2003/// no longer walks. `emitter/source_map.rs`, which wrote source-map JSON, is the same
2004/// shape one carve earlier — P7.5 (#1308) relocated it to `bynk-ts/src/source_map.rs`
2005/// in full; its own #1561 removal from this list.)
2006const TS_WRITES_EXCLUDED_FILES: &[&str] = &[
2007    "emitter/wrangler.rs",
2008    "emitter/toml_doc.rs",
2009    "emitter/secrets.rs",
2010    "emitter/contracts.rs",
2011];
2012
2013/// Is `rel_path` (relative to `bynk-emit/src`) one of [`TS_WRITES_EXCLUDED_FILES`]?
2014fn is_ts_writes_excluded_file(rel_path: &Path) -> bool {
2015    let rel = rel_path.to_string_lossy().replace('\\', "/");
2016    TS_WRITES_EXCLUDED_FILES.contains(&rel.as_str())
2017}
2018
2019/// True if `line` builds a filesystem path via `format!` rather than TypeScript text —
2020/// the `PathBuf::from(format!(...))`/`.join(format!(...))`/`.with_file_name(format!(...))`
2021/// idiom [`ts_writes`] excludes at line granularity, not by file, because the files it
2022/// appears in (`project.rs`, `project/tests_emit.rs`) are otherwise genuinely
2023/// TypeScript-producing.
2024///
2025/// **`.with_file_name(format!` found and added by Arc F's own item-4 investigation
2026/// (#1457):** `project.rs`'s `sibling_path` (`output_path.with_file_name(format!(
2027/// "{name}.{suffix}"))`) builds a sibling filesystem path the same way the two idioms
2028/// above do, but spelled with `.with_file_name(` — the prior substring match didn't
2029/// catch it, over-counting `ts_writes` by this one site.
2030fn is_path_construction_line(line: &str) -> bool {
2031    line.contains("PathBuf::from(format!")
2032        || line.contains(".join(format!")
2033        || line.contains(".with_file_name(format!")
2034}
2035
2036/// Is `rel` (relative to `bynk-driver/src`) the `project` module that moved there from
2037/// `bynk-emit` (crate-hygiene D1, #2982): `project.rs` or anything under `project/`?
2038fn is_moved_project_file(rel: &Path) -> bool {
2039    rel == Path::new("project.rs") || rel.starts_with("project")
2040}
2041
2042/// The code-generation family's source files, relative to the crate `src/` each lives
2043/// in: all of `bynk-emit/src` (the test-harness generation, `testgen`, included since 1B.2a moved
2044/// it there from the driver; [`is_testgen_path`] still tells the two apart), plus the orchestration that used to be `bynk-emit`'s
2045/// `project` module and now lives at `bynk-driver/src/project{.rs,/}` (crate-hygiene D1,
2046/// #2982). The probes that read "the emitter's source" ([`ts_writes`], [`ts_any`],
2047/// [`verbatim_origins`], [`verbatim_sites`]) are re-pointed here so moving `project` to
2048/// the driver does not drop emission code out of their universe. The exclusion rules in
2049/// them name `project.rs` / `project/…` relative to the old root, which still resolves.
2050fn codegen_family_files(root: &Path) -> Vec<(PathBuf, String)> {
2051    let driver = rust_files_relative(&root.join("bynk-driver/src"))
2052        .into_iter()
2053        .filter(|(p, _)| is_moved_project_file(p))
2054        .collect();
2055    codegen_family_from(rust_files_relative(&root.join("bynk-emit/src")), driver)
2056}
2057
2058/// [`codegen_family_files`]' selection over the two halves' files, without the file walk,
2059/// so a test can exercise it: both halves, less every whole test file
2060/// ([`is_family_test_file`]).
2061fn codegen_family_from(
2062    mut emit: Vec<(PathBuf, String)>,
2063    driver: Vec<(PathBuf, String)>,
2064) -> Vec<(PathBuf, String)> {
2065    // Each half's declarations are read against its own paths (`bynk-emit/src`, `bynk-driver/src`).
2066    let emit_gated = gated_stems(&emit);
2067    let driver_gated = gated_stems(&driver);
2068    emit.retain(|(p, _)| !is_family_test_file(p, &emit_gated));
2069    let mut driver = driver;
2070    driver.retain(|(p, _)| !is_family_test_file(p, &driver_gated));
2071    emit.extend(driver);
2072    emit
2073}
2074
2075/// Is `rel` a whole test file (`tests.rs`, `*_tests.rs`, or anything under a `tests/`
2076/// directory)? Such a file is test code throughout, so the probes that read the emitter's
2077/// production source skip it, as `module_lines` does. Without this, moving a module's
2078/// tests out to `foo/tests.rs` would raise `ts_writes` with no production line changed.
2079/// Applied to both halves, by file name alone: a production helper named `tests.rs`,
2080/// `*_tests.rs` or under a `tests/` directory would drop out of these probes, so that
2081/// naming convention is load-bearing for them. Counting `bynk-emit`'s whole test files as production read
2082/// `ts_writes` 464 and `ts_any` 24 where the production lines are 462 and 21.
2083fn is_family_test_file(rel: &Path, gated: &std::collections::BTreeSet<String>) -> bool {
2084    is_test_only_file(&rel.to_string_lossy().replace('\\', "/"), gated)
2085}
2086
2087/// Relativises every path in [`rust_files`]'s output against `dir`, so [`ts_writes`]
2088/// and [`ts_any`]'s counting logic ([`ts_writes_violations`], [`ts_any_violations`])
2089/// takes the same `&[(PathBuf, String)]` shape [`production_std_fs_files`] does — an
2090/// in-memory file list a test can construct directly, per review of #1297 (a first cut
2091/// of these two probes took `root: &Path` and did its own walk, so nothing but the
2092/// drift gate actually exercised the exclusion logic; deleting a `continue` left every
2093/// test green).
2094fn rust_files_relative(dir: &Path) -> Vec<(PathBuf, String)> {
2095    rust_files(dir)
2096        .into_iter()
2097        .map(|(path, contents)| {
2098            let rel = path.strip_prefix(dir).unwrap_or(&path).to_path_buf();
2099            (rel, contents)
2100        })
2101        .collect()
2102}
2103
2104/// [`ts_writes`]'s counting logic, over an explicit `(relative path, contents)` list —
2105/// see [`rust_files_relative`] for why this isn't `root: &Path`.
2106///
2107/// **A real mistake this slice's own grounding found and fixed, not carried forward:**
2108/// an earlier survey (during phase 7's own track-opening research) characterised
2109/// `project/tests_emit.rs`'s 128 such sites as excludable "test-assertion strings" — the
2110/// same mischaracterisation `semantics-in-the-checker.md`'s own settling review caught
2111/// and corrected for a *different* probe (`emit_diagnostics`) on this same file: it is
2112/// `process_tests`/`process_integration_tests`, real production TypeScript-emission
2113/// code, not fixture noise, and none of its 128 sites fall inside its own single
2114/// `#[cfg(test)] mod tests { .. }` block. All 128 count here, less the one line that
2115/// genuinely builds a file path ([`is_path_construction_line`]).
2116///
2117/// **Known, accepted gap:** `project/tests_emit.rs`'s
2118/// `target_name: format!("system · {suite}")` builds a human-readable struct-field
2119/// label, not TypeScript text, and matches neither exclusion rule. A text-level scanner
2120/// has no cheap way to catch one field-name-specific site without a bespoke rule for it
2121/// alone — accepted as a one-site over-count, the same "known remaining gaps, out of
2122/// reach for a text-level scanner" discipline [`production_std_fs_files`] already
2123/// documents for a different probe.
2124fn ts_writes_violations(files: &[(PathBuf, String)]) -> usize {
2125    let mut count = 0usize;
2126    for (rel, contents) in files {
2127        if is_ts_writes_excluded_file(rel) {
2128            continue;
2129        }
2130        let lines: Vec<&str> = contents.lines().collect();
2131        let ranges = test_mod_ranges(&lines);
2132        for (i, line) in lines.iter().enumerate() {
2133            if in_test_range(i, &ranges) || is_line_comment(line) || is_path_construction_line(line)
2134            {
2135                continue;
2136            }
2137            if line.contains("write!") || line.contains("writeln!") || line.contains("format!") {
2138                count += 1;
2139            }
2140        }
2141    }
2142    count
2143}
2144
2145/// The trajectory's own phase-7 probe (`design/bynk-compiler-trajectory.md` §3):
2146/// "TypeScript-producing `write!` outside a printer". Never measured before this slice
2147/// (P7.0, #1296; see phase 7's own closing summary, `design/archive/retired-tracks.md`,
2148/// for the full retirement argument) — `bynk-ts` did not exist yet at measurement time,
2149/// so "outside a printer" reduced then to "in `bynk-emit`, outside a `Verbatim`
2150/// construction"; the `Verbatim` half of that exclusion was vacuous until P7.5 built the
2151/// type.
2152///
2153/// **Not "zero/closure"-shaped like this module's other twelve gated probes, and gated
2154/// anyway — a deliberate choice, not an inherited one.** The reading started at 1641 and
2155/// converged, over dozens of slices, to phase 7's own argued retirement floor, **809**
2156/// (ADR 0409; the full bucket-by-bucket accounting is in phase 7's own closing summary,
2157/// `design/archive/retired-tracks.md`) — never the literal 0 first proposed, nor a small
2158/// fixed number the way `ast_importers`/`emit_abi_shapes` are. Stays gated after
2159/// retirement, not deleted — a regression ratchet like `ast_importers` (floor 5) already
2160/// is: it moves on any `bynk-emit` PR that adds or removes a single `write!`/`writeln!`/
2161/// `format!` line anywhere in the crate — the same volatility #999 Decision D cites for
2162/// *not* gating `wildcard_arms` (311, ungated for exactly this reason) — but a floor this
2163/// track spent dozens of slices earning is worth catching a silent regression against,
2164/// the same trade `ast_importers` already made successfully across phase 6's 59 slices.
2165/// The churn cost is real and accepted, not overlooked: see ADR 0389/ADR 0390 for the
2166/// argument in full (review of #1297).
2167///
2168/// Counts `bynk-emit/src/**/*.rs` lines — excluding comments, `#[cfg(test)]` test-module
2169/// ranges, [`TS_WRITES_EXCLUDED_FILES`], and [`is_path_construction_line`] matches —
2170/// containing `write!`, `writeln!` or `format!`. See [`ts_writes_violations`] for the
2171/// counting logic itself.
2172fn ts_writes(root: &Path) -> Probe {
2173    Probe {
2174        name: "ts_writes",
2175        gated: true,
2176        reads: ts_writes_violations(&codegen_family_files(root)).to_string(),
2177    }
2178}
2179
2180// --- Gated probe 11: ts_any -------------------------------------------------
2181
2182/// True if `line` (not a comment) violates R7.1's `TsType::Any` prohibition: an
2183/// `as any` cast, a bare `: any` type annotation, or `any` in generic type-argument
2184/// position (`Array<any>`, `Record<string, any[]>`, `Promise<any>`).
2185///
2186/// Six patterns, not `as any` alone, following three rounds of the same finding.
2187/// Round one (Q3, phase 7's own settling pass) found `as any` alone
2188/// under-counts R7.1 and added bare `: any`. Round two (review of #1297) found *that*
2189/// still under-counts: `bynk-emit/src/emitter/lower.rs`'s `joinOn`/`leftJoin`/`groupBy`
2190/// emit `const __h: Record<string, any[]> = {}` — `, any[]` contains neither `as any`
2191/// nor `: any`, so three live, production, TypeScript-emitting sites read as clean
2192/// under the round-one predicate. Widened to also match `<any`, `any>` and `any[]` —
2193/// each checked against the live tree for false positives (no non-`any`-typed English
2194/// word starts with `any` immediately after `<` or ends in `any` immediately before
2195/// `>`/`[]` anywhere in `bynk-emit/src` today) rather than assumed safe. Round three
2196/// (review of #1322) found a fourth spelling: once a site builds a real `bynk_ts::
2197/// TsType` node instead of writing TypeScript text directly, an emitted `any` no
2198/// longer appears as Rust-source `as any`/`: any` at all — `workers.rs`'s own
2199/// `TsType::named("any")` calls (#1321) emit the identical `payload as any`/
2200/// `let __who: any` text as before, byte-for-byte, but the *Rust spelling* that
2201/// produces it no longer matches any of the five text patterns above, so the probe
2202/// silently uncounted three real, still-live R7.1 residuals. Every later Arc C slice
2203/// converting an `any`-emitting `writeln!`/`format!` site the same way would keep
2204/// deflating this count the same way, so the fix generalises rather than special-
2205/// cases these three lines: match the construction spelling itself
2206/// (`named("any"`), not just raw emitted text.
2207///
2208/// Split out from [`ts_any_violations`] so a test can exercise the predicate directly,
2209/// without file I/O.
2210fn line_violates_ts_any(line: &str) -> bool {
2211    !is_line_comment(line)
2212        && (line.contains("as any")
2213            || line.contains(": any")
2214            || line.contains("<any")
2215            || line.contains("any>")
2216            || line.contains("any[]")
2217            || line.contains("named(\"any\""))
2218}
2219
2220/// [`ts_any`]'s counting logic, over an explicit `(relative path, contents)` list — see
2221/// [`rust_files_relative`] for why this isn't `root: &Path`.
2222fn ts_any_violations(files: &[(PathBuf, String)]) -> usize {
2223    let mut count = 0usize;
2224    for (rel, contents) in files {
2225        if is_ts_writes_excluded_file(rel) {
2226            continue;
2227        }
2228        let lines: Vec<&str> = contents.lines().collect();
2229        let ranges = test_mod_ranges(&lines);
2230        for (i, line) in lines.iter().enumerate() {
2231            if in_test_range(i, &ranges) {
2232                continue;
2233            }
2234            if line_violates_ts_any(line) {
2235                count += 1;
2236            }
2237        }
2238    }
2239    count
2240}
2241
2242/// Reference rule R7.1 (`design/bynk-greenfield-compiler.md` Part 7) — "the tree
2243/// contains no ... `TsType::Any`". Gated for the same reason [`ts_writes`] is (see its
2244/// own doc comment): started at 55 (not the settling review's estimated ~24 — ADR
2245/// 0390), converged over several slices to phase 7's own argued retirement floor, **26**
2246/// (ADR 0404; six already-argued families, none newly tractable — full accounting in
2247/// phase 7's own closing summary, `design/archive/retired-tracks.md`), and stays gated
2248/// after retirement as a regression ratchet, the same "I removed an `Any`" CI-checkable
2249/// claim every slice needed.
2250///
2251/// Counts `bynk-emit/src/**/*.rs` lines — excluding `#[cfg(test)]` test-module ranges
2252/// and [`TS_WRITES_EXCLUDED_FILES`] (the same files [`ts_writes`] excludes for producing
2253/// no TypeScript at all; an `any`-typed value there isn't R7.1's business either) —
2254/// matching [`line_violates_ts_any`]. Hand-written runtime `.ts` files under
2255/// `bynk-emit/runtime/` are out of scope by construction: [`rust_files`] only walks
2256/// `.rs` files, and R7.1 governs the emitted *tree*, not the hand-written runtime R7.7
2257/// separately covers.
2258fn ts_any(root: &Path) -> Probe {
2259    Probe {
2260        name: "ts_any",
2261        gated: true,
2262        reads: ts_any_violations(&codegen_family_files(root)).to_string(),
2263    }
2264}
2265
2266// --- Gated probe 12: verbatim_origins ---------------------------------------
2267
2268/// P7.5 (#1307): distinct `bynk_ts::VerbatimOrigin` variants named in
2269/// `bynk-emit/src` — how many *families* of residual, not-yet-converted
2270/// emission remain, not their size (`verbatim_sites`, below, is the size).
2271/// Retired at an **argued floor**, named file-by-file the way `ast_importers`'s
2272/// floor of 5 was: **1** (ADR 0410) — only `NotYetConverted` has a live
2273/// production reference, at the same two sites `verbatim_sites`'s own floor
2274/// names permanent; full accounting in phase 7's own closing summary,
2275/// `design/archive/retired-tracks.md`. Read **0** at this slice's own
2276/// landing (`bynk-emit` built no `Verbatim` content yet, #1307's Decision C
2277/// — Arc C's own first slice is what gave this probe something to count);
2278/// stays gated after retirement as a regression ratchet.
2279///
2280/// Line-scans for `VerbatimOrigin::<Variant>` and counts distinct variant
2281/// names referenced, the same needle-scan shape [`hoist_sinks`] uses. A
2282/// known, accepted gap (review of #1308, finding 6): a bare `use
2283/// bynk_ts::VerbatimOrigin::Contracts;` followed by unqualified `Contracts`
2284/// elsewhere would undercount, since the needle is the qualified path. Not
2285/// worth a real-parser fix for an *argued-floor* probe (unlike
2286/// `verbatim_sites`'s own floor of exactly 0) — `bynk-emit`'s own existing
2287/// call-site style always qualifies (`TsStmt::verbatim(VerbatimOrigin::X,
2288/// …)`), so this is a theoretical undercount, not an observed one.
2289fn verbatim_origins(root: &Path) -> Probe {
2290    Probe {
2291        name: "verbatim_origins",
2292        gated: true,
2293        reads: verbatim_origins_violations(&codegen_family_files(root)).to_string(),
2294    }
2295}
2296
2297/// [`verbatim_origins`]'s counting logic, over an explicit `(relative path,
2298/// contents)` list — see [`rust_files_relative`] for why this isn't `root:
2299/// &Path`. Excludes `#[cfg(test)]` ranges the same way [`ts_any_violations`]
2300/// does (review of #1308, finding 6): without this, one `bynk-emit` unit
2301/// test constructing a `VerbatimOrigin` for its own fixture pins this probe
2302/// above its argued floor permanently, for a reason that has nothing to do
2303/// with residual production emission.
2304fn verbatim_origins_violations(files: &[(PathBuf, String)]) -> usize {
2305    let needle = "VerbatimOrigin::";
2306    let mut variants: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
2307    for (_, contents) in files {
2308        let lines: Vec<&str> = contents.lines().collect();
2309        let ranges = test_mod_ranges(&lines);
2310        for (i, line) in lines.iter().enumerate() {
2311            if in_test_range(i, &ranges) || is_line_comment(line) {
2312                continue;
2313            }
2314            let mut rest = *line;
2315            while let Some(idx) = rest.find(needle) {
2316                let after = &rest[idx + needle.len()..];
2317                let name: String = after
2318                    .chars()
2319                    .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
2320                    .collect();
2321                rest = &after[name.len()..];
2322                if !name.is_empty() {
2323                    variants.insert(name);
2324                }
2325            }
2326        }
2327    }
2328    variants.len()
2329}
2330
2331// --- Gated probe 13: verbatim_sites -----------------------------------------
2332
2333/// P7.5 (#1307): distinct `TsStmt::verbatim(...)`/`TsExpr::VerbatimExpr(...)`
2334/// construction call sites in `bynk-emit/src`, line-scanned the same way
2335/// [`hoist_sinks`] counts `stmts: &mut Vec<String>` occurrences. Every call
2336/// site converting to a real tree node is what Arc C's own per-file slices
2337/// were actually for — `verbatim_origins` alone can't distinguish "3
2338/// variants, 12 residual call sites" from "3 variants, 900 residual call
2339/// sites, two files never decomposed"; this is what closes that gap. Retired
2340/// at an **argued floor** for the `TsStmt` half, not the flat 0 first
2341/// proposed: **2** (ADR 0399/ADR 0407, confirmed unchanged by the #1486
2342/// capstone) — `project.rs`'s adapter-binding copy loop (a foreign,
2343/// user-authored TypeScript payload) and its `runtime.ts` staging (a
2344/// committed npm build artifact), neither ever generated by `bynk-emit`;
2345/// full accounting in phase 7's own closing summary, `design/archive/
2346/// retired-tracks.md`.
2347///
2348/// #1539 widens the scan to the `TsExpr` half of the same escape hatch
2349/// (`TsExpr::VerbatimExpr`, closing the untagged-`Ident` gap the review
2350/// found) and moves the floor to **11** (the 2 permanent `TsStmt` sites plus
2351/// 9 residual `TsExpr` construction sites in `emit.rs` — a generic-typed
2352/// callee `Call`/`New` has no `type_args` field, a nested `As`-under-`As`
2353/// chain the printer's own operand-parenthesisation rule would mis-wrap, a
2354/// block-bodied ICU IIFE, and a `pred_condition_and_message`-style message
2355/// that a second `TsLit::Str` escaping pass would corrupt — see
2356/// `TsExpr::VerbatimExpr`'s own doc for the full list). Unlike the `TsStmt`
2357/// pair, these 9 are not argued-permanent the same way: each converts to a
2358/// real node the day `bynk-ts` gains the matching type-algebra piece
2359/// (`type_args`, a parenthesisation fix, …), so this half of the floor is
2360/// expected to keep shrinking, tracked here rather than assumed fixed. Read
2361/// **0** at this slice's own landing, same reason `verbatim_origins` did;
2362/// stays gated after retirement as a regression ratchet.
2363fn verbatim_sites(root: &Path) -> Probe {
2364    Probe {
2365        name: "verbatim_sites",
2366        gated: true,
2367        reads: verbatim_sites_violations(&codegen_family_files(root)).to_string(),
2368    }
2369}
2370
2371/// [`verbatim_sites`]'s counting logic, over an explicit `(relative path,
2372/// contents)` list — see [`rust_files_relative`] for why this isn't `root:
2373/// &Path`. Excludes `#[cfg(test)]` ranges the same way [`ts_any_violations`]
2374/// does (review of #1308, finding 6): `verbatim_sites` is documented as
2375/// retiring at 0, so a residual construction site inside a test fixture
2376/// would pin it above zero permanently for a reason that has nothing to do
2377/// with production emission conversion.
2378fn verbatim_sites_violations(files: &[(PathBuf, String)]) -> usize {
2379    let needles = ["TsStmt::verbatim(", "TsExpr::VerbatimExpr("];
2380    let mut count = 0usize;
2381    for (_, contents) in files {
2382        let lines: Vec<&str> = contents.lines().collect();
2383        let ranges = test_mod_ranges(&lines);
2384        for (i, line) in lines.iter().enumerate() {
2385            if in_test_range(i, &ranges) || is_line_comment(line) {
2386                continue;
2387            }
2388            if needles.iter().any(|needle| line.contains(needle)) {
2389                count += 1;
2390            }
2391        }
2392    }
2393    count
2394}
2395
2396// --- Gated probes 20-22: ts_raw_sites, ts_text_idents (#3681), emit_print_calls (1A.35b) ---------------
2397
2398/// Counts non-comment lines outside `#[cfg(test)]` modules that contain any of
2399/// `needles` with a non-identifier character (or the line start) immediately
2400/// before it, so `MyTsStmt::raw(` or `FooIdent(format!(` do not count. The same
2401/// scanner helpers [`verbatim_sites_violations`] uses. Text-level: a needle must
2402/// open on a single line (see [`ts_text_idents`] for the known multi-line gap).
2403fn opening_token_lines(files: &[(PathBuf, String)], needles: &[&str]) -> usize {
2404    production_lines_matching(files, |line| line_has_token(line, needles))
2405}
2406
2407/// The count of non-comment lines outside `#[cfg(test)]` modules for which
2408/// `hit` holds — the scan [`opening_token_lines`] and
2409/// [`emit_print_calls_violations`] share.
2410fn production_lines_matching(files: &[(PathBuf, String)], hit: impl Fn(&str) -> bool) -> usize {
2411    let mut count = 0usize;
2412    for (_, contents) in files {
2413        let lines: Vec<&str> = contents.lines().collect();
2414        let ranges = test_mod_ranges(&lines);
2415        for (i, line) in lines.iter().enumerate() {
2416            if in_test_range(i, &ranges) || is_line_comment(line) {
2417                continue;
2418            }
2419            if hit(line) {
2420                count += 1;
2421            }
2422        }
2423    }
2424    count
2425}
2426
2427/// Whether `line` contains any of `needles` with a non-identifier character (or
2428/// the line start) immediately before it. A method-call needle (`.finish_text(`)
2429/// carries its own left boundary; only an identifier-led needle needs the check.
2430fn line_has_token(line: &str, needles: &[&str]) -> bool {
2431    let is_word = |c: char| c.is_ascii_alphanumeric() || c == '_';
2432    needles.iter().any(|needle| {
2433        let dot_led = needle.starts_with('.');
2434        line.match_indices(needle)
2435            .any(|(at, _)| dot_led || !line[..at].chars().next_back().is_some_and(is_word))
2436    })
2437}
2438
2439/// #3681, split by origin in 1A.19: `TsStmt::raw(text, span)` construction sites
2440/// in the emitter's source, and (1A.36a) `TsStmt::raw_using(text, names)` ones: the
2441/// constructor that records the names a surviving fixed snippet uses is the same
2442/// escape hatch, so it is counted with `raw(` and the survivors stay measured. `TsStmt::raw` prints a whole statement verbatim — a
2443/// separate escape hatch from `TsStmt::verbatim`, which [`verbatim_sites`] counts and
2444/// this probe deliberately does not fold into it (that would break `verbatim_sites`'
2445/// history). Retired by building real nodes.
2446///
2447/// The one probe `ts_raw_sites` became two, by where the site lives
2448/// ([`is_testgen_path`]): production emission here, test-harness generation in
2449/// [`ts_raw_sites_testgen`]. The split is a reclassification: the two readings sum
2450/// to the old probe's (41 + 58 = 99 on the commit it landed), so nothing fell. Both
2451/// are growth probes ([`GROWTH_PROBES`]): each may only fall unless a pending file
2452/// `raises:` it with a reason.
2453///
2454/// Counts non-comment lines outside `#[cfg(test)]` modules in
2455/// [`codegen_family_files`] that are not test-harness generation. Text-level gaps:
2456/// matched on the line that opens the call, so a call split after `TsStmt::` is
2457/// missed; a bare `raw(` after a `use` of the type is not counted; two sites on one
2458/// line count once.
2459fn ts_raw_sites_emit(root: &Path) -> Probe {
2460    Probe {
2461        name: "ts_raw_sites_emit",
2462        gated: true,
2463        reads: ts_raw_sites_violations(&codegen_family_files(root), false).to_string(),
2464    }
2465}
2466
2467/// Test-harness generation's share of the old `ts_raw_sites` (see
2468/// [`ts_raw_sites_emit`]): the same count over [`is_testgen_path`] files.
2469fn ts_raw_sites_testgen(root: &Path) -> Probe {
2470    Probe {
2471        name: "ts_raw_sites_testgen",
2472        gated: true,
2473        reads: ts_raw_sites_violations(&codegen_family_files(root), true).to_string(),
2474    }
2475}
2476
2477/// Whether `rel` (relative to the `src/` of the crate it lives in, as
2478/// [`codegen_family_files`] gives it) generates the *test harness* rather than
2479/// production emission: `bynk-emit::testgen` (`testgen.rs`, `testgen/**`), which 1B.2a moved
2480/// there from the driver's `project/tests_emit/**`.
2481///
2482/// Two probes read it since 1B.5e (Decision H of #4054): `ts_raw_sites_emit` and
2483/// `ts_raw_sites_testgen`, because §8 has a row for each, and [`ast_importers`], because the
2484/// harness reads the AST by design. Every other probe over `bynk-emit/src` reads the whole
2485/// crate, the harness included.
2486fn is_testgen_path(rel: &Path) -> bool {
2487    rel.components().any(|c| {
2488        let c = c.as_os_str().to_string_lossy();
2489        c == "testgen" || c == "testgen.rs"
2490    })
2491}
2492
2493/// [`ts_raw_sites_emit`]'s and [`ts_raw_sites_testgen`]'s counting logic over an
2494/// explicit file list: the files [`is_testgen_path`] accepts when `testgen`, the
2495/// rest otherwise.
2496fn ts_raw_sites_violations(files: &[(PathBuf, String)], testgen: bool) -> usize {
2497    let part: Vec<(PathBuf, String)> = files
2498        .iter()
2499        .filter(|(p, _)| is_testgen_path(p) == testgen)
2500        .cloned()
2501        .collect();
2502    opening_token_lines(&part, &["TsStmt::raw(", "TsStmt::raw_using("])
2503}
2504
2505/// 1A.19: unconditional `thread_local!` declarations in `bynk-emit`'s production
2506/// source. Per-unit context travels in the unit's `EmitProjectCtx` and `ModuleCtx`;
2507/// a thread-local stood in for it twice (`FAULT_SOURCE`, `type_renames::SPELLINGS`),
2508/// which made a function's behaviour depend on its call stack. It reads 0 and a
2509/// growth probe ([`GROWTH_PROBES`]) keeps it there: a new one needs a pending
2510/// file's `raises:` with a reason.
2511///
2512/// Counts non-comment lines outside `#[cfg(test)]` modules in `bynk-emit/src` that
2513/// contain `thread_local!`, except one whose preceding attribute is a `cfg` that
2514/// names `test` (`#[cfg(test)]`, or `#[cfg(any(test, feature = "…"))]`): the
2515/// test-only counters are not compiled into a product build. `bynk-ts`, the
2516/// driver and the checker keep their own thread-locals, which this does not count.
2517fn emit_thread_locals(root: &Path) -> Probe {
2518    Probe {
2519        name: "emit_thread_locals",
2520        gated: true,
2521        reads: emit_thread_locals_violations(&rust_files_relative(&root.join("bynk-emit/src")))
2522            .to_string(),
2523    }
2524}
2525
2526/// [`emit_thread_locals`]'s counting logic over an explicit file list.
2527fn emit_thread_locals_violations(files: &[(PathBuf, String)]) -> usize {
2528    let mut count = 0usize;
2529    for (_, contents) in files {
2530        let lines: Vec<&str> = contents.lines().collect();
2531        let ranges = test_mod_ranges(&lines);
2532        for (i, line) in lines.iter().enumerate() {
2533            if in_test_range(i, &ranges)
2534                || is_line_comment(line)
2535                || !line_has_token(line, &["thread_local!"])
2536            {
2537                continue;
2538            }
2539            let attr = lines[..i]
2540                .iter()
2541                .rev()
2542                .map(|l| l.trim())
2543                .find(|l| !l.is_empty());
2544            let test_only = attr.is_some_and(cfg_is_test_only);
2545            if !test_only {
2546                count += 1;
2547            }
2548        }
2549    }
2550    count
2551}
2552
2553/// 1A.34 (#3735, Decision E): the silent fallbacks in `bynk-emit`'s production source, where a
2554/// missing checker fact (or a legitimate absence) is answered by writing `any` or `undefined`
2555/// instead of by `LowerCtx::missing_fact` (a reported fault) or by an `Option` rendered once as
2556/// `undefined_node()`. A growth probe ([`GROWTH_PROBES`]): it reads 0 and a new fallback needs a
2557/// pending file's `raises:` with a reason.
2558///
2559/// **The pattern, precisely.** A line counts when, outside comments and `#[cfg(test)]` modules,
2560/// it holds a *fallback position* and, after it on the same line, an *`any`/`undefined`
2561/// construction*:
2562/// - fallback positions: `.unwrap_or_else(`, `.unwrap_or(`, `.map_or(`, `.map_or_else(`,
2563///   and the match arms `_ =>`, `None =>`, `Err(_) =>`;
2564/// - constructions: a string literal `"any"`, a string literal that begins `"undefined`
2565///   (`"undefined"`, `"undefined as never"`, `"undefined /* .. */"`), which covers
2566///   `TsType::named("any")`, `ident("undefined")` and `Ident("undefined".to_string())`; the
2567///   named-widening helper's predecessor `any_ty` (call or function path); and the closure name
2568///   `undefined` (`unwrap_or_else(undefined)`).
2569///
2570/// So `.unwrap_or_else(|| "any")`, `_ => any_ty()` and `None => ident("undefined")` count, and
2571/// `.unwrap_or_else(undefined_node)` (a legitimate default, rendered once), a call to
2572/// `cx.missing_fact(..)` and `fn unnameable_receiver_type_arg() -> TsType { TsType::named("any") }`
2573/// (the one named widening: a function body, with no fallback position on its line) do not.
2574///
2575/// **Known gaps, accepted as the other line scanners accept theirs:** an arm whose value sits on
2576/// the next line, and a fallback spelt through a helper of another name, read as clean. The
2577/// sweep's classification of every remaining fallback is in the slice's PR, not in this count.
2578fn emit_silent_fallbacks(root: &Path) -> Probe {
2579    Probe {
2580        name: "emit_silent_fallbacks",
2581        gated: true,
2582        reads: emit_silent_fallbacks_violations(&rust_files_relative(&root.join("bynk-emit/src")))
2583            .to_string(),
2584    }
2585}
2586
2587/// Whether `line` holds a fallback position followed by an `any`/`undefined` construction
2588/// (see [`emit_silent_fallbacks`] for the pattern).
2589fn line_is_silent_fallback(line: &str) -> bool {
2590    const POSITIONS: [&str; 7] = [
2591        ".unwrap_or_else(",
2592        ".unwrap_or(",
2593        ".map_or(",
2594        ".map_or_else(",
2595        "_ =>",
2596        "None =>",
2597        "Err(_) =>",
2598    ];
2599    const CONSTRUCTIONS: [&str; 4] = ["\"any\"", "\"undefined", "any_ty", "undefined)"];
2600    POSITIONS.iter().any(|position| {
2601        line.match_indices(position).any(|(at, _)| {
2602            let rest = &line[at + position.len()..];
2603            CONSTRUCTIONS.iter().any(|c| rest.contains(c))
2604        })
2605    })
2606}
2607
2608/// [`emit_silent_fallbacks`]'s counting logic over an explicit file list.
2609fn emit_silent_fallbacks_violations(files: &[(PathBuf, String)]) -> usize {
2610    let mut count = 0usize;
2611    for (_, contents) in files {
2612        let lines: Vec<&str> = contents.lines().collect();
2613        let ranges = test_mod_ranges(&lines);
2614        for (i, line) in lines.iter().enumerate() {
2615            if in_test_range(i, &ranges) || is_line_comment(line) {
2616                continue;
2617            }
2618            if line_is_silent_fallback(line) {
2619                count += 1;
2620            }
2621        }
2622    }
2623    count
2624}
2625
2626/// Whether a `#[cfg(..)]` attribute line gates the next item on `test` alone, or on
2627/// `any(..)` with a bare `test` arm. Anything else counts as production: a `not(..)`
2628/// predicate (`#[cfg(not(test))]` compiles into every product build), `all(..)`,
2629/// and any predicate that merely contains the substring `test`
2630/// (`feature = "attestation"`). Review of #3746.
2631fn cfg_is_test_only(attr: &str) -> bool {
2632    let Some(pred) = attr
2633        .strip_prefix("#[cfg(")
2634        .and_then(|rest| rest.strip_suffix(")]"))
2635        .map(str::trim)
2636    else {
2637        return false;
2638    };
2639    if pred == "test" {
2640        return true;
2641    }
2642    let Some(arms) = pred
2643        .strip_prefix("any(")
2644        .and_then(|rest| rest.strip_suffix(')'))
2645    else {
2646        return false;
2647    };
2648    !arms.contains("not(") && arms.split(',').any(|arm| arm.trim() == "test")
2649}
2650
2651/// #3681: `TsExpr::Ident(format!(…))` sites — arbitrary expression text wrapped in
2652/// a node documented as holding an identifier (`bynk-ts/src/program/expr.rs`). Retired
2653/// by using the right expression node. A growth probe ([`GROWTH_PROBES`]).
2654///
2655/// Counts non-comment lines outside `#[cfg(test)]` modules in
2656/// [`codegen_family_files`] containing `Ident(format!(` — which covers both
2657/// `TsExpr::Ident(format!(` and the bare form after a `use`. **Known multi-line
2658/// gap** (the same kind of text-level limit [`ts_writes`] records): the opening
2659/// token and `format!(` are matched on one line, so `TsExpr::Ident(` with
2660/// `format!(` on the next line is missed, as is any `Ident(` built from a
2661/// `String` variable or a helper returning text. Do not build a parser for it.
2662fn ts_text_idents(root: &Path) -> Probe {
2663    Probe {
2664        name: "ts_text_idents",
2665        gated: true,
2666        reads: ts_text_idents_violations(&codegen_family_files(root)).to_string(),
2667    }
2668}
2669
2670/// [`ts_text_idents`]'s counting logic over an explicit file list.
2671fn ts_text_idents_violations(files: &[(PathBuf, String)]) -> usize {
2672    opening_token_lines(files, &["Ident(format!("])
2673}
2674
2675/// 1A.35b (#3736, Decision F): the `print_expr(`, `print_stmt(` and `print_type(` calls in
2676/// `bynk-emit`'s production source. Each prints a tree to text, which is a round trip unless it is
2677/// one of the named boundaries (the final program print, `lower_block_to_async_body`, the
2678/// assembly of a surviving foreign `raw` statement or text template); the PR that set the
2679/// baseline lists them. A growth probe ([`GROWTH_PROBES`]): it may only fall unless a pending
2680/// file `raises:` it with a reason, so a round trip cannot creep back in.
2681///
2682/// **End state (1B.2b):** the probe reads 0. The one line it read after 1A.39a was
2683/// `extend_printed_at`, the test harness's entry that prints the statements it is given, at a
2684/// depth. 1B.2a moved the harness into `bynk-emit::testgen` and the probe skips that module
2685/// ([`emit_files_by_origin`]), as [`ts_raw_sites_emit`] does; 1B.2b moved `extend_printed_at`
2686/// there too (`testgen/case_body.rs`), and [`testgen_print_calls`] reads it with the harness's own
2687/// 43, so it reads 44.
2688/// The final program print (`bynk_ts::print`) and `lower_block_to_async_body` count no line.
2689///
2690/// Counts non-comment lines outside `#[cfg(test)]` modules in `bynk-emit/src` that contain
2691/// `print_expr(`, `print_stmt(` or `print_type(` (a call), or the same name as a path
2692/// (`.map(bynk_ts::print_type)`). `print_stmt_with_spans(` and the like are other names and do not
2693/// match. Also counted: a path as an argument (`print_type)` or `print_type,`) and an `as` rename of
2694/// the import (`print_expr as pe`). Text-level gaps, as for the other line scanners: two calls on
2695/// one line count once, a call whose name is on the next line is missed, and a call through a
2696/// renamed binding (`pe(&e)`) is counted only at its `use` line.
2697fn emit_print_calls(root: &Path) -> Probe {
2698    Probe {
2699        name: "emit_print_calls",
2700        gated: true,
2701        reads: emit_print_calls_violations(&rust_files_relative(&root.join("bynk-emit/src")))
2702            .to_string(),
2703    }
2704}
2705
2706/// [`emit_print_calls`]'s counting logic over an explicit file list.
2707fn emit_print_calls_violations(files: &[(PathBuf, String)]) -> usize {
2708    const NAMES: [&str; 3] = ["print_expr", "print_stmt", "print_type"];
2709    // A call, a path as the last argument (`)`), a path as an earlier argument (`,`) and an `as`
2710    // rename of the import (`use bynk_ts::print_expr as pe;`).
2711    const SUFFIXES: [&str; 4] = ["(", ")", ",", " as "];
2712    let needles: Vec<String> = NAMES
2713        .iter()
2714        .flat_map(|n| SUFFIXES.iter().map(move |s| format!("{n}{s}")))
2715        .collect();
2716    let needles: Vec<&str> = needles.iter().map(String::as_str).collect();
2717    production_lines_matching(files, |line| line_has_token(line, &needles))
2718}
2719
2720/// 1A.36a (#3737, Decision F): the functions in `bynk-emit`'s production source that decide,
2721/// ahead of the body, a fact the built tree will carry anyway: a name segment `needs`,
2722/// `mentions` or `uses` (`agent_needs_rehydrate`, `file_mentions_connection`,
2723/// `uses_json_codec`), less [`IMPORT_PREDICTION_ALLOWLIST`], the resolved-fact queries that
2724/// decide a binding, an emitted helper or a structural walk rather than an import (Decision B).
2725/// The 17 of the exit row is not read from a name pattern over the driver too: this probe counts
2726/// `bynk-emit` and its allowlist. 1A.36b-1 deleted the header's predicates and renamed the one
2727/// that survives for another reason (`agent_gates_rehydration`, which also decides the
2728/// `commitState` an agent emits), so it reads 0. A growth probe
2729/// ([`GROWTH_PROBES`]): it may only fall unless a pending file `raises:` it with a reason, so a
2730/// new prediction cannot creep in.
2731///
2732/// Counts non-comment lines outside `#[cfg(test)]` modules in `bynk-emit/src` that declare a
2733/// `fn` whose name has such a segment (split on `_`) and is not allowlisted. Text-level gaps, as
2734/// for the other line scanners: a `fn` whose name is on the next line is missed, and two
2735/// declarations on one line count once.
2736fn import_prediction_fns(root: &Path) -> Probe {
2737    Probe {
2738        name: "import_prediction_fns",
2739        gated: true,
2740        reads: import_prediction_fns_violations(&rust_files_relative(&root.join("bynk-emit/src")))
2741            .to_string(),
2742    }
2743}
2744
2745/// The resolved-fact queries [`import_prediction_fns`] does not count (Decision B of #3737).
2746/// They decide a Worker's bindings from the checker's resolved `Callee` map
2747/// (`unit_table_uses_emit`, `unit_table_uses_idempotency`, `call_handler_needs_exec`), whether a
2748/// context's `deps` interface carries `__eventsDispatch` (`commons_uses_emit`), or are structural
2749/// type walks (`mentions_decimal`, `mentions_factory_param`). None of them decides an import.
2750///
2751/// 1B.5e (Decision H of #4054) adds `double_uses`, which the widened scan reaches. It is the
2752/// opposite of a prediction: it lists the runtime and sibling names an authored test double's
2753/// fixed body *spells*, which `TsStmt::raw_using` declares so the derived header imports them
2754/// (Decision A). A guard test in `testgen/stubs.rs` holds the list against the body's words.
2755const IMPORT_PREDICTION_ALLOWLIST: [&str; 7] = [
2756    "unit_table_uses_emit",
2757    "unit_table_uses_idempotency",
2758    "call_handler_needs_exec",
2759    "commons_uses_emit",
2760    "mentions_decimal",
2761    "mentions_factory_param",
2762    "double_uses",
2763];
2764
2765/// The name of the function a line declares (`fn name(`, after any `pub`, `pub(crate)`, `const`,
2766/// `async` or `unsafe`), or `None` when the line declares none.
2767fn declared_fn_name(line: &str) -> Option<&str> {
2768    let is_word = |c: char| c.is_ascii_alphanumeric() || c == '_';
2769    let at = line
2770        .match_indices("fn ")
2771        .find(|(at, _)| !line[..*at].chars().next_back().is_some_and(is_word))?
2772        .0;
2773    let rest = line[at + 3..].trim_start();
2774    let end = rest.find(|c: char| !is_word(c)).unwrap_or(rest.len());
2775    (end > 0).then(|| &rest[..end])
2776}
2777
2778/// [`import_prediction_fns`]'s counting logic over an explicit file list.
2779fn import_prediction_fns_violations(files: &[(PathBuf, String)]) -> usize {
2780    production_lines_matching(files, |line| {
2781        declared_fn_name(line).is_some_and(|name| {
2782            name.split('_')
2783                .any(|seg| matches!(seg, "needs" | "mentions" | "uses"))
2784                && !IMPORT_PREDICTION_ALLOWLIST.contains(&name)
2785        })
2786    })
2787}
2788
2789/// 1B.4a (#4051, Decision E): the production helpers in `bynk-emit` that are one `bynk_ts`
2790/// constructor over their parameters, each a local spelling of a shape `ts_build` defines once
2791/// (`ident`, `str_lit`, `member`, `call`, `const_`, ...), plus each `as` rename in a
2792/// `use crate::ts_build::{..}` clause. Before 1B.4a every file defined its own, in up to five
2793/// spellings; 1B.4a left only the renames, and 1B.4b (Phase 2) took the probe to 0, where it stays as
2794/// a guard against a new local wrapper or an `as` rename in a split. A growth probe ([`GROWTH_PROBES`]): a new local wrapper in a
2795/// later slice needs a `raises:` line.
2796///
2797/// A *definition* counts when it lies outside `ts_build.rs` and outside `#[cfg(test)]` modules, is
2798/// a `fn` returning `TsExpr` or `TsStmt`, and has a body of at most eight lines that applies
2799/// exactly one constructor: a `Ts*` variant or associated function, or two for one shape
2800/// (`TsExpr::Lit(TsLit::Str(..))`), with any `Box::new`, `Some`, `vec![..]` around its arguments,
2801/// or one call to a helper that is itself a builder (`id` over `ident_node`, `ne` over `binary`).
2802/// The body has no string literal, `self`, `let`, `match`, `if`, loop, iterator or `format!`, and
2803/// no `.clone()`, so it is a function of its parameters alone; a path value must be a `Ts*` one
2804/// (`TsBinaryOp::StrictEq`, not `VerbatimOrigin::FormFieldSpecs`). A helper with no parameters is a
2805/// constant (`empty_deps`, `plain_json_test`, `deserialise_path_param`), not a builder. A helper
2806/// that composes two constructors (`if_then`, `applied`, `tag_const`) says something about a
2807/// construct, not about TypeScript, and does not count. Text-level gaps, as for the other line
2808/// scanners: a signature split over more than twelve lines is missed, the helpers a body calls are
2809/// known by name only, a wrapper with a `where` clause or one returning `TsStmt` through a type
2810/// alias is missed, and a rename inside a nested `use` tree (`use crate::{ts_build::{ident as id},
2811/// ..}`) is not matched by the alias scan; closures (`let ident = |n| ..`) are not scanned.
2812fn node_builder_defs(root: &Path) -> Probe {
2813    Probe {
2814        name: "node_builder_defs",
2815        gated: true,
2816        reads: node_builder_defs_count(&codegen_family_files(root)).to_string(),
2817    }
2818}
2819
2820/// [`node_builder_defs`]'s counting logic over an explicit file list.
2821fn node_builder_defs_count(files: &[(PathBuf, String)]) -> usize {
2822    let (defs, aliases) = node_builder_defs_found(files);
2823    defs.len() + aliases
2824}
2825
2826/// The `(file, line, name)` of each counted definition, and the number of `as` renames in
2827/// `use ..::ts_build::{..}` clauses. [`node_builder_defs_count`] sums them; a test reads the
2828/// names.
2829fn node_builder_defs_found(files: &[(PathBuf, String)]) -> (Vec<(PathBuf, usize, String)>, usize) {
2830    use std::collections::BTreeSet;
2831    struct Candidate {
2832        file: PathBuf,
2833        line: usize,
2834        name: String,
2835        helper_calls: Vec<String>,
2836        constructs: bool,
2837    }
2838    let call = regex::Regex::new(r"((?:\w+::)*\w+)\s*[({]").expect("call pattern");
2839    let path_value = regex::Regex::new(r"(?:\w+::)+\w+").expect("path pattern");
2840    let forbidden = regex::Regex::new(
2841        r#""|\bself\b|\blet\b|\bmatch\b|\bif\b|\bfor\b|\bloop\b|\bwhile\b|format!|\.iter|\.map\(|\.collect|\.clone\(\)"#,
2842    )
2843    .expect("forbidden pattern");
2844    let ret = regex::Regex::new(r"->\s*(?:bynk_ts::)?Ts(?:Expr|Stmt)\s*$").expect("return pattern");
2845    let fn_name = regex::Regex::new(r"\bfn\s+(\w+)").expect("fn pattern");
2846    let ts_alias =
2847        regex::Regex::new(r"use\s+(?:crate|super|self)(?:::\w+)*::ts_build::(\{[^;]*\}|[^;]*)\s*;")
2848            .expect("use pattern");
2849    let rename = regex::Regex::new(r"\w+\s+as\s+\w+").expect("rename pattern");
2850
2851    let mut known: BTreeSet<String> = BTreeSet::new();
2852    let mut candidates: Vec<Candidate> = Vec::new();
2853    let mut aliases = 0usize;
2854    for (path, contents) in files {
2855        let is_ts_build = path.file_name().is_some_and(|n| n == "ts_build.rs");
2856        let lines: Vec<&str> = contents.lines().collect();
2857        let ranges = test_mod_ranges(&lines);
2858        let production: Vec<&str> = lines
2859            .iter()
2860            .enumerate()
2861            .map(|(i, l)| {
2862                if in_test_range(i, &ranges) || is_line_comment(l) {
2863                    ""
2864                } else {
2865                    *l
2866                }
2867            })
2868            .collect();
2869        if is_ts_build {
2870            for l in &production {
2871                if let Some(c) = fn_name.captures(l) {
2872                    known.insert(c[1].to_string());
2873                }
2874            }
2875            continue;
2876        }
2877        let text = production.join("\n");
2878        for m in ts_alias.captures_iter(&text) {
2879            aliases += rename.find_iter(&m[1]).count();
2880        }
2881        let mut i = 0;
2882        while i < production.len() {
2883            let Some(name) = fn_name.captures(production[i]).map(|c| c[1].to_string()) else {
2884                i += 1;
2885                continue;
2886            };
2887            // The signature runs to the first `{`; the body to its matching `}`.
2888            let mut head = String::new();
2889            let mut end = i;
2890            let mut opened = None;
2891            while end < production.len() && end < i + 12 {
2892                if let Some(at) = production[end].find('{') {
2893                    head.push_str(&production[end][..at]);
2894                    opened = Some((end, at));
2895                    break;
2896                }
2897                head.push_str(production[end]);
2898                head.push(' ');
2899                end += 1;
2900            }
2901            let Some((open_line, open_at)) = opened else {
2902                i += 1;
2903                continue;
2904            };
2905            // A helper with no parameters is a constant (`empty_deps`, `undefined`), not a builder:
2906            // the proposal leaves the constant helpers alone.
2907            let after_name = fn_name.find(&head).map_or("", |m| &head[m.end()..]);
2908            let no_params = after_name
2909                .split_once('(')
2910                .and_then(|(_, rest)| rest.split_once(')'))
2911                .is_some_and(|(params, _)| params.trim().is_empty());
2912            if !ret.is_match(head.trim_end()) || no_params {
2913                i += 1;
2914                continue;
2915            }
2916            let mut depth = 0i32;
2917            let mut body = String::new();
2918            let mut closed = false;
2919            let mut body_lines = 0usize;
2920            'scan: for (offset, line) in production[open_line..].iter().enumerate() {
2921                body_lines += 1;
2922                if body_lines > 9 {
2923                    break;
2924                }
2925                let from = if offset == 0 { open_at } else { 0 };
2926                for ch in line[from..].chars() {
2927                    match ch {
2928                        '{' => {
2929                            depth += 1;
2930                            if depth == 1 {
2931                                continue;
2932                            }
2933                        }
2934                        '}' => {
2935                            depth -= 1;
2936                            if depth == 0 {
2937                                closed = true;
2938                                break 'scan;
2939                            }
2940                        }
2941                        _ => {}
2942                    }
2943                    body.push(ch);
2944                }
2945                body.push('\n');
2946            }
2947            if !closed || body_lines > 9 || forbidden.is_match(&body) {
2948                i += 1;
2949                continue;
2950            }
2951            // A path value (not a call) must be a `Ts*` one.
2952            let bad_path = path_value.find_iter(&body).any(|m| {
2953                let rest = body[m.end()..].trim_start();
2954                let is_call = rest.starts_with('(') || rest.starts_with('{');
2955                !is_call && !m.as_str().trim_start_matches("bynk_ts::").starts_with("Ts")
2956            });
2957            if bad_path {
2958                i += 1;
2959                continue;
2960            }
2961            let mut helper_calls = Vec::new();
2962            let mut constructs = false;
2963            let mut ctor_tokens = 0usize;
2964            for c in call.captures_iter(&body) {
2965                let at = c.get(1).map_or(0, |m| m.start());
2966                // A method call (`s.into()`) is neither a constructor nor a helper.
2967                if body[..at].ends_with('.') {
2968                    continue;
2969                }
2970                let callee = &c[1];
2971                let local = callee.trim_start_matches("bynk_ts::");
2972                if local.starts_with("Ts") {
2973                    constructs = true;
2974                    ctor_tokens += 1;
2975                } else if !matches!(callee, "Box::new" | "Some" | "Ok" | "Vec::new" | "Box") {
2976                    helper_calls.push(callee.to_string());
2977                }
2978            }
2979            // `TsExpr::Lit(TsLit::Str(..))` and `TsStmt::const_stmt(TsBindingName::Ident(..), ..)` are
2980            // one shape; three or more nested constructors build a structure of their own.
2981            if ctor_tokens > 2 {
2982                i += 1;
2983                continue;
2984            }
2985            candidates.push(Candidate {
2986                file: path.clone(),
2987                line: i + 1,
2988                name,
2989                helper_calls,
2990                constructs,
2991            });
2992            i += 1;
2993        }
2994    }
2995    // A candidate whose one call is a helper counts when that helper is itself a builder: a
2996    // fixed point over the names `ts_build` defines and the one-constructor candidates.
2997    for c in &candidates {
2998        if c.helper_calls.is_empty() && c.constructs {
2999            known.insert(c.name.clone());
3000        }
3001    }
3002    loop {
3003        let before = known.len();
3004        for c in &candidates {
3005            if !c.constructs && c.helper_calls.len() == 1 && known.contains(&c.helper_calls[0]) {
3006                known.insert(c.name.clone());
3007            }
3008        }
3009        if known.len() == before {
3010            break;
3011        }
3012    }
3013    let defs = candidates
3014        .into_iter()
3015        .filter(|c| {
3016            (c.helper_calls.is_empty() && c.constructs)
3017                || (!c.constructs
3018                    && c.helper_calls.len() == 1
3019                    && known.contains(&c.helper_calls[0]))
3020        })
3021        .map(|c| (c.file, c.line, c.name))
3022        .collect();
3023    (defs, aliases)
3024}
3025
3026/// 1D.1 (#3929, the ruling on Decision A): the production sites in `bynk/src/deploy/**` that
3027/// call or define a per-kind ledger accessor (`recorded_kv`, `record_r2`, `forget_vectorize`,
3028/// `allocate_ratelimit`, …), each of which a `ResourceKind` replaces with its `LedgerTable`. It
3029/// read 68 on `main` before 1D.1a; each 1D.1 slice deletes its kinds' accessors, and 1D.1e takes
3030/// it to 0. A growth probe ([`GROWTH_PROBES`]): it may only fall unless a pending file `raises:`
3031/// it with a reason, so a converted kind's accessor cannot come back and an unconverted kind
3032/// cannot grow one.
3033///
3034/// Counts non-comment lines outside `#[cfg(test)]` modules and wholly-test files
3035/// ([`is_test_only_file`]) in `bynk/src/deploy` that match [`DEPLOY_KIND_ACCESSOR`]. Text-level
3036/// gaps, as for the other line scanners: two sites on one line count once, and a definition with
3037/// generics (`fn recorded_r2<'a>(`) is not matched, which is how #3929's pattern read 68. Its
3038/// callers are, so a kind is converted only once they are gone.
3039fn deploy_kind_accessors(root: &Path) -> Probe {
3040    Probe {
3041        name: "deploy_kind_accessors",
3042        gated: true,
3043        reads: deploy_kind_accessors_violations(&rust_files_relative(
3044            &root.join("bynk/src/deploy"),
3045        ))
3046        .to_string(),
3047    }
3048}
3049
3050/// A call or definition of a per-kind ledger accessor: #3929's "Tooling delta" pattern.
3051const DEPLOY_KIND_ACCESSOR: &str = r"\b(recorded_(kv|kv_binding|r2|d1|vectorize|hyperdrive|ratelimit|stored_secret|mtls_certificate|ai_search|container_image)|record_(kv|r2|vectorize|d1|hyperdrive|stored_secret|ai_search|mtls_certificate|container_image|queue|reused_queue)|forget_(kv|vectorize|hyperdrive|undeclared_ratelimits)|allocate_ratelimit)\(";
3052
3053/// [`deploy_kind_accessors`]'s counting logic over an explicit file list, paths relative to
3054/// `bynk/src/deploy`.
3055fn deploy_kind_accessors_violations(files: &[(PathBuf, String)]) -> usize {
3056    let accessor = regex::Regex::new(DEPLOY_KIND_ACCESSOR).expect("the accessor pattern compiles");
3057    // Deploy's test modules are `pub(crate) mod tests`, so other modules' tests can share their
3058    // helpers; [`test_mod_ranges`] reads a test module by its `mod ` line, so the visibility is
3059    // dropped here rather than there, where it would move the probes that already read it.
3060    let gated = gated_stems(files);
3061    let production: Vec<(PathBuf, String)> = files
3062        .iter()
3063        .filter(|(path, _)| !is_test_only_file(&path.to_string_lossy().replace('\\', "/"), &gated))
3064        .map(|(path, contents)| {
3065            let contents: Vec<&str> = contents
3066                .lines()
3067                .map(|line| {
3068                    line.strip_prefix("pub(crate) mod ")
3069                        .map_or(line, |_| &line[11..])
3070                })
3071                .collect();
3072            (path.clone(), contents.join("\n"))
3073        })
3074        .collect();
3075    production_lines_matching(&production, |line| accessor.is_match(line))
3076}
3077
3078/// 1D.2 (#4001, the ruling on 1D.2a): the production sites in `bynk/src/deploy/**` that write
3079/// `bynk.deploy.lock` or ask a kind's context to: a call of `write_lock`, or of `cx.record`,
3080/// `cx.change` or `cx.commit`, the 1D.1 context's writes. It read 25 on `main` before 1D.2a (the
3081/// 23 kind sites, `ApplyCx::commit`'s own write and `run`'s post-push write) and 1 after it, the
3082/// apply's one `LedgerWriter`. `revert.rs` is left out by path: its write, per rolled-back Worker,
3083/// is `bynk revert`'s, not the apply's. A growth probe ([`GROWTH_PROBES`]): a second write site
3084/// needs a pending file that `raises:` it with a reason.
3085///
3086/// Counts non-comment lines outside `#[cfg(test)]` modules and wholly-test files
3087/// ([`is_test_only_file`]) in `bynk/src/deploy` that match [`DEPLOY_LEDGER_WRITE`], less the line
3088/// that defines `write_lock`.
3089fn deploy_ledger_writes(root: &Path) -> Probe {
3090    Probe {
3091        name: "deploy_ledger_writes",
3092        gated: true,
3093        reads: deploy_ledger_writes_violations(&rust_files_relative(&root.join("bynk/src/deploy")))
3094            .to_string(),
3095    }
3096}
3097
3098/// A ledger write, or a 1D.1 context's: #4001's "Probes and guards" pattern.
3099const DEPLOY_LEDGER_WRITE: &str = r"\bwrite_lock\(|\bcx\.(record|change|commit)\(";
3100
3101/// [`deploy_ledger_writes`]'s counting logic over an explicit file list, paths relative to
3102/// `bynk/src/deploy`.
3103fn deploy_ledger_writes_violations(files: &[(PathBuf, String)]) -> usize {
3104    let write = regex::Regex::new(DEPLOY_LEDGER_WRITE).expect("the write pattern compiles");
3105    let definition = regex::Regex::new(r"\bfn write_lock\(").expect("the definition compiles");
3106    // As for [`deploy_kind_accessors_violations`]: deploy's test modules are `pub(crate) mod tests`.
3107    let gated = gated_stems(files);
3108    let production: Vec<(PathBuf, String)> = files
3109        .iter()
3110        .filter(|(path, _)| {
3111            let path = path.to_string_lossy().replace('\\', "/");
3112            !is_test_only_file(&path, &gated) && path != "revert.rs"
3113        })
3114        .map(|(path, contents)| {
3115            let contents: Vec<&str> = contents
3116                .lines()
3117                .map(|line| {
3118                    line.strip_prefix("pub(crate) mod ")
3119                        .map_or(line, |_| &line[11..])
3120                })
3121                .collect();
3122            (path.clone(), contents.join("\n"))
3123        })
3124        .collect();
3125    production_lines_matching(&production, |line| {
3126        write.is_match(line) && !definition.is_match(line)
3127    })
3128}
3129
3130// --- Gated probe: cloudflare_client_sites (1D.3a) -------------------------------------------
3131
3132/// 1D.3 (#4043, Decision L): the production sites in `bynk/src` that reach Cloudflare without
3133/// going through the `cloudflare` module: a wrangler spawn built at the call site
3134/// (`wrangler_command(` or `tools::wrangler::command(`), or a REST client constructed there
3135/// (`Rest {`). It read 34 on `main` before 1D.3a (24 wrangler call sites and 10 REST
3136/// constructions), falls as 1D.3a and 1D.3b move the wrangler calls behind `CloudflareApi`, and
3137/// reaches 0 when 1D.3c builds the one REST client per run. A growth probe ([`GROWTH_PROBES`]): a
3138/// new site needs a pending file that `raises:` it with a reason.
3139///
3140/// Counts non-comment lines outside `#[cfg(test)]` modules, wholly-test files
3141/// ([`is_test_only_file`]) and `bynk/src/cloudflare/`, less the lines that define
3142/// `wrangler_command` or declare the `Rest` type (`struct Rest {`, `impl … Rest {`). A REST
3143/// construction spans several lines (its credentials, its agent); only its `Rest {` line counts.
3144fn cloudflare_client_sites(root: &Path) -> Probe {
3145    Probe {
3146        name: "cloudflare_client_sites",
3147        gated: true,
3148        reads: cloudflare_client_sites_violations(&rust_files_relative(&root.join("bynk/src")))
3149            .to_string(),
3150    }
3151}
3152
3153/// A wrangler spawn built at the call site, or a REST client constructed there.
3154const CLOUDFLARE_CLIENT_SITE: &str = r"\bwrangler_command\(|\btools::wrangler::command\(|\bRest \{";
3155
3156/// [`cloudflare_client_sites`]'s counting logic over an explicit file list, paths relative to
3157/// `bynk/src`.
3158fn cloudflare_client_sites_violations(files: &[(PathBuf, String)]) -> usize {
3159    let site = regex::Regex::new(CLOUDFLARE_CLIENT_SITE).expect("the site pattern compiles");
3160    let declaration =
3161        regex::Regex::new(r"\bfn wrangler_command\(|\bstruct Rest \{|\bimpl\b.*\bRest \{")
3162            .expect("the declaration pattern compiles");
3163    // As for [`deploy_kind_accessors_violations`]: the crate's test modules may be `pub(crate)`.
3164    let gated = gated_stems(files);
3165    let production: Vec<(PathBuf, String)> = files
3166        .iter()
3167        .filter(|(path, _)| {
3168            let path = path.to_string_lossy().replace('\\', "/");
3169            !is_test_only_file(&path, &gated)
3170                && !path.starts_with("cloudflare/")
3171                && path != "test_support.rs"
3172        })
3173        .map(|(path, contents)| {
3174            let contents: Vec<&str> = contents
3175                .lines()
3176                .map(|line| {
3177                    line.strip_prefix("pub(crate) mod ")
3178                        .map_or(line, |_| &line[11..])
3179                })
3180                .collect();
3181            (path.clone(), contents.join("\n"))
3182        })
3183        .collect();
3184    production_lines_matching(&production, |line| {
3185        site.is_match(line) && !declaration.is_match(line)
3186    })
3187}
3188
3189// --- Gated probe: env_protocol_literals (1D.5a) ---------------------------------------------
3190
3191/// Back-half paydown 1D.5a (#4003, Decision H): production Rust lines that spell a name of the
3192/// cross-language `BYNK_*` protocol themselves, instead of using
3193/// `bynk_project::env_protocol`'s constant. The pattern is the table: a `BYNK_` or `__BYNK_`
3194/// token counts when [`bynk_project::env_protocol::entry_of`] places it (an entry's name, or a
3195/// member of a prefix family), so a name added to the table is measured at once and the probe
3196/// cannot drift from it.
3197///
3198/// It read 36 on `main` before 1D.5a. After it, the residual is named: the three literals in
3199/// `bynk-emit/src/testgen/test_main.rs`, which 1B.2a moved there from the driver untouched
3200/// (a follow-up replaces them there), and `bynk/src/deploy/config.rs`'s
3201/// `BYNK_DATASET_`, inside `synthesise_environment_block`, which 1C.2 deletes. A growth probe
3202/// ([`GROWTH_PROBES`]): it may only fall unless a pending file `raises:` it with a reason, so a
3203/// new bare protocol literal fails the gate.
3204///
3205/// Counts non-comment lines outside `#[cfg(test)]` modules (deploy's `pub(crate) mod tests`
3206/// included) and wholly-test files ([`is_test_only_file`]) in every workspace crate's `src/`,
3207/// except `xtask` (repo automation, not shipped), the test-only crates `bynk-tests` and
3208/// `bynk-testkit`, the table itself, and `bynk-syntax/src/diagnostics.rs`, whose explanations
3209/// name the edge-key families as prose, not as uses. Text-level gaps, as for the other line
3210/// scanners: two names on one line count once, and a name in a block comment counts.
3211fn env_protocol_literals(root: &Path) -> Probe {
3212    let files: Vec<(PathBuf, String)> = workspace_crate_src_files(root)
3213        .into_iter()
3214        .filter(|(krate, _, _)| !matches!(krate.as_str(), "xtask" | "bynk-tests" | "bynk-testkit"))
3215        .map(|(krate, path, contents)| (Path::new(&krate).join("src").join(path), contents))
3216        .collect();
3217    Probe {
3218        name: "env_protocol_literals",
3219        gated: true,
3220        reads: env_protocol_literals_violations(&files).to_string(),
3221    }
3222}
3223
3224/// The files [`env_protocol_literals`] never counts, from the repo root.
3225const ENV_PROTOCOL_LITERALS_EXEMPT: [&str; 2] = [
3226    "bynk-project/src/env_protocol.rs",
3227    "bynk-syntax/src/diagnostics.rs",
3228];
3229
3230/// [`env_protocol_literals`]'s counting logic over an explicit file list, paths from the repo
3231/// root.
3232fn env_protocol_literals_violations(files: &[(PathBuf, String)]) -> usize {
3233    let token = regex::Regex::new(r"\b(__)?BYNK_[A-Z0-9_]+").expect("the token pattern compiles");
3234    let gated = gated_stems(files);
3235    let production: Vec<(PathBuf, String)> = files
3236        .iter()
3237        .filter(|(path, _)| {
3238            let rel = path.to_string_lossy().replace('\\', "/");
3239            !is_test_only_file(&rel, &gated)
3240                && !ENV_PROTOCOL_LITERALS_EXEMPT.contains(&rel.as_str())
3241        })
3242        .map(|(path, contents)| {
3243            // As in [`deploy_kind_accessors_violations`]: a `pub(crate) mod tests` is a test
3244            // module, which [`test_mod_ranges`] reads only by its `mod ` line.
3245            let contents: Vec<&str> = contents
3246                .lines()
3247                .map(|line| {
3248                    line.strip_prefix("pub(crate) mod ")
3249                        .map_or(line, |_| &line[11..])
3250                })
3251                .collect();
3252            (path.clone(), contents.join("\n"))
3253        })
3254        .collect();
3255    production_lines_matching(&production, |line| {
3256        token
3257            .find_iter(line)
3258            .any(|m| bynk_project::env_protocol::entry_of(m.as_str()).is_some())
3259    })
3260}
3261
3262// --- Gated probe: binding_kind_homes (1C.1b) -------------------------------------------------
3263
3264/// Back-half paydown 1C.1b (#4031, Decision G): the places a binding kind is defined, the Phase 1
3265/// exit row "Places a binding kind is defined" (§8 of the track). The number of production `.rs`
3266/// files in `bynk-check`, `bynk-emit`, `bynk-driver` and `bynk`, other than the vocabulary file
3267/// `bynk-check/src/worker_bindings.rs` (the one enum, [`BINDING_KIND_VOCABULARY`]), that contain
3268/// either
3269///
3270/// - a construction of a `BindingSource` value: a line matching `source: (\w+::)*BindingSource::`
3271///   or `=> (\w+::)*BindingSource::\w+( {|,|$)`; or
3272/// - a `#[derive(..Deserialize..)]` struct whose name ends in `Binding`, `Stanza` or
3273///   `ManifestEntry`: a parallel definition of a binding kind that a serialised file is read into.
3274///
3275/// Rendering per kind (TOML, TypeScript types, test doubles) is not counted: a renderer has to
3276/// match on the kind, and it matches on the one enum.
3277///
3278/// It read 3 on `main` before 1C.1 (the driver's `worker_bindings.rs`, `wrangler.rs` and the
3279/// CLI's `deploy/config.rs`), reads 2 after 1C.1b (`bindings.rs` and `config.rs`) and reads 1 after
3280/// 1C.3b, which replaces the CLI's stanza structs with the model: the §8 target of 1
3281/// (`WorkerBindings`). A growth probe ([`GROWTH_PROBES`]): it may only fall unless a pending file
3282/// `raises:` it with a reason.
3283///
3284/// Counts files, not lines, so the many construction lines of the one model count once. Skips
3285/// `#[cfg(test)]` modules (deploy's `pub(crate) mod tests` included), wholly-test files
3286/// ([`is_test_only_file`]) and comment lines. Text-level gaps, as for the other line scanners.
3287fn binding_kind_homes(root: &Path) -> Probe {
3288    let mut files = Vec::new();
3289    for krate in ["bynk-check", "bynk-emit", "bynk-driver", "bynk"] {
3290        for (path, contents) in rust_files_relative(&root.join(krate).join("src")) {
3291            files.push((Path::new(krate).join("src").join(path), contents));
3292        }
3293    }
3294    Probe {
3295        name: "binding_kind_homes",
3296        gated: true,
3297        reads: binding_kind_homes_files(&files).len().to_string(),
3298    }
3299}
3300
3301/// The one file that may define a binding kind: the vocabulary, from the repo root.
3302const BINDING_KIND_VOCABULARY: &str = "bynk-check/src/worker_bindings.rs";
3303
3304/// [`binding_kind_homes`]' counting logic over an explicit file list, paths from the repo root:
3305/// the files that define a binding kind outside the vocabulary.
3306fn binding_kind_homes_files(files: &[(PathBuf, String)]) -> Vec<String> {
3307    let construction = regex::Regex::new(
3308        r"source:\s*(\w+::)*BindingSource::|=>\s*(\w+::)*BindingSource::\w+(\s*\{|,|$)",
3309    )
3310    .expect("the construction pattern compiles");
3311    let stanza = regex::Regex::new(r"\bstruct\s+\w+(Binding|Stanza|ManifestEntry)\b")
3312        .expect("the stanza pattern compiles");
3313    let gated = gated_stems(files);
3314    let mut homes = Vec::new();
3315    for (path, contents) in files {
3316        let rel = path.to_string_lossy().replace('\\', "/");
3317        if rel == BINDING_KIND_VOCABULARY || is_test_only_file(&rel, &gated) {
3318            continue;
3319        }
3320        // As in [`deploy_kind_accessors_violations`]: a `pub(crate) mod tests` is a test module,
3321        // which [`test_mod_ranges`] reads only by its `mod ` line.
3322        let owned: Vec<String> = contents
3323            .lines()
3324            .map(|line| match line.strip_prefix("pub(crate) mod ") {
3325                Some(rest) => format!("mod {rest}"),
3326                None => line.to_string(),
3327            })
3328            .collect();
3329        let lines: Vec<&str> = owned.iter().map(String::as_str).collect();
3330        let ranges = test_mod_ranges(&lines);
3331        let defines = lines.iter().enumerate().any(|(i, line)| {
3332            if in_test_range(i, &ranges) || is_line_comment(line) {
3333                return false;
3334            }
3335            // A stanza is a `Deserialize` struct: the derive is on one of the attribute lines
3336            // just above it.
3337            let derived = || {
3338                lines[..i]
3339                    .iter()
3340                    .rev()
3341                    .take_while(|l| {
3342                        let l = l.trim_start();
3343                        l.starts_with("#[") || l.starts_with("//")
3344                    })
3345                    .any(|l| l.contains("Deserialize"))
3346            };
3347            construction.is_match(line) || (stanza.is_match(line) && derived())
3348        });
3349        if defines {
3350            homes.push(rel);
3351        }
3352    }
3353    homes.sort();
3354    homes
3355}
3356
3357// --- Gated probe: wrangler_key_literals (1C.2) -----------------------------------------------
3358
3359/// Back-half paydown 1C.2 (#4039, Decision F): the places a top-level `wrangler.toml` key is
3360/// spelled as a string literal outside the vocabulary, `bynk-project/src/wrangler_keys.rs`
3361/// (`WranglerKey`). Production code in `bynk-emit`, `bynk-driver` and `bynk` names a key through
3362/// `WranglerKey`, so the key has one spelling and its environment rule is one `match`: a table the
3363/// emitter writes cannot be left out of the `[env.<name>]` block by omission (#3577, #3586).
3364///
3365/// Counts a literal equal to a [`WranglerKey::ALL`] header or top key (`name` excluded, as too
3366/// generic) in a TOML position: a `TomlBlock` header, a `.get(`, `.get_mut(`, `.entry(`,
3367/// `.remove(` or `.insert(` argument, an index, or a `for .. in [..]` list. A literal in a
3368/// different position (a wrangler subcommand, a runtime module name) is not a key. The pattern
3369/// is the vocabulary, so a key added to it is measured at once.
3370///
3371/// It read 91 on `main` before 1C.2 by this pattern (the proposal's 97 counted by hand) and reads 0 after it. A growth probe ([`GROWTH_PROBES`]):
3372/// it may only fall unless a pending file `raises:` it with a reason, so a new table written as a
3373/// raw literal in a patcher fails the gate.
3374///
3375/// Counts matches in the non-comment production text (outside `#[cfg(test)]` modules, deploy's
3376/// `pub(crate) mod tests` included, and wholly-test files, [`is_test_only_file`]). Text-level
3377/// gaps, as for the other scanners.
3378fn wrangler_key_literals(root: &Path) -> Probe {
3379    let mut files = Vec::new();
3380    for krate in ["bynk-emit", "bynk-driver", "bynk"] {
3381        for (path, contents) in rust_files_relative(&root.join(krate).join("src")) {
3382            files.push((Path::new(krate).join("src").join(path), contents));
3383        }
3384    }
3385    Probe {
3386        name: "wrangler_key_literals",
3387        gated: true,
3388        reads: wrangler_key_literals_count(&files).to_string(),
3389    }
3390}
3391
3392/// [`wrangler_key_literals`]' counting logic over an explicit file list, paths from the repo root.
3393fn wrangler_key_literals_count(files: &[(PathBuf, String)]) -> usize {
3394    use bynk_project::wrangler_keys::WranglerKey;
3395    let mut keys: Vec<&str> = WranglerKey::ALL
3396        .iter()
3397        .flat_map(|k| [k.header(), k.top_key()])
3398        .filter(|k| *k != "name")
3399        .collect();
3400    keys.sort_unstable();
3401    keys.dedup();
3402    let key = keys
3403        .iter()
3404        .map(|k| regex::escape(k))
3405        .collect::<Vec<_>>()
3406        .join("|");
3407    let positions = regex::Regex::new(&format!(
3408        r#"TomlBlock::(?:table|array_table|keyed_table)\(\s*"(?:{key})"|\.(?:get|get_mut|entry|remove|insert)\(\s*"(?:{key})"|\[\s*"(?:{key})"\s*\]|\bin\s*\[[^\]]*"(?:{key})""#
3409    ))
3410    .expect("the key pattern compiles");
3411    let gated = gated_stems(files);
3412    let mut count = 0;
3413    for (path, contents) in files {
3414        let rel = path.to_string_lossy().replace('\\', "/");
3415        if is_test_only_file(&rel, &gated) {
3416            continue;
3417        }
3418        // As in [`binding_kind_homes_files`]: a `pub(crate) mod tests` is a test module.
3419        let owned: Vec<String> = contents
3420            .lines()
3421            .map(|line| match line.strip_prefix("pub(crate) mod ") {
3422                Some(rest) => format!("mod {rest}"),
3423                None => line.to_string(),
3424            })
3425            .collect();
3426        let lines: Vec<&str> = owned.iter().map(String::as_str).collect();
3427        let ranges = test_mod_ranges(&lines);
3428        let production: Vec<&str> = lines
3429            .iter()
3430            .enumerate()
3431            .filter(|(i, line)| !in_test_range(*i, &ranges) && !is_line_comment(line))
3432            .map(|(_, line)| *line)
3433            .collect();
3434        count += positions.find_iter(&production.join("\n")).count();
3435    }
3436    count
3437}
3438
3439// --- Gated probe: tool_spawn_sites (1D.5b) ---------------------------------------------------
3440
3441/// Back-half paydown 1D.5b (#4003, Decision H): production process spawns in `bynk` and
3442/// `bynk-driver` that do not go through `bynk-driver/src/tools/` (npm, pnpm, bun, yarn, `tsc`,
3443/// `tsx`, `node`, `git`) or the detection layer, `bynk-driver/src/probe.rs`.
3444///
3445/// It read 20 on `main` before 1D.5b, 12 after it, and 10 after 1D.3a moved the wrangler spawn
3446/// into `bynk-driver/src/tools/wrangler.rs` (#4043). The residual is listed by reason in the
3447/// reading ([`spawn_reason`]): process control (`kill`, `ps`, `lsof`, `taskkill` and the Windows
3448/// junction's `cmd`) and self re-execution (`dev_run.rs`). Any other spawn reads as `other`. A growth probe ([`GROWTH_PROBES`]): it may only fall unless a pending
3449/// file `raises:` it with a reason, so a new tool spawn goes through `tools`.
3450///
3451/// Counts non-comment lines matching `Command::new(` or `ProcCommand::new(` (a word boundary
3452/// before) outside `#[cfg(test)]` modules (deploy's `pub(crate) mod tests` included),
3453/// wholly-test files ([`is_test_only_file`]) and the test-only `test_support.rs`. Text-level gaps, as for the other line scanners:
3454/// two spawns on one line count once, and a `Command` imported under another name is missed.
3455fn tool_spawn_sites(root: &Path) -> Probe {
3456    let mut files = Vec::new();
3457    for krate in ["bynk", "bynk-driver"] {
3458        for (path, contents) in rust_files_relative(&root.join(krate).join("src")) {
3459            files.push((Path::new(krate).join("src").join(path), contents));
3460        }
3461    }
3462    Probe {
3463        name: "tool_spawn_sites",
3464        gated: true,
3465        reads: tool_spawn_sites_reading(&files),
3466    }
3467}
3468
3469/// What a spawn outside `tools` is for, from its file and line.
3470fn spawn_reason(rel: &str, line: &str) -> &'static str {
3471    const PROCESS_CONTROL: [&str; 5] =
3472        ["\"kill\"", "\"ps\"", "\"lsof\"", "\"taskkill\"", "\"cmd\""];
3473    if PROCESS_CONTROL
3474        .iter()
3475        .any(|p| line.contains(&format!("::new({p}")))
3476    {
3477        "process control"
3478    } else if rel == "bynk-driver/src/dev_run.rs" {
3479        "self re-execution"
3480    } else {
3481        "other"
3482    }
3483}
3484
3485/// [`tool_spawn_sites`]'s reading over an explicit file list, paths from the repo root:
3486/// the count, then the count per [`spawn_reason`].
3487fn tool_spawn_sites_reading(files: &[(PathBuf, String)]) -> String {
3488    let spawn =
3489        regex::Regex::new(r"\b(Command|ProcCommand)::new\(").expect("the spawn pattern compiles");
3490    let mut by_reason: std::collections::BTreeMap<&'static str, usize> =
3491        ["process control", "self re-execution", "other"]
3492            .into_iter()
3493            .map(|r| (r, 0))
3494            .collect();
3495    let gated = gated_stems(files);
3496    let mut total = 0usize;
3497    for (path, contents) in files {
3498        let rel = path.to_string_lossy().replace('\\', "/");
3499        // `bynk/src/test_support.rs` is declared `#[cfg(test)] mod test_support;`.
3500        if is_test_only_file(&rel, &gated)
3501            || rel.ends_with("/test_support.rs")
3502            || rel.starts_with("bynk-driver/src/tools/")
3503            || rel == "bynk-driver/src/probe.rs"
3504        {
3505            continue;
3506        }
3507        // As in [`deploy_kind_accessors_violations`]: a `pub(crate) mod tests` is a test module.
3508        let lines: Vec<&str> = contents
3509            .lines()
3510            .map(|line| {
3511                line.strip_prefix("pub(crate) mod ")
3512                    .map_or(line, |_| &line[11..])
3513            })
3514            .collect();
3515        let ranges = test_mod_ranges(&lines);
3516        for (i, line) in lines.iter().enumerate() {
3517            if in_test_range(i, &ranges) || is_line_comment(line) || !spawn.is_match(line) {
3518                continue;
3519            }
3520            total += 1;
3521            *by_reason.entry(spawn_reason(&rel, line)).or_default() += 1;
3522        }
3523    }
3524    format!(
3525        "{total} (process control {}, self re-execution {}, other {})",
3526        by_reason["process control"], by_reason["self re-execution"], by_reason["other"]
3527    )
3528}
3529
3530/// Named identifiers imported from the compiler-generated firstparty/runtime relative
3531/// modules (`./bynk.js`, `./runtime.js`, `./bynk/locale/types.js`, `./cloudflare.js`,
3532/// or their `../` forms) — `import type { A, B }`/`import { A, B }` braces, stripping
3533/// `type ` markers and `X as Y` aliases (keeping the imported name, not the local one,
3534/// since the allowlists are about what's referenced, not what it's called locally).
3535fn ts_named_imports_from_runtime_modules(src: &str) -> Vec<String> {
3536    let mut out = Vec::new();
3537    for line in src.lines() {
3538        let line = line.trim();
3539        if !line.starts_with("import") {
3540            continue;
3541        }
3542        let is_runtime_module = ["\"./bynk.js\"", "\"./runtime.js\"", "\"../runtime.js\""]
3543            .iter()
3544            .any(|m| line.ends_with(&format!("from {m};")))
3545            || line.contains("__bynk_runtime/")
3546            || line.contains("bynk/locale/types.js")
3547            || line.contains("cloudflare.js");
3548        if !is_runtime_module {
3549            continue;
3550        }
3551        let Some(open) = line.find('{') else { continue };
3552        let Some(close) = line.find('}') else {
3553            continue;
3554        };
3555        for part in line[open + 1..close].split(',') {
3556            let part = part.trim().trim_start_matches("type ").trim();
3557            if part.is_empty() {
3558                continue;
3559            }
3560            let imported = part.split(" as ").next().unwrap_or(part).trim();
3561            out.push(imported.to_string());
3562        }
3563    }
3564    out
3565}
3566
3567// --- Gated probe 14: incremental_query_types --------------------------------
3568
3569/// Phase 8's own completion criterion (`design/bynk-compiler-trajectory.md` §3,
3570/// "keystroke-to-diagnostic latency by query level"), settled by #1509 (Q5, ADR 0414;
3571/// `design/tracks/incrementality.md` §5) as a one-time **existence** proof, not a count
3572/// trending toward a floor the way every other gated probe in this module is shaped —
3573/// R3.13/R3.14 describe a property to construct, not a defect to exhaust, so a
3574/// shrinking count would be the wrong shape regardless of how it was tuned.
3575///
3576/// **Re-settled by #1537 (2 September 2026), after the 30 August post-restructuring
3577/// review found the probe could not tell adoption from existence.** Phase 8 built all
3578/// four R3.13 levels; only the file level (P8.4's shared parse cache) and the unit
3579/// level's *proof* (P8.2's stability test over `UnitSignature`) had a consumer. The
3580/// definition level (`Body(DefId)`/`TypeOf(DefId)`, 816 lines) and the project level
3581/// (`ProjectGraph`, 174 lines) were reachable only from their own tests, with no
3582/// scheduler to call them and — per R3.15 and #1523 — no trigger yet for one. Both
3583/// were deleted rather than left "available but unwired" (P5), the same decision the
3584/// IR cutover (#1542) reached for phase 6's expression IR. This probe now certifies
3585/// the decision, in both directions:
3586///
3587/// 1. **Unit level** — `struct UnitSignature` exists as real code in `bynk-check`
3588///    (P8.1, ADR 0412). It is the R3.14 firewall's own specification, and the one
3589///    phase 8 artefact #1523's trigger presupposes; it stays as a *proof*, not a
3590///    production path (its only reader is clause 3's test), argued in #1537's ADR.
3591/// 2. **Shared cache** — the file-level parse cache has migrated off
3592///    `PROJECT_UNIT_CACHE` (`bynk-ide/src/completion.rs`) onto one shared,
3593///    `bynk-project`-owned cache (P8.4, ADR 0413). Checked two ways: the old static
3594///    gone from `bynk-ide/src`, *and* some cache-shaped `static`/`struct` present in
3595///    `bynk-project/src` — absence alone would read "migrated" for a bare deletion.
3596/// 3. **Stability test** — some `#[test]` under `bynk-check/tests/` proves
3597///    `UnitSignature`'s stability under a body edit (P8.2): any test name containing
3598///    both `unit_signature` and `stab`.
3599/// 4. **Definition and project levels absent** — no `struct ProjectGraph`, and no
3600///    `DefId`-keyed `fn body(`/`fn type_of(`, in **any** workspace crate's `src/`
3601///    ([`workspace_crate_src_files`], the same walk `unconsumed_ir_items` uses, minus
3602///    `xtask` itself, whose source spells the needles) — not just the two crates
3603///    phase 8 landed them in, since R3.13's own table
3604///    assigns `DefId` bindings to a `bynk-resolve` crate that does not exist yet and
3605///    a rebuild might put them there (review of #1582). `checker.rs`'s own
3606///    pre-existing per-expression `type_of`, which has no `DefId` parameter, does
3607///    not count — the false positive #1510's first run caught, now with the opposite
3608///    consequence. This clause is what makes the probe a gate on #1537 rather than a
3609///    memorial: re-adding either level changes the committed reading and fails the
3610///    currency test, so it needs a consumer and a re-settling — the trigger
3611///    R3.15/#1523 names. **What the gate does not see, stated rather than asserted
3612///    away:** a `DefId` parameter wrapped onto the line after `fn body(` (the
3613///    same-line rule [`defid_query_fn_present`] documents), or a query function under
3614///    any other name. Text-level, like every probe in this file.
3615///
3616/// Every clause is a static read of the tree (never a nested build or test run — see
3617/// [`unit_signature_present`]'s own doc comment for why a "does the stability test
3618/// *pass*" clause was deliberately rejected, #1510's own review-shaped framing).
3619fn incremental_query_types(root: &Path) -> Probe {
3620    let check_src = rust_files(&root.join("bynk-check/src"));
3621    let project_src = rust_files(&root.join("bynk-project/src"));
3622    let ide_src = rust_files(&root.join("bynk-ide/src"));
3623    let check_tests = rust_files(&root.join("bynk-check/tests"));
3624
3625    let unit_present = unit_signature_present(&check_src);
3626    let cache_migrated = shared_cache_migrated(&ide_src, &project_src);
3627    let test_present = stability_test_present(&check_tests);
3628    // Every workspace crate but this one: the harness's own source spells the
3629    // needles it scans for (in these very functions and their tests), so it
3630    // would read as a re-add of both levels on every run.
3631    let workspace_src: Vec<(PathBuf, String)> = workspace_crate_src_files(root)
3632        .into_iter()
3633        .filter(|(krate, _, _)| krate != "xtask")
3634        .map(|(_, path, contents)| (path, contents))
3635        .collect();
3636    let readded = deleted_levels_present(&workspace_src);
3637
3638    let reads = format!(
3639        "unit_signature {}; shared_cache {}; stability_test {}; definition/project levels {}",
3640        if unit_present { "present" } else { "absent" },
3641        if cache_migrated {
3642            "migrated"
3643        } else {
3644            "not migrated (PROJECT_UNIT_CACHE still bynk-ide-local)"
3645        },
3646        if test_present { "present" } else { "absent" },
3647        if readded.is_empty() {
3648            "absent (deleted by #1537)".to_string()
3649        } else {
3650            format!(
3651                "re-added ({}) — need a consumer and a re-settling of #1537",
3652                readded.join(", ")
3653            )
3654        },
3655    );
3656    Probe {
3657        name: "incremental_query_types",
3658        gated: true,
3659        reads,
3660    }
3661}
3662
3663/// Clause 1 of [`incremental_query_types`]: does `struct UnitSignature` exist as real
3664/// code (not a comment or doc prose) in `bynk-check`? The same "grep for the real
3665/// identifier, not the doc claim" discipline `design/tracks/incrementality.md` §1 used
3666/// to measure this reading as zero at settling. Deliberately *not* a "does P8.2's
3667/// fixture pass" check: every gated probe here is a static read of the tree, computed
3668/// from inside `xtask/tests/greenfield_status.rs`'s own `#[test]`; shelling out to
3669/// `cargo test` from inside a running `cargo test` is the identical nested-invocation
3670/// cost [`wildcard_arms`] (the one probe that shells out, and stays trend-only for
3671/// exactly this reason) avoids.
3672fn unit_signature_present(check_src: &[(PathBuf, String)]) -> bool {
3673    any_real_code_line(check_src, "struct UnitSignature")
3674}
3675
3676/// Clause 4 of [`incremental_query_types`]: which of the two levels #1537 deleted are
3677/// back anywhere in `src` — `ProjectGraph` as a real struct, or a `DefId`-keyed
3678/// `body`/`type_of` query function ([`defid_query_fn_present`]). Empty is the
3679/// committed reading; any entry changes the table and fails the currency gate, which
3680/// is the point.
3681fn deleted_levels_present(src: &[(PathBuf, String)]) -> Vec<&'static str> {
3682    let mut found = Vec::new();
3683    if any_real_code_line(src, "struct ProjectGraph") {
3684        found.push("ProjectGraph");
3685    }
3686    if defid_query_fn_present(src, "fn body(") {
3687        found.push("Body");
3688    }
3689    if defid_query_fn_present(src, "fn type_of(") {
3690        found.push("TypeOf");
3691    }
3692    found
3693}
3694
3695/// A `fn_needle`-matching signature line that *also* names `DefId` on the same line —
3696/// not just `fn_needle` alone. **A real, empirically-confirmed false positive this
3697/// slice's own first run caught, not a hypothetical:** `bynk-check/src/checker.rs`
3698/// already has a `pub(crate) fn type_of(expr: &Expr, expected: Option<TyId>, ctx: &mut
3699/// Ctx) -> Option<TyId>` — real, pre-existing, ordinary per-expression type-inference
3700/// plumbing that predates this whole track and has nothing to do with R3.13's
3701/// `DefId`-keyed query — a naive `fn type_of(` scan reads this as `TypeOf` already
3702/// existing on the very first run, before P8.5 does any work at all. Requiring
3703/// `DefId` on the same signature line is a real, if narrow, precision fix: it correctly
3704/// reads false against `checker.rs`'s own `type_of` today, and correctly flips true
3705/// once P8.5 lands a real `DefId`-keyed function, whatever it ends up calling it, as
3706/// long as the parameter appears on the `fn` line itself (a wrapped multi-line
3707/// signature would need widening this scan window — not needed for any function in
3708/// the tree today).
3709fn defid_query_fn_present(files: &[(PathBuf, String)], fn_needle: &str) -> bool {
3710    files.iter().any(|(_, contents)| {
3711        contents.lines().any(|line| {
3712            !is_line_comment(line) && line.contains(fn_needle) && line.contains("DefId")
3713        })
3714    })
3715}
3716
3717/// Whether the file-level parse cache has migrated off `bynk-ide`'s own
3718/// `PROJECT_UNIT_CACHE` onto some shared cache in `bynk-project` — see
3719/// [`incremental_query_types`]'s own doc comment (clause 2) for why *both* halves are
3720/// checked: absence from `bynk-ide` alone cannot distinguish a real migration from a
3721/// bare rename or deletion with nothing shared put in its place. The needle is
3722/// anchored on the `static` declaration line (`static PROJECT_UNIT_CACHE`), not a bare
3723/// substring, so `PROJECT_UNIT_CACHE_CAP` (a real, unrelated `const` in
3724/// `bynk-ide/src/completion.rs`) can't hold this false on its own.
3725fn shared_cache_migrated(ide_src: &[(PathBuf, String)], project_src: &[(PathBuf, String)]) -> bool {
3726    !any_real_code_line(ide_src, "static PROJECT_UNIT_CACHE")
3727        && cache_shaped_item_present(project_src)
3728}
3729
3730/// Whether `bynk-project/src` has a `static`/`struct` item whose name mentions "cache"
3731/// (case-insensitive) — the only crate-boundary-checkable proxy for "some shared cache
3732/// now lives where P8.4 is meant to put it," until that slice pins the real identifier
3733/// down. Deliberately loose, the same "exact name not yet proposed" reasoning
3734/// [`stability_test_present`] already uses.
3735fn cache_shaped_item_present(project_src: &[(PathBuf, String)]) -> bool {
3736    project_src.iter().any(|(_, contents)| {
3737        contents.lines().any(|line| {
3738            if is_line_comment(line) {
3739                return false;
3740            }
3741            let trimmed = line.trim_start();
3742            let is_item = trimmed.starts_with("static ")
3743                || trimmed.starts_with("pub static ")
3744                || trimmed.starts_with("struct ")
3745                || trimmed.starts_with("pub struct ");
3746            is_item && line.to_lowercase().contains("cache")
3747        })
3748    })
3749}
3750
3751/// Whether any `#[test]` fn under `bynk-check/tests/` looks like P8.2's own
3752/// body-edit-stability property test — see [`incremental_query_types`]'s own doc
3753/// comment (clause 3) for why the name match (`unit_signature` + `stab`) is
3754/// deliberately loose. The `#[test]` attribute itself is *not* loose: it must be on the
3755/// matching `fn` line or on a contiguous run of attribute lines directly above it, so a
3756/// same-named non-test helper (a fixture builder, say) can't satisfy this clause.
3757fn stability_test_present(check_tests: &[(PathBuf, String)]) -> bool {
3758    check_tests.iter().any(|(_, contents)| {
3759        let lines: Vec<&str> = contents.lines().collect();
3760        lines.iter().enumerate().any(|(i, line)| {
3761            if is_line_comment(line) {
3762                return false;
3763            }
3764            let lower = line.to_lowercase();
3765            let name_matches =
3766                lower.contains("fn ") && lower.contains("unit_signature") && lower.contains("stab");
3767            if !name_matches {
3768                return false;
3769            }
3770            line.contains("#[test]")
3771                || lines[..i]
3772                    .iter()
3773                    .rev()
3774                    .take_while(|l| l.trim_start().starts_with('#'))
3775                    .any(|l| l.trim() == "#[test]")
3776        })
3777    })
3778}
3779
3780/// Whether any line in `files` (excluding comments) contains `needle` — the shared
3781/// existence-check primitive [`unit_signature_present`]/[`deleted_levels_present`]/
3782/// [`shared_cache_migrated`] all use.
3783fn any_real_code_line(files: &[(PathBuf, String)], needle: &str) -> bool {
3784    files.iter().any(|(_, contents)| {
3785        contents
3786            .lines()
3787            .any(|line| !is_line_comment(line) && line.contains(needle))
3788    })
3789}
3790
3791// --- Gated probe 15: unconsumed_ir_items ------------------------------------
3792
3793/// Slice D3 of #1542 (`design/archive/retired-tracks.md`, the IR cutover's own
3794/// closing summary): the adoption probe the 30 August 2026 post-restructuring
3795/// review (`design/reviews/2026-08-30-post-restructuring-review.md`, Part 5 §8)
3796/// asked for — for each `pub` item in `bynk-ir/src` and `bynk-lower/src`, does
3797/// a production call site exist outside the owning crate and outside a test
3798/// module? That review found phase 6 had shipped an expression IR nothing
3799/// consumed (fifteen `bynk-lower` entry points, twenty-one `bynk-ir` types),
3800/// invisible to every existing gate because each of them certifies that a name
3801/// *exists* in a directory, not that anything *reads* it. Scoped to the two IR
3802/// crates because their entire purpose is to be consumed elsewhere: a `pub`
3803/// item in either with no reader in another crate is, by construction, either
3804/// dead or a second path waiting to be wired in — the P5 failure
3805/// (`bynk-greenfield-compiler.md`) both phases 6 and 8 reproduced.
3806///
3807/// Reads **0** at its own landing, by construction: Slices D0–D2 deleted every
3808/// unconsumed item (D1 also demoted the two crate-internal helpers,
3809/// `lower_fn_sig_ir_from_types`/`lower_op_sig_ir_from_commons`, that would
3810/// otherwise have read as 2). Gated as a ratchet: a new `pub` item in either
3811/// crate with no consumer moves it off zero and fails
3812/// `greenfield_status_table_is_current`, so the "available but unwired" state
3813/// cannot land silently again. The reading names the offending items so the
3814/// failure is actionable, not just a count.
3815///
3816/// **What counts as a consumer.** A non-comment line, outside any `#[cfg(test)]
3817/// mod` range ([`test_mod_ranges`]), in a workspace crate's `src/` that is
3818/// **not the owner**, containing the item's name as a whole word.
3819///
3820/// **Re-pointed by crate-hygiene B1 (#2939).** `bynk-ir` and `bynk-lower` merged
3821/// into one crate, `bynk-model` (the system-model ADR, track §6 Q2), so the
3822/// owner is now that one crate and the scan covers both of its modules. The rule
3823/// is exactly as strict as before: the builder (`bynk_model::lower`) still can't
3824/// vouch for the vocabulary, because both sit inside the excluded crate. The
3825/// reading didn't move (0). Before the merge, the rule was the two-owner one
3826/// below. The
3827/// two owners do not vouch for each other, on purpose (review of this slice's
3828/// own PR, #1581): run against pre-D0 `main` with only the owning crate
3829/// excluded, every one of phase 6's twenty-one unconsumed `bynk-ir` types
3830/// would have read as consumed, because `bynk-lower`'s own unconsumed
3831/// constructors named them — the probe would have missed half the surface it
3832/// was built to see. With both excluded, its first honest run read 5
3833/// (`IndexIr` and the four `MUTATING_*_OPS` tables, read only from
3834/// `bynk-lower`), resolved by inlining the alias and moving the tables beside
3835/// their one reader rather than arguing a floor. Text-level, like every probe
3836/// in this file — a name that happens to be shared with an unrelated item in
3837/// another crate would read as consumed (a false negative for the ratchet,
3838/// never a false positive that blocks a PR), accepted the same way
3839/// [`ts_writes`]'s own known over-count is. Items are `pub` at column zero
3840/// only — `fn`, `struct`, `enum`, `type`, `const`, `static`, `trait`, `union`,
3841/// with any `async`/`unsafe`/`const`/`extern` qualifier on a `fn` — see
3842/// [`column_zero_pub_item_name`]: `pub(crate)` is by definition not offered
3843/// to another crate, a `pub` item nested inside an `impl` block is reachable
3844/// only through its owner (which is what gets counted), and `pub use`/`pub
3845/// mod` re-export rather than declare.
3846fn unconsumed_ir_items(root: &Path) -> Probe {
3847    let owners = ["bynk-model"];
3848    let mut owner_files = Vec::new();
3849    for owner in owners {
3850        for (path, contents) in rust_files_relative(&root.join(owner).join("src")) {
3851            owner_files.push((owner.to_string(), path, contents));
3852        }
3853    }
3854    let consumer_files = workspace_crate_src_files(root);
3855    let unconsumed = unconsumed_pub_items(&owners, &owner_files, &consumer_files);
3856    let reads = if unconsumed.is_empty() {
3857        "0".to_string()
3858    } else {
3859        format!("{} ({})", unconsumed.len(), unconsumed.join(", "))
3860    };
3861    Probe {
3862        name: "unconsumed_ir_items",
3863        gated: true,
3864        reads,
3865    }
3866}
3867
3868// --- Gated probe 17: model_readers_beyond_emit -------------------------------
3869
3870/// Crate-hygiene track §6.2 M-3, added by slice B1 (#2939), with the
3871/// system-model ADR. It counts the system model's items (the column-zero `pub`
3872/// items of `bynk-model`, the same set [`unconsumed_ir_items`] scans) that have
3873/// a production reader in a workspace crate other than `bynk-model` **and
3874/// `bynk-emit`**. Re-pointed by B1's rename from the two crates `bynk-ir` and
3875/// `bynk-lower` to `bynk-model`: the count didn't move, but each item's owner
3876/// prefix in the reading changed.
3877///
3878/// [`unconsumed_ir_items`] asks whether every item has *a* reader. This asks how
3879/// far the model reaches past the emitter, which was its only consumer until
3880/// B1. The reading names the items, so a move is reviewable.
3881///
3882/// **Its count can only rise.** The row is gated exact-match like every gated
3883/// row, so each move is named in a pending file's `probes:`. On top of that,
3884/// `xtask/tests/greenfield_status.rs`'s `model_readers_beyond_emit_never_falls`
3885/// fails whenever a fresh count is below the committed one, whatever `probes:`
3886/// says. A fall means some consumer went back to re-deriving a fact the model
3887/// carries, which M-1 calls a defect. The mechanical floor is on the count, not
3888/// the set: dropping one item while adding another keeps the count, and only
3889/// the exact-match row (and so its `probes:` acknowledgement) surfaces the swap
3890/// for review.
3891///
3892/// Same text-level limits as [`unconsumed_ir_items`]: a name shared with an
3893/// unrelated item in another crate over-counts, which errs toward a higher
3894/// reading and never blocks a PR.
3895fn model_readers_beyond_emit(root: &Path) -> Probe {
3896    let owners = ["bynk-model"];
3897    let mut owner_files = Vec::new();
3898    for owner in owners {
3899        for (path, contents) in rust_files_relative(&root.join(owner).join("src")) {
3900            owner_files.push((owner.to_string(), path, contents));
3901        }
3902    }
3903    // `bynk-driver`'s `project` module is the old `bynk-emit::project` (crate-hygiene D1,
3904    // #2982): the emitter's own orchestration, so it is not a reader "past the emitter".
3905    let consumer_files: Vec<_> = workspace_crate_src_files(root)
3906        .into_iter()
3907        .filter(|(krate, path, _)| {
3908            !(krate == "bynk-driver"
3909                && (path == Path::new("project.rs") || path.starts_with("project")))
3910        })
3911        .collect();
3912    let excluded = ["bynk-model", "bynk-emit"];
3913    let (read, _) = pub_items_by_readership(&owners, &excluded, &owner_files, &consumer_files);
3914    Probe {
3915        name: "model_readers_beyond_emit",
3916        gated: true,
3917        reads: model_readers_reading(&read),
3918    }
3919}
3920
3921/// `N (a, b, …)`, or `0`. [`model_readers_count`] parses it back.
3922fn model_readers_reading(read: &[String]) -> String {
3923    if read.is_empty() {
3924        "0".to_string()
3925    } else {
3926        format!("{} ({})", read.len(), read.join(", "))
3927    }
3928}
3929
3930/// The leading count of a `model_readers_beyond_emit` reading, which is what
3931/// the floor test compares. `None` if the reading doesn't start with a count.
3932pub fn model_readers_count(reads: &str) -> Option<usize> {
3933    leading_count(reads)
3934}
3935
3936/// The leading integer of a reading such as `104 (bynk-browser.ts:Claim, …)`:
3937/// the first whitespace-separated token, parsed. `None` if it is not an integer.
3938/// The shared parser behind [`model_readers_count`] and [`growth_rises`].
3939pub fn leading_count(reads: &str) -> Option<usize> {
3940    reads.split_whitespace().next()?.parse().ok()
3941}
3942
3943/// The committed reading of gated probe `name` in the table text `committed`.
3944pub fn committed_reading<'a>(committed: &'a str, name: &str) -> Option<&'a str> {
3945    let prefix = format!("| `{name}` | yes | ");
3946    committed
3947        .lines()
3948        .find_map(|l| l.strip_prefix(&prefix))?
3949        .strip_suffix(" |")
3950}
3951
3952/// A growth probe whose live count exceeds the committed one.
3953#[derive(Debug, Clone, PartialEq, Eq)]
3954pub struct GrowthRise {
3955    pub probe: &'static str,
3956    pub from: usize,
3957    pub to: usize,
3958}
3959
3960/// Every [`GROWTH_PROBES`] member whose live leading count in `probes` is higher
3961/// than its committed row's in `committed` (the table text). `Err` lists every
3962/// growth probe whose live or committed reading is missing or has no leading
3963/// integer: that is a hard failure, never a skip (a probe that stopped reporting
3964/// a count must not quietly leave the ratchet). A growth probe with *no row at
3965/// all* in `committed` is newly introduced and is skipped (#3681): it is checked
3966/// from the first time its row exists.
3967pub fn growth_rises(probes: &[Probe], committed: &str) -> Result<Vec<GrowthRise>, Vec<String>> {
3968    let mut rises = Vec::new();
3969    let mut errors = Vec::new();
3970    for name in GROWTH_PROBES {
3971        let Some(live) = probes.iter().find(|p| p.name == name) else {
3972            errors.push(format!("growth probe {name} did not run"));
3973            continue;
3974        };
3975        let Some(now) = leading_count(&live.reads) else {
3976            errors.push(format!(
3977                "growth probe {name}: live reading {:?} has no leading count",
3978                live.reads
3979            ));
3980            continue;
3981        };
3982        // No row at all: the probe is newly introduced by this change, so there is
3983        // nothing to rise from (the exact-match gate and the stamp seed the row).
3984        // A row that exists but has no leading count stays a hard failure.
3985        let Some(row) = committed_reading(committed, name) else {
3986            continue;
3987        };
3988        let Some(floor) = leading_count(row) else {
3989            errors.push(format!(
3990                "growth probe {name}: the committed row {row:?} has no leading count"
3991            ));
3992            continue;
3993        };
3994        if now > floor {
3995            rises.push(GrowthRise {
3996                probe: name,
3997                from: floor,
3998                to: now,
3999            });
4000        }
4001    }
4002    if errors.is_empty() {
4003        Ok(rises)
4004    } else {
4005        Err(errors)
4006    }
4007}
4008
4009/// The one growth-direction check, shared by `growth_probes_never_rise` (base =
4010/// the working-tree table) and `cargo xtask greenfield-status --check-growth`
4011/// (base = the table at the PR's base revision, so a hand-edited row cannot
4012/// launder a rise). Compares `live`'s growth probes with `base_table`'s rows and
4013/// requires a pending file under `root` to `raises:` each rise.
4014pub fn check_growth(live: &[Probe], base_table: &str, root: &Path) -> Result<(), String> {
4015    let rises = growth_rises(live, base_table)
4016        .map_err(|errs| format!("growth probe reading unusable:\n{}", errs.join("\n")))?;
4017    if rises.is_empty() {
4018        return Ok(());
4019    }
4020    let raised = crate::raised_probes_checked(root).map_err(|errs| {
4021        format!(
4022            "growth probe(s) rose, and the pending files are invalid, so no `raises:` could be \
4023             read. Fix them first (run `cargo xtask check-pending`):\n{}",
4024            errs.join("\n")
4025        )
4026    })?;
4027    let left = unraised(rises, &raised);
4028    if left.is_empty() {
4029        return Ok(());
4030    }
4031    Err(format!(
4032        "growth probe(s) rose without a reasoned raise. A growth probe may only fall in an \
4033         ordinary PR; if this rise is deliberate, add a line to your increment's \
4034         `design/pending/<slug>.md` frontmatter, `raises: <probe> — <reason>` (one line per \
4035         probe; see design/pending/README.md). The stamp records it in \
4036         design/greenfield-status-raises.md. Otherwise, reduce the count:\n{}",
4037        left.iter()
4038            .map(|r| format!("  {}: committed {}, live {}", r.probe, r.from, r.to))
4039            .collect::<Vec<_>>()
4040            .join("\n")
4041    ))
4042}
4043
4044/// The `rises` no pending file `raised` — the ones that must fail the gate.
4045pub fn unraised(rises: Vec<GrowthRise>, raised: &BTreeSet<String>) -> Vec<GrowthRise> {
4046    rises
4047        .into_iter()
4048        .filter(|r| !raised.contains(r.probe))
4049        .collect()
4050}
4051
4052/// Every `.rs` file under `<crate>/src` for every workspace crate — each entry
4053/// tagged with its crate directory name so [`unconsumed_pub_items`] can exclude
4054/// an item's own crate. A workspace crate is any immediate child of `root` with
4055/// both a `Cargo.toml` and a `src/`, the same shape every `members` entry in the
4056/// root manifest has; reading the manifest itself would add a TOML parse for no
4057/// gain in precision.
4058fn workspace_crate_src_files(root: &Path) -> Vec<(String, PathBuf, String)> {
4059    let mut out = Vec::new();
4060    let Ok(entries) = std::fs::read_dir(root) else {
4061        return out;
4062    };
4063    let mut crates: Vec<PathBuf> = entries
4064        .flatten()
4065        .map(|e| e.path())
4066        .filter(|p| p.join("Cargo.toml").is_file() && p.join("src").is_dir())
4067        .collect();
4068    crates.sort();
4069    for krate in crates {
4070        let name = krate
4071            .file_name()
4072            .map(|n| n.to_string_lossy().into_owned())
4073            .unwrap_or_default();
4074        for (path, contents) in rust_files_relative(&krate.join("src")) {
4075            out.push((name.clone(), path, contents));
4076        }
4077    }
4078    out
4079}
4080
4081/// [`unconsumed_ir_items`]'s counting logic over explicit `(crate, relative
4082/// path, contents)` lists — see [`rust_files_relative`] for why this isn't
4083/// `root: &Path`. Returns `crate::item` for every column-zero `pub` item in
4084/// `owner_files` that no non-comment, non-test line in a file belonging to a
4085/// crate outside `owners` names as a whole word; sorted and deduplicated (a
4086/// name declared in two files of one crate is one item, not two), so the
4087/// reading is stable across runs and across a crate being split into modules.
4088///
4089/// Each consumer file is split and its `#[cfg(test)]` ranges computed once,
4090/// up front, not once per candidate item (review of #1581): this runs under
4091/// `cargo test --workspace` on every Rust-touching PR, and the failure path —
4092/// an item with no consumer — is exactly the one that scans every file.
4093fn unconsumed_pub_items(
4094    owners: &[&str],
4095    owner_files: &[(String, PathBuf, String)],
4096    consumer_files: &[(String, PathBuf, String)],
4097) -> Vec<String> {
4098    pub_items_by_readership(owners, owners, owner_files, consumer_files).1
4099}
4100
4101/// The shared scan behind [`unconsumed_pub_items`] and
4102/// [`model_readers_beyond_emit`]. It returns `(read, unread)`, each as sorted,
4103/// deduplicated `crate::item` names, over every column-zero `pub` item in
4104/// `owner_files`.
4105///
4106/// An item counts as read when a non-comment, non-test line names it as a whole
4107/// word in a file belonging to a crate **not** in `excluded`. `excluded` always
4108/// contains the owners, and may add more crates: the M-3 ratchet adds
4109/// `bynk-emit`.
4110fn pub_items_by_readership(
4111    owners: &[&str],
4112    excluded: &[&str],
4113    owner_files: &[(String, PathBuf, String)],
4114    consumer_files: &[(String, PathBuf, String)],
4115) -> (Vec<String>, Vec<String>) {
4116    debug_assert!(owners.iter().all(|o| excluded.contains(o)));
4117    let mut items: Vec<(String, String)> = Vec::new();
4118    for (krate, _, contents) in owner_files {
4119        let lines: Vec<&str> = contents.lines().collect();
4120        let ranges = test_mod_ranges(&lines);
4121        for (i, line) in lines.iter().enumerate() {
4122            if in_test_range(i, &ranges) {
4123                continue;
4124            }
4125            if let Some(name) = column_zero_pub_item_name(line) {
4126                items.push((krate.clone(), name.to_string()));
4127            }
4128        }
4129    }
4130    items.sort();
4131    items.dedup();
4132
4133    // Production lines outside every excluded crate only — preprocessed once.
4134    let consumer_lines: Vec<&str> = consumer_files
4135        .iter()
4136        .filter(|(krate, _, _)| !excluded.contains(&krate.as_str()))
4137        .flat_map(|(_, _, contents)| {
4138            let lines: Vec<&str> = contents.lines().collect();
4139            let ranges = test_mod_ranges(&lines);
4140            lines
4141                .iter()
4142                .enumerate()
4143                .filter(|(i, line)| !in_test_range(*i, &ranges) && !is_line_comment(line))
4144                .map(|(_, line)| *line)
4145                .collect::<Vec<_>>()
4146        })
4147        .collect();
4148
4149    let (read, unread): (Vec<_>, Vec<_>) = items
4150        .iter()
4151        .partition(|(_, name)| consumer_lines.iter().any(|line| contains_word(line, name)));
4152    let names = |v: Vec<&(String, String)>| -> Vec<String> {
4153        v.into_iter()
4154            .map(|(owner, name)| format!("{owner}::{name}"))
4155            .collect()
4156    };
4157    (names(read), names(unread))
4158}
4159
4160/// The name of a column-zero `pub` item declaration, if `line` is one: `pub`
4161/// followed by `fn`, `struct`, `enum`, `type`, `const`, `static`, `trait` or
4162/// `union`, where a `fn` may carry `async`/`unsafe`/`const`/`extern "…"`
4163/// qualifiers in any order. `pub(crate)`/`pub(super)` do not qualify (they
4164/// are not offered to other crates), and neither does anything indented (a
4165/// method or associated item, reachable only through its owner), nor `pub
4166/// use`/`pub mod` (re-exports and module declarations, not items).
4167fn column_zero_pub_item_name(line: &str) -> Option<&str> {
4168    let mut rest = line.strip_prefix("pub ")?;
4169    // `pub const fn` / `pub async unsafe fn` / `pub unsafe extern "C" fn` …:
4170    // peel qualifiers until the item keyword is exposed. A bare `pub const X`
4171    // is a constant, not a qualifier, so `const` only peels when a `fn`
4172    // (possibly behind further qualifiers) follows it.
4173    loop {
4174        if let Some(r) = rest
4175            .strip_prefix("async ")
4176            .or_else(|| rest.strip_prefix("unsafe "))
4177        {
4178            rest = r;
4179            continue;
4180        }
4181        if let Some(r) = rest.strip_prefix("extern ") {
4182            // `extern "C" fn` — skip the ABI string if present.
4183            let r = r.trim_start();
4184            let r = if let Some(after_quote) = r.strip_prefix('"') {
4185                after_quote
4186                    .find('"')
4187                    .map(|q| after_quote[q + 1..].trim_start())
4188                    .unwrap_or(r)
4189            } else {
4190                r
4191            };
4192            rest = r;
4193            continue;
4194        }
4195        if let Some(r) = rest.strip_prefix("const ")
4196            && (r.starts_with("fn ")
4197                || r.starts_with("async ")
4198                || r.starts_with("unsafe ")
4199                || r.starts_with("extern "))
4200        {
4201            rest = r;
4202            continue;
4203        }
4204        break;
4205    }
4206    let rest = [
4207        "fn ", "struct ", "enum ", "type ", "const ", "static ", "trait ", "union ",
4208    ]
4209    .iter()
4210    .find_map(|kw| rest.strip_prefix(kw))?;
4211    let end = rest
4212        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
4213        .unwrap_or(rest.len());
4214    (end > 0).then(|| &rest[..end])
4215}
4216
4217/// Does `line` contain `word` as a whole identifier — not as a prefix or
4218/// suffix of a longer one (`IrExpr` inside `IrExprKind` must not count)?
4219fn contains_word(line: &str, word: &str) -> bool {
4220    let bytes = line.as_bytes();
4221    let mut from = 0;
4222    while let Some(pos) = line[from..].find(word) {
4223        let start = from + pos;
4224        let end = start + word.len();
4225        let before_ok = start == 0 || !is_ident_byte(bytes[start - 1]);
4226        let after_ok = end == bytes.len() || !is_ident_byte(bytes[end]);
4227        if before_ok && after_ok {
4228            return true;
4229        }
4230        from = start + 1;
4231    }
4232    false
4233}
4234
4235fn is_ident_byte(b: u8) -> bool {
4236    b.is_ascii_alphanumeric() || b == b'_'
4237}
4238
4239// --- Reported probe 1: wildcard_arms --------------------------------------
4240
4241/// R2.12. `clippy::wildcard_enum_match_arm` diagnostics, forced on via `-W` so the
4242/// count is real from day one and doesn't wait on `workspace_lints`/T0.3 (#999 Decision
4243/// C — delegating to clippy's own type-aware pass, rather than a hand-rolled scan for
4244/// "compiler-owned enum", so the probe and the enforcement mechanism can never
4245/// disagree). A count, not a boolean — moves on nearly every match statement anyone
4246/// writes, so it is reported, not gated (#999 Decision D).
4247fn wildcard_arms(root: &Path) -> Probe {
4248    let reads = match run_clippy_wildcard_scan(root) {
4249        Ok(n) => n.to_string(),
4250        Err(e) => format!("error running clippy: {e}"),
4251    };
4252    Probe {
4253        name: "wildcard_arms",
4254        gated: false,
4255        reads,
4256    }
4257}
4258
4259/// Runs clippy with the lint forced on and parses the NDJSON output properly —
4260/// **not** a substring count. A single `wildcard_enum_match_arm` diagnostic's JSON
4261/// repeats the lint name several times (the `code` field, the human-readable message,
4262/// the `#[warn(...)]` note, and the `rendered` field duplicating the whole thing as
4263/// text), so `stdout.matches("wildcard_enum_match_arm").count()` overcounts by roughly
4264/// 3x — caught by cross-checking this probe's own first run against a real JSON parse
4265/// (296 real diagnostics, not the naive scan's 888).
4266///
4267/// Checks the process exit status: a forced `-W` (not `-D`) never fails the build on
4268/// account of the lint itself, so a non-zero exit means clippy genuinely could not run
4269/// (a compile error elsewhere, a missing toolchain component, offline with no cached
4270/// index) — in which case stdout carries no `compiler-message` lines and a silent
4271/// success would report a false, and indistinguishable, `0`. This probe is reported,
4272/// not gated, precisely so an honest "couldn't measure" surfaces loudly here rather
4273/// than being read as "closed."
4274fn run_clippy_wildcard_scan(root: &Path) -> std::io::Result<usize> {
4275    let output = Command::new("cargo")
4276        .args([
4277            "clippy",
4278            "--workspace",
4279            "--message-format=json",
4280            "--",
4281            "-W",
4282            "clippy::wildcard_enum_match_arm",
4283        ])
4284        .current_dir(root)
4285        .output()?;
4286    if !output.status.success() {
4287        return Err(std::io::Error::other(format!(
4288            "cargo clippy exited with {}: {}",
4289            output.status,
4290            String::from_utf8_lossy(&output.stderr).trim()
4291        )));
4292    }
4293    let stdout = String::from_utf8_lossy(&output.stdout);
4294    let mut count = 0usize;
4295    for line in stdout.lines() {
4296        let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
4297            continue;
4298        };
4299        if value.get("reason").and_then(|r| r.as_str()) != Some("compiler-message") {
4300            continue;
4301        }
4302        let code = value.pointer("/message/code/code").and_then(|c| c.as_str());
4303        if code == Some("clippy::wildcard_enum_match_arm") {
4304            count += 1;
4305        }
4306    }
4307    Ok(count)
4308}
4309
4310// --- Reported probe 2: keep_in_sync ---------------------------------------
4311
4312/// P2 (trend only). Comments across the workspace containing "in sync", "mirrors",
4313/// "parity", or "must match" — each one names a rule the compiler cannot teach itself
4314/// and must be taught in review, every time.
4315fn keep_in_sync(root: &Path) -> Probe {
4316    let phrases = ["in sync", "mirrors", "parity", "must match"];
4317    let mut count = 0usize;
4318    for dir in top_level_crate_dirs(root) {
4319        for (_, contents) in rust_files(&dir.join("src")) {
4320            for line in contents.lines() {
4321                if is_line_comment(line) {
4322                    let lower = line.to_lowercase();
4323                    if phrases.iter().any(|p| lower.contains(p)) {
4324                        count += 1;
4325                    }
4326                }
4327            }
4328        }
4329    }
4330    Probe {
4331        name: "keep_in_sync",
4332        gated: false,
4333        reads: count.to_string(),
4334    }
4335}
4336
4337// --- Reported probe 3: test_density ---------------------------------------
4338
4339/// R11.1, and §3.4's phase-3 trigger. Per crate: (lines inside `#[test]` fn bodies,
4340/// plus lines inside `#[cfg(test)] mod` blocks outside those fns) ÷ (non-blank,
4341/// non-comment lines under that crate's `src/`) — #999 Decision F's definition,
4342/// written down precisely because an undefined "ratio" is exactly the ambiguity that
4343/// produced the track doc §9's four-row ambiguity.
4344fn test_density(root: &Path) -> Probe {
4345    let mut parts = Vec::new();
4346    for dir in top_level_crate_dirs(root) {
4347        let name = dir.file_name().unwrap().to_string_lossy().to_string();
4348        let src_dir = dir.join("src");
4349        let mut test_lines = 0usize;
4350        let mut code_lines = 0usize;
4351        for (_, contents) in rust_files(&src_dir) {
4352            let lines: Vec<&str> = contents.lines().collect();
4353            let ranges = test_mod_ranges(&lines);
4354            for (i, line) in lines.iter().enumerate() {
4355                let is_blank_or_comment = line.trim().is_empty() || is_line_comment(line);
4356                if !is_blank_or_comment {
4357                    code_lines += 1;
4358                }
4359                if in_test_range(i, &ranges) && !is_blank_or_comment {
4360                    test_lines += 1;
4361                }
4362            }
4363        }
4364        if code_lines > 0 {
4365            let ratio = 100.0 * test_lines as f64 / code_lines as f64;
4366            parts.push(format!("{name}={ratio:.1}%"));
4367        }
4368    }
4369    Probe {
4370        name: "test_density",
4371        gated: false,
4372        reads: parts.join(", "),
4373    }
4374}
4375
4376// --- Reported probe: module_lines -------------------------------------------
4377
4378/// A source file at least this many production lines long counts as large.
4379const MODULE_LINES_THRESHOLDS: [usize; 3] = [2000, 3000, 5000];
4380
4381/// The probe's one-line reading from `(path from the repo root, production lines)`
4382/// pairs: how many files reach each threshold, the largest file anywhere, the three
4383/// largest back-half files, the back-half files at or over the track's exit cap
4384/// ([`crate::module_lines::EXIT_CAP`], §8's "Back-half files ≥ 3,000 lines (production)"),
4385/// and how many ceilings `xtask/module-line-ceilings.txt` holds. Ties break on path so the
4386/// reading is stable.
4387fn module_lines_reading(files: &[(String, usize)], ceilings: usize) -> String {
4388    let at_least = |n: usize| files.iter().filter(|(_, l)| *l >= n).count();
4389    let mut sorted: Vec<&(String, usize)> = files.iter().collect();
4390    sorted.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
4391    let named = |f: &&(String, usize)| format!("{} {}", f.0, f.1);
4392    let largest = sorted.first().map(named).unwrap_or_else(|| "none".into());
4393    let is_back_half = |p: &str| {
4394        p.split('/')
4395            .next()
4396            .is_some_and(|c| BACK_HALF_CRATES.contains(&c))
4397    };
4398    let back_half: Vec<String> = sorted
4399        .iter()
4400        .filter(|(p, _)| is_back_half(p))
4401        .take(3)
4402        .map(named)
4403        .collect();
4404    let exit_cap = crate::module_lines::EXIT_CAP;
4405    let back_half_over_cap = files
4406        .iter()
4407        .filter(|(p, l)| is_back_half(p) && *l >= exit_cap)
4408        .count();
4409    let [a, b, c] = MODULE_LINES_THRESHOLDS;
4410    format!(
4411        "≥{a}: {} (≥{b}: {}, ≥{c}: {}); largest: {largest}; back half: {}; back half ≥{b}: {back_half_over_cap}; ceilings: {ceilings}",
4412        at_least(a),
4413        at_least(b),
4414        at_least(c),
4415        back_half.join(", ")
4416    )
4417}
4418
4419/// Phase 2 of the back-half paydown track (#3683, ratcheted by #4085). Production lines per
4420/// `src/**/*.rs` file across every top-level crate, excluding `#[cfg(test)]` modules (with
4421/// an optional `pub`/`pub(…)` visibility; `#[cfg(all(test, …))]` is a known gap, one 840-line
4422/// front-half module), whole-test files and files declared by `#[cfg(test)] mod name;`. The
4423/// reading is a trend, because naming the largest files would change the row on almost every
4424/// Rust PR; the gate is `xtask/module-line-ceilings.txt`, checked by
4425/// `xtask/tests/module_lines_ratchet.rs` over the back-half crates. Both read
4426/// [`crate::module_lines`], so there is one definition.
4427fn module_lines(root: &Path) -> Probe {
4428    let files = crate::module_lines::measure_workspace(root);
4429    let ceilings = crate::module_lines::read_ceilings(root).len();
4430    Probe {
4431        name: "module_lines",
4432        gated: false,
4433        reads: module_lines_reading(&files, ceilings),
4434    }
4435}
4436
4437// --- diagnostic_coverage ---------------------------------------------------
4438
4439/// #1662 (track #1648, G2). Registry codes that some test **asserts**, out of all
4440/// `bynk_syntax::diagnostics::REGISTRY` codes, and the count no test asserts.
4441///
4442/// Static, so it runs inside this harness: the review that set the baseline
4443/// (2026-10-01, #1647 Part 4) instrumented `CompileError::new` across a full
4444/// `cargo test --workspace`, which this harness cannot afford. Asserted is a
4445/// subset of produced (a passing test that names a code saw it), so driving the
4446/// unasserted count to the argued floor meets "every reachable code is produced
4447/// by a test" a fortiori.
4448///
4449/// A code counts as asserted when it appears in:
4450/// - line 1 of a negative fixture's `expected_error.txt` (line 2 is a message
4451///   substring and may quote other codes);
4452/// - any other non-`.bynk` file under a crate's `tests/` directory (test
4453///   sources, expected-diagnostics files, JSON goldens). `.bynk` sources are
4454///   skipped, because their comments often name the code they provoke, and Rust
4455///   sources are read with their `//` comments removed, for the same reason;
4456/// - a `#[cfg(test)] mod` block in a crate's `src/`, comments removed;
4457/// - a blessed diagnostic transcript, `site/src/diagnostics/*.txt`.
4458///
4459/// Gated at the argued floor of **4** (#1662 Decision B). Each of the four is
4460/// emitted where no compiler test can reach it:
4461/// - `bynk.deploy.contract_skew`: `bynk deploy`, against a live deployment's
4462///   lock;
4463/// - `bynk.project.read_failed`: only when a host's file overlay omits a
4464///   discovered file, which neither the CLI nor the LSP does;
4465/// - `bynk.target.vendor_conflict`: needs platform-native capabilities from two
4466///   platforms, and only Cloudflare ships any today (the decision function is
4467///   unit-tested);
4468/// - `bynk.wasm.strip_failed`: stripping the compiler's own emitted TypeScript,
4469///   which fails only on an emitter bug.
4470///
4471/// `cargo xtask greenfield-status --list-unasserted` prints the codes.
4472pub fn unasserted_codes(root: &Path) -> Vec<&'static str> {
4473    let registry: BTreeSet<&'static str> = bynk_syntax::diagnostics::REGISTRY
4474        .iter()
4475        .map(|d| d.code)
4476        .collect();
4477    let mut asserted: BTreeSet<String> = BTreeSet::new();
4478    let mut note = |text: &str| {
4479        for code in registry_tokens(text) {
4480            asserted.insert(code);
4481        }
4482    };
4483    for krate in top_level_crate_dirs(root) {
4484        for (path, contents) in text_files(&krate.join("tests")) {
4485            if path.extension().is_some_and(|e| e == "bynk") {
4486                continue;
4487            }
4488            if path.file_name().is_some_and(|n| n == "expected_error.txt") {
4489                note(
4490                    contents
4491                        .lines()
4492                        .find(|l| !l.trim().is_empty())
4493                        .unwrap_or(""),
4494                );
4495            } else if path.extension().is_some_and(|e| e == "rs") {
4496                note(&strip_line_comments(&contents));
4497            } else {
4498                note(&contents);
4499            }
4500        }
4501        for (_, contents) in rust_files(&krate.join("src")) {
4502            let lines: Vec<&str> = contents.lines().collect();
4503            for (start, end) in test_mod_ranges(&lines) {
4504                note(&strip_line_comments(&lines[start..=end].join("\n")));
4505            }
4506        }
4507    }
4508    for (path, contents) in text_files(&root.join("site/src/diagnostics")) {
4509        if path.extension().is_some_and(|e| e == "txt") {
4510            note(&contents);
4511        }
4512    }
4513    registry
4514        .into_iter()
4515        .filter(|c| !asserted.contains(*c))
4516        .collect()
4517}
4518
4519/// `src` with every `//` comment (including `///` and `//!` doc comments)
4520/// removed, so a code named only in prose does not count as asserted. A `//`
4521/// inside a string literal is kept; block comments are rare enough in this
4522/// workspace to leave.
4523fn strip_line_comments(src: &str) -> String {
4524    src.lines()
4525        .map(|line| {
4526            let bytes = line.as_bytes();
4527            let (mut in_str, mut escaped) = (false, false);
4528            for (i, &b) in bytes.iter().enumerate() {
4529                if escaped {
4530                    escaped = false;
4531                } else if b == b'\\' && in_str {
4532                    escaped = true;
4533                } else if b == b'"' {
4534                    in_str = !in_str;
4535                } else if b == b'/' && !in_str && bytes.get(i + 1) == Some(&b'/') {
4536                    return &line[..i];
4537                }
4538            }
4539            line
4540        })
4541        .collect::<Vec<_>>()
4542        .join("\n")
4543}
4544
4545/// Every `bynk.<family>.<name>` token in `text` — the shape of a registry code,
4546/// whether quoted (Rust source) or bare (fixtures, transcripts).
4547fn registry_tokens(text: &str) -> Vec<String> {
4548    let bytes = text.as_bytes();
4549    let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'.';
4550    let mut out = Vec::new();
4551    let mut i = 0;
4552    while let Some(rel) = text[i..].find("bynk.") {
4553        let start = i + rel;
4554        let mut end = start;
4555        while end < bytes.len() && ident(bytes[end]) {
4556            end += 1;
4557        }
4558        if start == 0 || !ident(bytes[start - 1]) {
4559            out.push(text[start..end].trim_end_matches('.').to_string());
4560        }
4561        i = end.max(start + 1);
4562    }
4563    out
4564}
4565
4566/// Every readable UTF-8 file under `dir`, recursively, as `(path, contents)`.
4567fn text_files(dir: &Path) -> Vec<(PathBuf, String)> {
4568    let mut out = Vec::new();
4569    let mut stack = vec![dir.to_path_buf()];
4570    while let Some(d) = stack.pop() {
4571        let Ok(entries) = std::fs::read_dir(&d) else {
4572            continue;
4573        };
4574        for entry in entries.flatten() {
4575            let path = entry.path();
4576            if path.is_dir() {
4577                stack.push(path);
4578            } else if let Ok(contents) = std::fs::read_to_string(&path) {
4579                out.push((path, contents));
4580            }
4581        }
4582    }
4583    out
4584}
4585
4586fn diagnostic_coverage(root: &Path) -> Probe {
4587    let total = bynk_syntax::diagnostics::REGISTRY.len();
4588    let unasserted = unasserted_codes(root).len();
4589    Probe {
4590        name: "diagnostic_coverage",
4591        gated: true,
4592        reads: format!(
4593            "unasserted={unasserted} (asserted {}/{total})",
4594            total - unasserted
4595        ),
4596    }
4597}
4598
4599// --- explained_codes ------------------------------------------------------
4600
4601/// #3163. Registry codes with a curated `bynk explain` entry
4602/// ([`bynk_syntax::diagnostics::EXPLANATIONS`]), out of all registry codes.
4603///
4604/// Coverage is deliberately incremental (`bynk/src/explain.rs`, DECISION B),
4605/// so this is a ratchet, not a closure: `xtask/tests/greenfield_status.rs`'s
4606/// `explained_codes_never_fall` refuses a fall even when a pending file
4607/// acknowledges the probe. A new error code should ship with an explanation
4608/// (`design/proposals/README.md`, "Documentation is part of done").
4609fn explained_codes(_root: &Path) -> Probe {
4610    let total = bynk_syntax::diagnostics::REGISTRY.len();
4611    let explained = bynk_syntax::diagnostics::EXPLANATIONS.len();
4612    Probe {
4613        name: "explained_codes",
4614        gated: true,
4615        reads: format!("explained={explained} (of {total})"),
4616    }
4617}
4618
4619/// The leading count of an `explained_codes` reading (`explained=N (of M)`).
4620pub fn explained_codes_count(reading: &str) -> Option<usize> {
4621    reading
4622        .strip_prefix("explained=")?
4623        .split(' ')
4624        .next()?
4625        .parse()
4626        .ok()
4627}
4628
4629// --- Reported probe 4: fixture_kinds --------------------------------------
4630
4631/// R11.2. Fixture directories under `bynk-tests/tests` using each assertion granularity —
4632/// `expected_contains.txt` / `expected_absent.txt` / `expected_diagnostics.txt` — set
4633/// against the older, coarser `expected_error.txt` (category-string) convention.
4634///
4635/// #1660 (runtime-semantics track §3.5) added two counts:
4636/// - `warnings` (`expected_warnings.txt`, a positive fixture's pinned warnings), which
4637///   this probe had never counted;
4638/// - `run` (`expected_run.txt`), the positive fixtures whose `suite`s
4639///   `bynk-tests/tests/behaviour_fixtures.rs` actually *runs*, the one granularity that
4640///   asserts runtime behaviour rather than emitted text or diagnostics.
4641fn fixture_kinds(root: &Path) -> Probe {
4642    let tests_dir = root.join("bynk-tests/tests");
4643    let contains = count_files_named(&tests_dir, "expected_contains.txt");
4644    let absent = count_files_named(&tests_dir, "expected_absent.txt");
4645    let diagnostics = count_files_named(&tests_dir, "expected_diagnostics.txt");
4646    let error = count_files_named(&tests_dir, "expected_error.txt");
4647    let warnings = count_files_named(&tests_dir, "expected_warnings.txt");
4648    let run = count_files_named(&tests_dir, "expected_run.txt");
4649    Probe {
4650        name: "fixture_kinds",
4651        gated: false,
4652        reads: format!(
4653            "contains={contains}, absent={absent}, diagnostics={diagnostics}, error={error}, warnings={warnings}, run={run}"
4654        ),
4655    }
4656}
4657
4658fn count_files_named(dir: &Path, filename: &str) -> usize {
4659    let mut count = 0usize;
4660    count_files_named_walk(dir, filename, &mut count);
4661    count
4662}
4663
4664fn count_files_named_walk(dir: &Path, filename: &str, count: &mut usize) {
4665    let Ok(entries) = std::fs::read_dir(dir) else {
4666        return;
4667    };
4668    for entry in entries.flatten() {
4669        let path = entry.path();
4670        if path.is_dir() {
4671            count_files_named_walk(&path, filename, count);
4672        } else if path.file_name().is_some_and(|n| n == filename) {
4673            *count += 1;
4674        }
4675    }
4676}
4677
4678// --- Reported probe 5: keystroke_latency ------------------------------------
4679
4680/// Phase 8's own trend-only probe (`design/bynk-compiler-trajectory.md` §3,
4681/// "keystroke-to-diagnostic latency by query level") — settled (Q3/Q5, ADR 0414;
4682/// `design/tracks/incrementality.md` §5) as staying **"not measured" for this whole
4683/// phase's lifetime** (superseded by #3168: it now reads the committed per-release
4684/// benchmark, `design/benchmarks/`, and the row below is the measured number):
4685/// R3.15's scheduler decision defers whole (no memo table, salsa or
4686/// otherwise, ships in phase 8), and the literal latency number presupposes query
4687/// levels attributing latency to — levels [`incremental_query_types`] itself proves
4688/// exist, but attributing real latency to them needs a scheduler this phase
4689/// deliberately does not build. Added now, not deferred to whenever a scheduler
4690/// exists, so the trajectory's own §3.0 baseline table carries a live, CI-computed row
4691/// instead of a static doc claim — the same "instrument even a number that won't move
4692/// yet" precedent `test_density`/`fixture_kinds` already set for this module.
4693fn keystroke_latency(root: &Path) -> Probe {
4694    // #3168: no longer "not measured". `cargo xtask bench --record` writes one
4695    // result per release under `design/benchmarks/`; the probe reads the newest
4696    // back, so the figure is committed data (deterministic here, never timed by
4697    // this probe) and the row stays a trend, not a gate.
4698    let reads = crate::bench::latest_record(root)
4699        .and_then(|(v, record)| crate::bench::reading(v, &record))
4700        .unwrap_or_else(|| {
4701            "not measured — no recorded benchmark (`cargo xtask bench --record`, #3168)".to_string()
4702        });
4703    Probe {
4704        name: "keystroke_latency",
4705        gated: false,
4706        reads,
4707    }
4708}
4709
4710// --- Gated probe 18: unused_deps ---------------------------------------------
4711
4712/// Crate-hygiene track H-3, added by slice A4 (#2976): every declared dependency
4713/// edge carries a use. Counts the workspace members' declared dependencies with no
4714/// non-comment use in the crate's Rust sources, plus the `[workspace.dependencies]`
4715/// entries no member references. The reading is `0`, or `N (crate:dep, …)` sorted.
4716///
4717/// **What counts as a use** (A4's Decisions B and C): the dependency's crate
4718/// identifier (its manifest key with `-` as `_`, so a `package =` rename is read by
4719/// its alias) appears as a whole word on a non-`//`-comment line. That covers a
4720/// `use`, a path, a macro or derive path and a re-export. Block comments are not
4721/// stripped, so a name that appears only inside one reads as used: the probe fails
4722/// open on that shape, the way [`is_line_comment`]'s other callers do.
4723///
4724/// **Which files**: a `[dependencies]` entry is read in every `.rs` file under the
4725/// crate except `tests/`, `benches/` and `examples/`; a `[dev-dependencies]` entry in
4726/// all of them; a `[build-dependencies]` entry in the build script only (`build = "…"`,
4727/// default `build.rs`). `[target.<cfg>.…]` entries count as their kind, the cfg not
4728/// evaluated. `optional = true` entries count like any other; a `dep:` entry in
4729/// `[features]` is not a use. Files are found by walking the crate directory, so a
4730/// custom `[lib] path` or `build =` outside `src/` (as in `tree-sitter-bynk`) is read.
4731///
4732/// [`UNUSED_DEPS_ALLOWED`] is the escape hatch for a crate used only by macro
4733/// expansion, where no identifier appears in source.
4734fn unused_deps(root: &Path) -> Probe {
4735    Probe {
4736        name: "unused_deps",
4737        gated: true,
4738        reads: unused_deps_reading(&unused_deps_offenders(&unused_deps_raw(root))),
4739    }
4740}
4741
4742/// `(workspace label, dependency, reason)` triples [`unused_deps`] does not count. An
4743/// entry must name a real declared edge that would otherwise be flagged, and carry a
4744/// reason (`unused_deps_allowlist_entries_are_live` checks both), so a stale or
4745/// unexplained entry fails. The label is a crate's name, or `[workspace]` for a
4746/// `[workspace.dependencies]` entry.
4747const UNUSED_DEPS_ALLOWED: &[(&str, &str, &str)] = &[
4748    (
4749        "bynk-tests",
4750        "bynk-driver",
4751        "used by bynk/src/main.rs, which bynk-tests/src/bin/bynk-under-test.rs includes via \
4752         include!, so no identifier appears in this crate's source. Goes with the \
4753         `bynk-under-test` binary if the corpus stops spawning `bynk`.",
4754    ),
4755    (
4756        "bynk-tests",
4757        "bynk-emit",
4758        "used by bynk/src/main.rs, which bynk-tests/src/bin/bynk-under-test.rs includes via \
4759         include!, so no identifier appears in this crate's source. Goes with the \
4760         `bynk-under-test` binary if the corpus stops spawning `bynk`.",
4761    ),
4762    (
4763        "bynk-tests",
4764        "bynk-std",
4765        "declared only to switch on its `test-support` feature (the `bynk.testing` unit the \
4766         corpus runs, #3458); no identifier appears in this crate's source. Goes with that \
4767         feature if the unit moves.",
4768    ),
4769    (
4770        "bynk-tests",
4771        "clap",
4772        "used by bynk/src/main.rs, which bynk-tests/src/bin/bynk-under-test.rs includes via \
4773         include!, so no identifier appears in this crate's source. Goes with the \
4774         `bynk-under-test` binary if the corpus stops spawning `bynk`.",
4775    ),
4776];
4777
4778/// One declared edge with no use: `(crate label, dependency key, table kind)`.
4779/// `kind` is `""` for `[dependencies]`, `"dev"` or `"build"`.
4780type UnusedEdge = (String, String, &'static str);
4781
4782/// A workspace member as `(directory label, manifest text, (relative path, contents) files)`.
4783type UnusedDepsCrate = (String, String, Vec<(PathBuf, String)>);
4784
4785/// True for a member-relative path under a directory whose `.rs` text is not the
4786/// crate's own code: build output, vendored JS, or test fixture inputs (a crate name
4787/// inside a fixture string must not mask an unused edge).
4788fn unused_deps_skips(rel: &Path) -> bool {
4789    rel.components().any(|c| {
4790        matches!(
4791            c.as_os_str().to_str(),
4792            Some("target" | "node_modules" | "fixtures")
4793        )
4794    })
4795}
4796
4797/// Every unused edge under `root`, before [`UNUSED_DEPS_ALLOWED`] is applied.
4798///
4799/// Panics rather than reading `0` when it could not look: an unreadable root manifest,
4800/// an empty or glob `members`, or a member manifest that cannot be read.
4801fn unused_deps_raw(root: &Path) -> Vec<UnusedEdge> {
4802    let manifest = std::fs::read_to_string(root.join("Cargo.toml"))
4803        .unwrap_or_else(|e| panic!("unused_deps: cannot read the root Cargo.toml: {e}"));
4804    let members = workspace_members(&manifest);
4805    let crates: Vec<UnusedDepsCrate> = members
4806        .iter()
4807        .map(|dir| {
4808            let path = root.join(dir).join("Cargo.toml");
4809            let text = std::fs::read_to_string(&path)
4810                .unwrap_or_else(|e| panic!("unused_deps: cannot read {}: {e}", path.display()));
4811            let files = rust_files_relative(&root.join(dir))
4812                .into_iter()
4813                .filter(|(rel, _)| !unused_deps_skips(rel))
4814                .collect();
4815            (dir.clone(), text, files)
4816        })
4817        .collect();
4818    unused_deps_over(&manifest, &crates)
4819}
4820
4821/// `[workspace] members` of a root manifest. Panics on a manifest that does not parse,
4822/// an empty `members`, or a glob entry (this probe lists members literally).
4823fn workspace_members(manifest: &str) -> Vec<String> {
4824    let doc = manifest
4825        .parse::<toml::Table>()
4826        .unwrap_or_else(|e| panic!("unused_deps: the root Cargo.toml does not parse: {e}"));
4827    let members: Vec<String> = doc
4828        .get("workspace")
4829        .and_then(|w| w.get("members"))
4830        .and_then(|m| m.as_array())
4831        .map(|a| {
4832            a.iter()
4833                .filter_map(|v| v.as_str().map(str::to_string))
4834                .collect()
4835        })
4836        .unwrap_or_default();
4837    assert!(
4838        !members.is_empty(),
4839        "unused_deps: the root Cargo.toml lists no [workspace] members"
4840    );
4841    if let Some(glob) = members.iter().find(|m| m.contains(['*', '?', '['])) {
4842        panic!("unused_deps: workspace member `{glob}` is a glob; list members literally");
4843    }
4844    members
4845}
4846
4847/// A manifest's dependency tables as `(key, kind, is_workspace_ref)`, covering the
4848/// three kinds at the top level and under every `[target.<cfg>]`.
4849fn declared_edges(doc: &toml::Table) -> Vec<(String, &'static str, bool)> {
4850    let mut out = Vec::new();
4851    let mut collect = |tables: &toml::Table| {
4852        for (table, kind) in [
4853            ("dependencies", ""),
4854            ("dev-dependencies", "dev"),
4855            ("build-dependencies", "build"),
4856        ] {
4857            if let Some(deps) = tables.get(table).and_then(|t| t.as_table()) {
4858                for (key, value) in deps {
4859                    let workspace_ref = value
4860                        .as_table()
4861                        .and_then(|t| t.get("workspace"))
4862                        .and_then(|w| w.as_bool())
4863                        .unwrap_or(false);
4864                    out.push((key.clone(), kind, workspace_ref));
4865                }
4866            }
4867        }
4868    };
4869    collect(doc);
4870    if let Some(targets) = doc.get("target").and_then(|t| t.as_table()) {
4871        for target in targets.values().filter_map(|t| t.as_table()) {
4872            collect(target);
4873        }
4874    }
4875    out
4876}
4877
4878/// [`unused_deps_raw`]'s counting logic over in-memory inputs: the root manifest and
4879/// each member as `(directory label, manifest text, (relative path, contents) files)`.
4880fn unused_deps_over(root_manifest: &str, crates: &[UnusedDepsCrate]) -> Vec<UnusedEdge> {
4881    let mut out: Vec<UnusedEdge> = Vec::new();
4882    let mut referenced: BTreeSet<String> = BTreeSet::new();
4883    for (dir, manifest, files) in crates {
4884        let doc = manifest
4885            .parse::<toml::Table>()
4886            .unwrap_or_else(|e| panic!("unused_deps: {dir}/Cargo.toml does not parse: {e}"));
4887        let name = doc
4888            .get("package")
4889            .and_then(|p| p.get("name"))
4890            .and_then(|n| n.as_str())
4891            .unwrap_or(dir)
4892            .to_string();
4893        let build_script = match doc.get("package").and_then(|p| p.get("build")) {
4894            Some(toml::Value::String(path)) => Some(path.clone()),
4895            Some(toml::Value::Boolean(false)) => None,
4896            _ => Some("build.rs".to_string()),
4897        };
4898        for (key, kind, workspace_ref) in declared_edges(&doc) {
4899            if workspace_ref {
4900                referenced.insert(key.clone());
4901            }
4902            let ident = key.replace('-', "_");
4903            let used = files.iter().any(|(rel, contents)| {
4904                let top = rel.components().next().and_then(|c| c.as_os_str().to_str());
4905                let dev_only = matches!(top, Some("tests" | "benches" | "examples"));
4906                let is_build = build_script
4907                    .as_deref()
4908                    .is_some_and(|b| rel.to_string_lossy().replace('\\', "/") == b);
4909                let in_scope = match kind {
4910                    "dev" => true,
4911                    "build" => is_build,
4912                    _ => !dev_only && !is_build,
4913                };
4914                in_scope && mentions_ident(contents, &ident)
4915            });
4916            if !used {
4917                out.push((name.clone(), key, kind));
4918            }
4919        }
4920    }
4921    if let Ok(root_doc) = root_manifest.parse::<toml::Table>()
4922        && let Some(table) = root_doc
4923            .get("workspace")
4924            .and_then(|w| w.get("dependencies"))
4925            .and_then(|d| d.as_table())
4926    {
4927        for key in table.keys() {
4928            if !referenced.contains(key) {
4929                out.push(("[workspace]".to_string(), key.clone(), ""));
4930            }
4931        }
4932    }
4933    out
4934}
4935
4936/// True if some non-`//`-comment line of `src` holds `ident` as a whole word (the
4937/// characters on either side are not identifier characters).
4938fn mentions_ident(src: &str, ident: &str) -> bool {
4939    let is_word = |c: char| c.is_ascii_alphanumeric() || c == '_';
4940    src.lines().filter(|l| !is_line_comment(l)).any(|line| {
4941        line.match_indices(ident).any(|(at, _)| {
4942            let before = line[..at].chars().next_back();
4943            let after = line[at + ident.len()..].chars().next();
4944            !before.is_some_and(is_word) && !after.is_some_and(is_word)
4945        })
4946    })
4947}
4948
4949/// `crate:dep` (with `[dev]`/`[build]` for those tables) for every edge not in
4950/// [`UNUSED_DEPS_ALLOWED`], sorted.
4951fn unused_deps_offenders(raw: &[UnusedEdge]) -> Vec<String> {
4952    let mut out: Vec<String> = raw
4953        .iter()
4954        .filter(|(krate, dep, _)| {
4955            !UNUSED_DEPS_ALLOWED
4956                .iter()
4957                .any(|(k, d, _)| k == krate && d == dep)
4958        })
4959        .map(|(krate, dep, kind)| match *kind {
4960            "" => format!("{krate}:{dep}"),
4961            kind => format!("{krate}:{dep}[{kind}]"),
4962        })
4963        .collect();
4964    out.sort();
4965    out
4966}
4967
4968/// `N (a, b, …)`, or `0`.
4969fn unused_deps_reading(offenders: &[String]) -> String {
4970    if offenders.is_empty() {
4971        "0".to_string()
4972    } else {
4973        format!("{} ({})", offenders.len(), offenders.join(", "))
4974    }
4975}
4976
4977// --- Rendering + diffing ---------------------------------------------------
4978
4979/// The committed table: a plain Markdown table, probe name → gated?/reads, plus a
4980/// pointer to the rule ledger `stamp::apply` writes (#1001).
4981pub fn render_table(report: &Report) -> String {
4982    let mut out = String::new();
4983    out.push_str("<!-- GENERATED FILE — do not edit by hand.\n");
4984    out.push_str("     Source: cargo xtask greenfield-status (xtask/src/greenfield_status.rs).\n");
4985    out.push_str("     Regenerate with: cargo xtask greenfield-status --apply -->\n\n");
4986    out.push_str("# Greenfield status\n\n");
4987    out.push_str(
4988        "Track slice T0.0 (#999); `ts_writes`/`ts_any` added by P7.0 (#1296); \
4989         `verbatim_origins`/`verbatim_sites` added by P7.5 (#1307); \
4990         `incremental_query_types`/`keystroke_latency` added by P8.0 (#1510); \
4991         `unconsumed_ir_items` added by Slice D3 of the IR cutover (#1542); \
4992         `diagnostic_coverage` added by #1662; `model_readers_beyond_emit` added by \
4993         crate-hygiene B1 (#2939); `unused_deps` added by crate-hygiene A4 (#2976); `explained_codes` added by #3163; `ts_raw_sites`/`ts_text_idents` added by #3681; \
4994         `ts_raw_sites` split into `ts_raw_sites_emit`/`ts_raw_sites_testgen` and `emit_thread_locals` \
4995         added by 1A.19; `emit_silent_fallbacks` added by 1A.34; `emit_print_calls` added by 1A.35b \
4996         (`lowering_text_bridge` and `stmt_text_lines`, added by #3694 and #3711, were retired at 0 by 1A.35b); \
4997         `import_prediction_fns` added by 1A.36a; `deploy_kind_accessors` added by 1D.1a; \
4998         `env_protocol_literals` added by 1D.5a; `tool_spawn_sites` added by 1D.5b; \
4999         `deploy_ledger_writes` added by 1D.2a; `testgen_print_calls` added by 1B.2a; `node_builder_defs` added by 1B.4a; \
5000         `binding_kind_homes` added by 1C.1b; `wrangler_key_literals` added by 1C.2; `cloudflare_client_sites` added by 1D.3a. Thirty-five \
5001         probes are gated — a disagreement between this file and a fresh run fails \
5002         `greenfield_status_table_is_current` (`xtask/tests/greenfield_status.rs`). \
5003         Five are trend probes, reported only.\n\n",
5004    );
5005    // Two tables, not one: the stamp rewrites the gated rows and the weekly
5006    // trend workflow rewrites the trend rows, and git treats changed hunks on
5007    // adjacent lines as a conflict. The sub-heading keeps unchanged lines
5008    // between the two blocks, so the two writers never conflict.
5009    let row = |out: &mut String, probe: &Probe| {
5010        let _ = writeln!(
5011            out,
5012            "| `{}` | {} | {} |",
5013            probe.name,
5014            if probe.gated { "yes" } else { "no (trend)" },
5015            probe.reads
5016        );
5017    };
5018    out.push_str("| Probe | Gated | Reads |\n|---|---|---|\n");
5019    for probe in report.probes.iter().filter(|p| p.gated) {
5020        row(&mut out, probe);
5021    }
5022    out.push_str("\n## Trend probes (not gated)\n\n");
5023    out.push_str("| Probe | Gated | Reads |\n|---|---|---|\n");
5024    for probe in report.probes.iter().filter(|p| !p.gated) {
5025        row(&mut out, probe);
5026    }
5027
5028    out.push_str("\n## Rules closed\n\n");
5029    // A static, unconditional link — not a count, and not even an existence
5030    // check. A first draft read `design/greenfield-status-rules.md` here to
5031    // report a row count, but nothing regenerates *this* file when `stamp`
5032    // writes the ledger (`stamp.yml` never runs `greenfield-status --apply`,
5033    // and the gating test only diffs the nine probes) — so a count or an
5034    // exists/doesn't-exist message would silently go stale the moment the
5035    // first `closes_rule` landed, which is exactly the drift this section
5036    // exists to avoid, not invite (#1001 review). Static text can't go stale;
5037    // the ledger is one click away either way.
5038    out.push_str(
5039        "See [`design/greenfield-status-rules.md`](greenfield-status-rules.md) for rule ids \
5040         closed so far (written by `cargo xtask stamp --apply` at merge; may not exist yet if \
5041         no increment has cited `closes_rule`).\n",
5042    );
5043    out
5044}
5045
5046/// Every gated probe whose live reading disagrees with the committed table's, as
5047/// `(probe name, committed, live)`. Trend probes are never compared, and never
5048/// computed here — this only runs the twenty-one gated probes, so checking currency never
5049/// pays for `wildcard_arms`'s workspace-wide clippy pass. For a caller that has already
5050/// run the full report (e.g. to print it), use [`gated_disagreements_in`] instead so the
5051/// twenty-one gated probes aren't computed a second time.
5052pub fn gated_disagreements(root: &Path) -> Vec<(String, String, String)> {
5053    gated_disagreements_in(&run_gated(root), root)
5054}
5055
5056/// Like [`gated_disagreements`], but diffs `probes` (typically a [`Report`]'s
5057/// `.probes`, already computed) instead of re-running the gated probes.
5058pub fn gated_disagreements_in(probes: &[Probe], root: &Path) -> Vec<(String, String, String)> {
5059    let committed = std::fs::read_to_string(table_path(root)).unwrap_or_default();
5060    let mut out = Vec::new();
5061    for probe in probes.iter().filter(|p| p.gated) {
5062        let row_prefix = format!("| `{}` | yes | ", probe.name);
5063        let committed_reads = committed
5064            .lines()
5065            .find(|l| l.starts_with(&row_prefix))
5066            .and_then(|l| l.strip_prefix(&row_prefix))
5067            .and_then(|l| l.strip_suffix(" |"))
5068            .unwrap_or("<row missing>");
5069        if committed_reads != probe.reads {
5070            out.push((
5071                probe.name.to_string(),
5072                committed_reads.to_string(),
5073                probe.reads.clone(),
5074            ));
5075        }
5076    }
5077    out
5078}
5079
5080/// The disagreements no pending file acknowledges — what actually fails the gate.
5081///
5082/// A gated probe may move in a PR in one of two ways: the PR regenerates
5083/// `design/greenfield-status.md` itself (the original mechanism, still valid for
5084/// a change that carries no increment), or the PR's `design/pending/<slug>.md`
5085/// names the probe in its `probes` key and leaves the table alone. The second
5086/// keeps the acknowledgement in review — a probe still cannot move silently —
5087/// without every probe-moving PR editing the same shared rows, which is what
5088/// made this table the repo's most-conflicted file. The stamp then rewrites the
5089/// gated rows on `main` in merge order ([`refresh_gated_rows`]).
5090pub fn unacknowledged(
5091    disagreements: Vec<(String, String, String)>,
5092    acknowledged: &BTreeSet<String>,
5093) -> Vec<(String, String, String)> {
5094    disagreements
5095        .into_iter()
5096        .filter(|(name, _, _)| !acknowledged.contains(name))
5097        .collect()
5098}
5099
5100/// `committed` (the table's current text) with every gated row's reading
5101/// replaced by `probes`' live one; trend rows, prose and the rule-ledger pointer
5102/// are left exactly as committed, so the stamp never pays for the trend probes'
5103/// workspace-wide clippy pass. Errors naming any gated probe with no row to
5104/// rewrite — a table that has lost a row needs a full
5105/// `cargo xtask greenfield-status --apply`, not a silent append.
5106pub fn refresh_gated_rows(committed: &str, probes: &[Probe]) -> Result<String, String> {
5107    let mut out = String::with_capacity(committed.len());
5108    let mut seen = BTreeSet::new();
5109    for line in committed.split_inclusive('\n') {
5110        let replacement = probes.iter().filter(|p| p.gated).find_map(|p| {
5111            let prefix = format!("| `{}` | yes | ", p.name);
5112            line.starts_with(&prefix).then(|| {
5113                seen.insert(p.name);
5114                let eol = if line.ends_with('\n') { "\n" } else { "" };
5115                format!("{prefix}{} |{eol}", p.reads)
5116            })
5117        });
5118        out.push_str(replacement.as_deref().unwrap_or(line));
5119    }
5120    let missing: Vec<_> = probes
5121        .iter()
5122        .filter(|p| p.gated && !seen.contains(p.name))
5123        .map(|p| p.name)
5124        .collect();
5125    if missing.is_empty() {
5126        Ok(out)
5127    } else {
5128        Err(format!(
5129            "design/greenfield-status.md has no row for gated probe(s) {} — run \
5130             `cargo xtask greenfield-status --apply`",
5131            missing.join(", ")
5132        ))
5133    }
5134}
5135
5136/// `committed` (the table's current text) with every trend row's reading replaced
5137/// by `probes`' live one: the mirror of [`refresh_gated_rows`]. Gated rows, prose
5138/// and the rule-ledger pointer are left exactly as committed, so the weekly
5139/// trend-refresh workflow (`.github/workflows/greenfield-trends.yml`) and the
5140/// stamp never write the same lines.
5141///
5142/// Errors, rather than committing a bad table, when a trend probe has no row to
5143/// rewrite, or when a probe reports a *measurement failure* as its reading. Today
5144/// that is only `wildcard_arms`' `error running clippy: ...`; a failed clippy pass
5145/// must never be recorded as a measurement. Other non-figure readings are not
5146/// refused: `keystroke_latency` reads a committed benchmark file, so its
5147/// `not measured ...` is a truthful reading when the file is absent, not a failure.
5148pub fn refresh_trend_rows(committed: &str, probes: &[Probe]) -> Result<String, String> {
5149    let failed: Vec<_> = probes
5150        .iter()
5151        .filter(|p| !p.gated && p.reads.starts_with("error running"))
5152        .map(|p| format!("{}: {}", p.name, p.reads))
5153        .collect();
5154    if !failed.is_empty() {
5155        return Err(format!(
5156            "a trend probe failed to measure, refusing to write it as a reading: {}",
5157            failed.join("; ")
5158        ));
5159    }
5160    let mut out = String::with_capacity(committed.len());
5161    let mut seen = BTreeSet::new();
5162    for line in committed.split_inclusive('\n') {
5163        let replacement = probes.iter().filter(|p| !p.gated).find_map(|p| {
5164            let prefix = format!("| `{}` | no (trend) | ", p.name);
5165            line.starts_with(&prefix).then(|| {
5166                seen.insert(p.name);
5167                let eol = if line.ends_with('\n') { "\n" } else { "" };
5168                format!("{prefix}{} |{eol}", p.reads)
5169            })
5170        });
5171        out.push_str(replacement.as_deref().unwrap_or(line));
5172    }
5173    let missing: Vec<_> = probes
5174        .iter()
5175        .filter(|p| !p.gated && !seen.contains(p.name))
5176        .map(|p| p.name)
5177        .collect();
5178    if missing.is_empty() {
5179        Ok(out)
5180    } else {
5181        Err(format!(
5182            "design/greenfield-status.md has no row for trend probe(s) {} — run \
5183             `cargo xtask greenfield-status --apply`",
5184            missing.join(", ")
5185        ))
5186    }
5187}
5188
5189/// The stamp's refreshed table: [`refresh_gated_rows`], but only if every gated
5190/// probe whose live reading differs from `committed` is named by one of the
5191/// increments being stamped (`acknowledged` — the union of their `probes`).
5192///
5193/// Rewriting every gated row unconditionally would silently absorb a move that
5194/// reached `main` with no acknowledgement (a bypass push, say): after the stamp
5195/// the table would match by construction, and nothing downstream could notice.
5196/// Refusing instead keeps the invariant the gate enforces on PRs — a gated probe
5197/// never moves unacknowledged — true on `main` too. The stamp computes this
5198/// before applying, so a refusal leaves nothing written and the pending files
5199/// in place.
5200pub fn refresh_for_stamp(
5201    committed: &str,
5202    probes: &[Probe],
5203    acknowledged: &BTreeSet<String>,
5204) -> Result<String, String> {
5205    let unnamed: Vec<String> = probes
5206        .iter()
5207        .filter(|p| p.gated && !acknowledged.contains(p.name))
5208        .filter_map(|p| {
5209            let prefix = format!("| `{}` | yes | ", p.name);
5210            let committed_reads = committed
5211                .lines()
5212                .find(|l| l.starts_with(&prefix))?
5213                .strip_prefix(&prefix)?
5214                .strip_suffix(" |")?;
5215            (committed_reads != p.reads).then(|| {
5216                format!(
5217                    "  {}: committed {committed_reads:?}, live {:?}",
5218                    p.name, p.reads
5219                )
5220            })
5221        })
5222        .collect();
5223    if !unnamed.is_empty() {
5224        return Err(format!(
5225            "gated greenfield-status probe(s) moved without being named by any increment being \
5226             stamped — refusing to absorb them into the table. Acknowledge them in a pending \
5227             file or regenerate the table in a PR:\n{}",
5228            unnamed.join("\n")
5229        ));
5230    }
5231    let seeded = seed_missing_gated_rows(committed, probes, acknowledged)?;
5232    refresh_gated_rows(&seeded, probes)
5233}
5234
5235/// `committed` with a row appended after the last gated row for every gated probe
5236/// that has none, so a slice that introduces a probe can seed its row through
5237/// `probes:` and the stamp, with no hand edit of the generated table (#3681). A
5238/// missing row for a probe no increment names is refused, as any other
5239/// unacknowledged move is. The appended row carries the live reading; the
5240/// [`refresh_gated_rows`] pass that follows is then a no-op for it.
5241fn seed_missing_gated_rows(
5242    committed: &str,
5243    probes: &[Probe],
5244    acknowledged: &BTreeSet<String>,
5245) -> Result<String, String> {
5246    let has_row = |name: &str| {
5247        let prefix = format!("| `{name}` | yes | ");
5248        committed.lines().any(|l| l.starts_with(&prefix))
5249    };
5250    let missing: Vec<&Probe> = probes
5251        .iter()
5252        .filter(|p| p.gated && !has_row(p.name))
5253        .collect();
5254    if missing.is_empty() {
5255        return Ok(committed.to_string());
5256    }
5257    let unnamed: Vec<&str> = missing
5258        .iter()
5259        .filter(|p| !acknowledged.contains(p.name))
5260        .map(|p| p.name)
5261        .collect();
5262    if !unnamed.is_empty() {
5263        return Err(format!(
5264            "design/greenfield-status.md has no row for gated probe(s) {} and no increment \
5265             being stamped names them in `probes:` — acknowledge them in a pending file or \
5266             run `cargo xtask greenfield-status --apply`",
5267            unnamed.join(", ")
5268        ));
5269    }
5270    let mut lines: Vec<String> = committed
5271        .split_inclusive('\n')
5272        .map(str::to_string)
5273        .collect();
5274    if !lines.iter().any(|l| l.contains("| yes | ")) {
5275        return Err(
5276            "design/greenfield-status.md has no gated rows to append to — run \
5277             `cargo xtask greenfield-status --apply`"
5278                .to_string(),
5279        );
5280    }
5281    let row_at = |lines: &[String], name: &str| {
5282        let prefix = format!("| `{name}` | yes | ");
5283        lines.iter().position(|l| l.starts_with(&prefix))
5284    };
5285    let gated_order: Vec<&Probe> = probes.iter().filter(|p| p.gated).collect();
5286    // Insert in probe order (the order `render_table` writes), so a later `--apply`
5287    // produces no churn: after the nearest preceding probe's row, else before the
5288    // nearest following one's.
5289    for (i, p) in gated_order.iter().enumerate() {
5290        if row_at(&lines, p.name).is_some() {
5291            continue;
5292        }
5293        let new_row = format!("| `{}` | yes | {} |\n", p.name, p.reads);
5294        let after = gated_order[..i]
5295            .iter()
5296            .rev()
5297            .find_map(|q| row_at(&lines, q.name));
5298        let at = match after {
5299            Some(idx) => {
5300                if !lines[idx].ends_with('\n') {
5301                    lines[idx].push('\n');
5302                }
5303                idx + 1
5304            }
5305            None => gated_order[i + 1..]
5306                .iter()
5307                .find_map(|q| row_at(&lines, q.name))
5308                .unwrap_or(0),
5309        };
5310        lines.insert(at, new_row);
5311    }
5312    Ok(lines.concat())
5313}
5314
5315#[cfg(test)]
5316mod tests {
5317    use super::*;
5318
5319    // --- probe acknowledgement + refresh ------------------------------------
5320
5321    fn gated(name: &'static str, reads: &str) -> Probe {
5322        Probe {
5323            name,
5324            gated: true,
5325            reads: reads.to_string(),
5326        }
5327    }
5328
5329    #[test]
5330    fn unacknowledged_drops_only_acknowledged_probes() {
5331        let d = vec![
5332            (
5333                "ts_writes".to_string(),
5334                "850".to_string(),
5335                "851".to_string(),
5336            ),
5337            ("ts_any".to_string(), "26".to_string(), "27".to_string()),
5338        ];
5339        let ack: BTreeSet<String> = ["ts_writes".to_string()].into();
5340        let left = unacknowledged(d, &ack);
5341        assert_eq!(left.len(), 1);
5342        assert_eq!(left[0].0, "ts_any");
5343    }
5344
5345    #[test]
5346    fn refresh_rewrites_gated_rows_and_leaves_the_rest() {
5347        let committed = "# Greenfield status\n\n| Probe | Gated | Reads |\n|---|---|---|\n\
5348                         | `ts_writes` | yes | 850 |\n\
5349                         | `wildcard_arms` | no (trend) | 355 |\n\nfooter\n";
5350        let out = refresh_gated_rows(committed, &[gated("ts_writes", "851")]).unwrap();
5351        assert!(out.contains("| `ts_writes` | yes | 851 |\n"));
5352        assert!(out.contains("| `wildcard_arms` | no (trend) | 355 |\n"));
5353        assert!(out.ends_with("\nfooter\n"));
5354        assert_eq!(out.lines().count(), committed.lines().count());
5355    }
5356
5357    #[test]
5358    fn growth_probes_are_a_subset_of_gated_probes() {
5359        for g in GROWTH_PROBES {
5360            assert!(GATED_PROBES.contains(&g), "{g} is not gated");
5361        }
5362    }
5363
5364    #[test]
5365    fn leading_count_reads_compound_readings() {
5366        assert_eq!(leading_count("104 (bynk-browser.ts:Claim, x)"), Some(104));
5367        assert_eq!(leading_count("0"), Some(0));
5368        assert_eq!(leading_count("explained=3"), None);
5369        assert_eq!(leading_count(""), None);
5370        assert_eq!(model_readers_count("7 (a)"), Some(7));
5371    }
5372
5373    const GROWTH_TABLE: &str = "| Probe | Gated | Reads |\n|---|---|---|\n\
5374        | `ts_writes` | yes | 100 |\n\
5375        | `ts_any` | yes | 10 |\n\
5376        | `emit_abi_shapes` | yes | 4 (a, b) |\n\
5377        | `verbatim_sites` | yes | 3 |\n\
5378        | `ts_raw_sites_emit` | yes | 41 |\n\
5379        | `ts_raw_sites_testgen` | yes | 58 |\n\
5380        | `ts_text_idents` | yes | 13 |\n\
5381        | `span_keyed_maps` | yes | 2 |\n\
5382        | `emit_thread_locals` | yes | 2 |\n\
5383        | `emit_silent_fallbacks` | yes | 15 |\n\
5384        | `emit_print_calls` | yes | 30 |\n\
5385        | `testgen_print_calls` | yes | 43 |\n\
5386        | `import_prediction_fns` | yes | 8 |\n\
5387        | `deploy_kind_accessors` | yes | 68 |\n\
5388        | `env_protocol_literals` | yes | 36 |\n\
5389        | `tool_spawn_sites` | yes | 20 |\n\
5390        | `node_builder_defs` | yes | 195 |\n\
5391        | `deploy_ledger_writes` | yes | 25 |\n\
5392        | `binding_kind_homes` | yes | 2 |\n\
5393        | `wrangler_key_literals` | yes | 0 |\n\
5394        | `cloudflare_client_sites` | yes | 34 |\n";
5395
5396    fn growth_live(ts_writes: &str, abi: &str) -> Vec<Probe> {
5397        vec![
5398            gated("ts_writes", ts_writes),
5399            gated("ts_any", "10"),
5400            gated("emit_abi_shapes", abi),
5401            gated("verbatim_sites", "3"),
5402            gated("ts_raw_sites_emit", "41"),
5403            gated("ts_raw_sites_testgen", "58"),
5404            gated("ts_text_idents", "13"),
5405            gated("span_keyed_maps", "2"),
5406            gated("emit_thread_locals", "2"),
5407            gated("emit_silent_fallbacks", "15"),
5408            gated("emit_print_calls", "30"),
5409            gated("testgen_print_calls", "43"),
5410            gated("import_prediction_fns", "8"),
5411            gated("node_builder_defs", "195"),
5412            gated("deploy_kind_accessors", "68"),
5413            gated("env_protocol_literals", "36"),
5414            gated("tool_spawn_sites", "20"),
5415            gated("deploy_ledger_writes", "25"),
5416            gated("binding_kind_homes", "2"),
5417            gated("wrangler_key_literals", "0"),
5418            gated("cloudflare_client_sites", "34"),
5419        ]
5420    }
5421
5422    #[test]
5423    fn growth_rises_reports_only_rises() {
5424        // Equal and falling readings are free; a compound reading compares by its count.
5425        let live = growth_live("99", "5 (a, b, c)");
5426        let rises = growth_rises(&live, GROWTH_TABLE).unwrap();
5427        assert_eq!(
5428            rises,
5429            vec![GrowthRise {
5430                probe: "emit_abi_shapes",
5431                from: 4,
5432                to: 5
5433            }]
5434        );
5435        assert!(
5436            growth_rises(&growth_live("100", "4 (z)"), GROWTH_TABLE)
5437                .unwrap()
5438                .is_empty()
5439        );
5440    }
5441
5442    #[test]
5443    fn a_rise_needs_a_raise_and_passes_with_one() {
5444        let rises = growth_rises(&growth_live("101", "4"), GROWTH_TABLE).unwrap();
5445        assert_eq!(unraised(rises.clone(), &BTreeSet::new()).len(), 1);
5446        let raised: BTreeSet<String> = ["ts_writes".to_string()].into();
5447        assert!(unraised(rises.clone(), &raised).is_empty());
5448        // Raising a different probe does not excuse this one.
5449        let other: BTreeSet<String> = ["ts_any".to_string()].into();
5450        assert_eq!(unraised(rises, &other).len(), 1);
5451    }
5452
5453    #[test]
5454    fn check_growth_needs_a_valid_raise_and_names_invalid_pending_files() {
5455        let root = std::env::temp_dir().join("xtask-check-growth");
5456        let _ = std::fs::remove_dir_all(&root);
5457        std::fs::create_dir_all(root.join("design/pending")).unwrap();
5458        let live = growth_live("101", "4");
5459        // No pending file: the rise is refused.
5460        let e = check_growth(&live, GROWTH_TABLE, &root).unwrap_err();
5461        assert!(e.contains("ts_writes: committed 100, live 101"), "{e}");
5462        // A malformed pending file: say so, not a bare unraised rise.
5463        std::fs::write(root.join("design/pending/bad.md"), "no frontmatter\n").unwrap();
5464        let e = check_growth(&live, GROWTH_TABLE, &root).unwrap_err();
5465        assert!(
5466            e.contains("pending files are invalid") && e.contains("check-pending"),
5467            "{e}"
5468        );
5469        // A valid raise passes.
5470        std::fs::write(
5471            root.join("design/pending/bad.md"),
5472            "---\nlevel: patch\nchangelog: x\nraises: ts_writes — why\n---\n",
5473        )
5474        .unwrap();
5475        assert!(check_growth(&live, GROWTH_TABLE, &root).is_ok());
5476    }
5477
5478    #[test]
5479    fn a_growth_probe_without_a_leading_count_is_a_hard_failure() {
5480        let live = growth_live("many", "4");
5481        let errs = growth_rises(&live, GROWTH_TABLE).unwrap_err();
5482        assert!(errs.iter().any(|e| e.contains("ts_writes")));
5483        let bad_row = "| Probe | Gated | Reads |\n|---|---|---|\n\
5484                       | `ts_writes` | yes | many |\n";
5485        let errs = growth_rises(&growth_live("1", "1"), bad_row).unwrap_err();
5486        assert_eq!(errs.len(), 1, "{errs:?}");
5487        assert!(errs[0].contains("ts_writes"));
5488    }
5489
5490    /// #3681: a growth probe with no committed row is newly introduced — it passes
5491    /// at any reading — while the same probe is checked once its row exists.
5492    #[test]
5493    fn a_growth_probe_with_no_committed_row_is_newly_introduced() {
5494        let without = GROWTH_TABLE
5495            .lines()
5496            .filter(|l| !l.contains("emit_thread_locals") && !l.contains("ts_text_idents"))
5497            .collect::<Vec<_>>()
5498            .join("\n");
5499        let mut live = growth_live("100", "4");
5500        live.iter_mut()
5501            .find(|p| p.name == "emit_thread_locals")
5502            .unwrap()
5503            .reads = "9999".to_string();
5504        assert!(
5505            growth_rises(&live, &without).unwrap().is_empty(),
5506            "no row at the base: newly introduced, not a rise"
5507        );
5508        // Once the row exists, the same reading is a rise.
5509        let rises = growth_rises(&live, GROWTH_TABLE).unwrap();
5510        assert_eq!(rises.len(), 1);
5511        assert_eq!(rises[0].probe, "emit_thread_locals");
5512        // A probe that did not run is still a hard failure even with no row.
5513        let mut missing = growth_live("100", "4");
5514        missing.retain(|p| p.name != "ts_text_idents");
5515        assert!(growth_rises(&missing, &without).is_err());
5516    }
5517
5518    /// #3681: the stamp seeds the row of a newly introduced gated probe when an
5519    /// increment names it, and refuses when none does.
5520    #[test]
5521    fn the_stamp_seeds_a_new_gated_probe_row_only_when_acknowledged() {
5522        let committed = "| Probe | Gated | Reads |\n|---|---|---|\n\
5523                         | `ts_writes` | yes | 850 |\n\
5524                         \n## Trend probes (not gated)\n\n\
5525                         | `wildcard_arms` | no (trend) | 355 |\n";
5526        let live = [gated("ts_writes", "850"), gated("ts_raw_sites", "75")];
5527        let ack: BTreeSet<String> = ["ts_raw_sites".to_string()].into();
5528        let out = refresh_for_stamp(committed, &live, &ack).unwrap();
5529        assert!(out.contains("| `ts_writes` | yes | 850 |\n| `ts_raw_sites` | yes | 75 |\n\n"));
5530        assert!(out.contains("| `wildcard_arms` | no (trend) | 355 |"));
5531        let err = refresh_for_stamp(committed, &live, &BTreeSet::new()).unwrap_err();
5532        assert!(err.contains("ts_raw_sites"), "{err}");
5533    }
5534
5535    /// #3681 review: seeded rows land in probe order (where `render_table` puts them),
5536    /// not after the last gated row, so a later `--apply` has nothing to move.
5537    #[test]
5538    fn seeded_rows_follow_probe_order() {
5539        let committed = "| Probe | Gated | Reads |\n|---|---|---|\n\
5540                         | `a` | yes | 1 |\n\
5541                         | `d` | yes | 4 |\n\
5542                         | `e` | yes | 5 |\n\n## Trend\n";
5543        let live = [
5544            gated("a", "1"),
5545            gated("b", "2"),
5546            gated("c", "3"),
5547            gated("d", "4"),
5548            gated("e", "5"),
5549            gated("f", "6"),
5550        ];
5551        let ack: BTreeSet<String> = ["b", "c", "f"].map(String::from).into();
5552        let out = refresh_for_stamp(committed, &live, &ack).unwrap();
5553        let rows: Vec<&str> = out.lines().filter(|l| l.contains("| yes |")).collect();
5554        let names: Vec<&str> = rows.iter().map(|l| l.split('`').nth(1).unwrap()).collect();
5555        assert_eq!(names, ["a", "b", "c", "d", "e", "f"]);
5556        // A missing first row goes before the first existing one.
5557        let live = [gated("z", "0"), gated("a", "1")];
5558        let ack: BTreeSet<String> = ["z".to_string()].into();
5559        let out = refresh_for_stamp("| `a` | yes | 1 |\n\nx\n", &live, &ack).unwrap();
5560        assert!(out.starts_with("| `z` | yes | 0 |\n| `a` | yes | 1 |\n"));
5561    }
5562
5563    fn files_of(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
5564        files
5565            .iter()
5566            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
5567            .collect()
5568    }
5569
5570    #[test]
5571    fn ts_raw_sites_counts_construction_lines_only() {
5572        let src = "fn f() {\n    let a = TsStmt::raw(text, span);\n    \
5573                   let b = TsStmt::raw(\n        x,\n        span,\n    );\n    \
5574                   // TsStmt::raw(commented, span)\n    \
5575                   let c = MyTsStmt::raw(x);\n    let d = TsStmt::verbatim(x);\n}\n";
5576        assert_eq!(
5577            ts_raw_sites_violations(&files_of(&[("a.rs", src)]), false),
5578            2,
5579            "two construction lines; comment, longer name and verbatim excluded"
5580        );
5581        // Sites in several files add up.
5582        assert_eq!(
5583            ts_raw_sites_violations(&files_of(&[("a.rs", src), ("b.rs", src)]), false),
5584            4
5585        );
5586    }
5587
5588    /// 1A.36a: a surviving fixed snippet moved onto `TsStmt::raw_using(` is still a raw site, so
5589    /// the probe keeps measuring it (the four survivors read 4, not 0).
5590    #[test]
5591    fn ts_raw_sites_counts_raw_using_as_well_as_raw() {
5592        let count = |src: &str| ts_raw_sites_violations(&files_of(&[("a.rs", src)]), false);
5593        assert_eq!(
5594            count("fn f() { push(TsStmt::raw_using(TEXT, NAMES)); }\n"),
5595            1
5596        );
5597        assert_eq!(count("fn f() { push(TsStmt::raw(TEXT, None)); }\n"), 1);
5598        // One of each, on their own lines, add up; a longer type name does not count.
5599        let both = "fn f() {\n    a(TsStmt::raw(T, None));\n    b(TsStmt::raw_using(T, N));\n    \
5600                    c(MyTsStmt::raw_using(T, N));\n    // TsStmt::raw_using(T, N)\n}\n";
5601        assert_eq!(count(both), 2);
5602        // `raw_using` is not a prefix match of some other name.
5603        assert_eq!(
5604            count("fn f() { TsStmt::raw_usingx(T); TsStmt::rawish(T); }\n"),
5605            0
5606        );
5607    }
5608
5609    #[test]
5610    fn deploy_kind_accessors_counts_accessor_sites_outside_tests_and_comments() {
5611        let count = |src: &str| deploy_kind_accessors_violations(&files_of(&[("ledger.rs", src)]));
5612        // A definition and a call, of each family.
5613        let src = "pub(crate) fn record_r2(\n\
5614                   let id = recorded_d1(lock, w, b, e);\n\
5615                   lock.record_queue(env, q);\n\
5616                   lock.forget_vectorize(env, w, b, i);\n\
5617                   let (id, new) = lock.allocate_ratelimit(env, w, b);\n";
5618        assert_eq!(count(src), 5);
5619        // A word boundary and a call: a longer name, a path and a mention are not accessors.
5620        assert_eq!(
5621            count("fn my_recorded_kv() {}\nlet f = record_kv;\nlock.recorded::<Kv>(e, w, b);\n"),
5622            0
5623        );
5624        // #3929's pattern, as it measured 68: a definition with generics is not matched.
5625        assert_eq!(count("pub(crate) fn recorded_kv_binding<'a>(\n"), 0);
5626        // A comment, a test module (deploy's are `pub(crate)`) and a wholly-test file do not count.
5627        let src = "// record_kv(\n#[cfg(test)]\nmod tests {\n    fn t() { lock.record_kv(a, b, c, d); }\n}\n";
5628        assert_eq!(count(src), 0);
5629        let src =
5630            "#[cfg(test)]\npub(crate) mod tests {\n    fn t() { lock.record_kv(a, b, c, d); }\n}\n";
5631        assert_eq!(count(src), 0);
5632        assert_eq!(
5633            deploy_kind_accessors_violations(&files_of(&[
5634                ("hyperdrive/tests.rs", "lock.record_hyperdrive(a);\n"),
5635                ("snapshot_tests.rs", "recorded_r2(l, w, b, e);\n"),
5636                ("hyperdrive.rs", "lock.record_hyperdrive(a);\n"),
5637            ])),
5638            1
5639        );
5640    }
5641
5642    #[test]
5643    fn env_protocol_literals_counts_protocol_names_outside_tests_comments_and_the_table() {
5644        let count = |src: &str| {
5645            env_protocol_literals_violations(&files_of(&[("bynk-driver/src/run.rs", src)]))
5646        };
5647        // A name, a prefix spelt into a `format!`, a family member and a binding name.
5648        let src = "cmd.env(\"BYNK_TEST_SEED\", hex);\n\
5649                   format!(\"BYNK_DATASET_{binding}\")\n\
5650                   let k = \"BYNK_CALL_FROM_SHOP__ORDERS\";\n\
5651                   name: \"__BYNK_INSPECT_REGISTRY\".to_string(),\n";
5652        assert_eq!(count(src), 4);
5653        // Not protocol names: Rust-only configuration, a longer name than an exact entry,
5654        // a runtime constant, a misspelling and a constant path.
5655        let src = "env::var(\"BYNK_HOME\")\nenv::var(\"BYNK_DEV_COMMAND\")\n\
5656                   \"__BYNK_TIMED_OUT\"\n\"BYNK_TEST_SEDE\"\ncmd.env(env_protocol::TEST_SEED, h);\n";
5657        assert_eq!(count(src), 0);
5658        // Comments and test modules (deploy's are `pub(crate)`) do not count.
5659        let src =
5660            "// BYNK_TEST_SEED\n#[cfg(test)]\nmod tests {\n    const S: &str = \"BYNK_DEV\";\n}\n";
5661        assert_eq!(count(src), 0);
5662        let src = "#[cfg(test)]\npub(crate) mod tests {\n    const S: &str = \"BYNK_DEV\";\n}\n";
5663        assert_eq!(count(src), 0);
5664        // The table, the diagnostics' prose and a wholly-test file are exempt.
5665        assert_eq!(
5666            env_protocol_literals_violations(&files_of(&[
5667                (
5668                    "bynk-project/src/env_protocol.rs",
5669                    "pub const DEV: &str = \"BYNK_DEV\";\n"
5670                ),
5671                (
5672                    "bynk-syntax/src/diagnostics.rs",
5673                    "blurb: \"`BYNK_CALL_TO_<CONTEXT>`\",\n"
5674                ),
5675                ("bynk/src/deploy/tests.rs", "\"BYNK_DEV\"\n"),
5676                ("bynk/src/dev.rs", "\"BYNK_DEV\"\n"),
5677            ])),
5678            1
5679        );
5680    }
5681
5682    #[test]
5683    fn tool_spawn_sites_counts_spawns_outside_tools_probe_and_tests_by_reason() {
5684        let reading = |files: &[(&str, &str)]| tool_spawn_sites_reading(&files_of(files));
5685        let src = "let mut cmd = Command::new(p);\n\
5686                   let mut cmd = std::process::Command::new(\"git\");\n\
5687                   let _ = ProcCommand::new(\"taskkill\")\n";
5688        assert_eq!(
5689            reading(&[("bynk/src/workers.rs", src)]),
5690            "3 (process control 1, self re-execution 0, other 2)"
5691        );
5692        assert_eq!(
5693            reading(&[
5694                (
5695                    "bynk-driver/src/dev_run.rs",
5696                    "Command::new(me)\nCommand::new(\"kill\")\n"
5697                ),
5698                (
5699                    "bynk-driver/src/mutate.rs",
5700                    "std::process::Command::new(\"git\")\n"
5701                ),
5702            ]),
5703            "3 (process control 1, self re-execution 1, other 1)"
5704        );
5705        // The tools module, detection, comments, test modules (deploy's are `pub(crate)`),
5706        // wholly-test files and a longer name do not count.
5707        let none = "0 (process control 0, self re-execution 0, other 0)";
5708        assert_eq!(
5709            reading(&[
5710                ("bynk-driver/src/tools/mod.rs", "Command::new(\"git\")\n"),
5711                (
5712                    "bynk-driver/src/tools/ladder.rs",
5713                    "Command::new(&self.path)\n"
5714                ),
5715                ("bynk-driver/src/probe.rs", "Command::new(path)\n"),
5716                ("bynk/src/a.rs", "// Command::new(\"git\")\n"),
5717                (
5718                    "bynk/src/b.rs",
5719                    "#[cfg(test)]\nmod tests {\n    fn t() { Command::new(\"sh\"); }\n}\n",
5720                ),
5721                (
5722                    "bynk/src/c.rs",
5723                    "#[cfg(test)]\npub(crate) mod tests {\n    fn t() { Command::new(\"sh\"); }\n}\n",
5724                ),
5725                ("bynk/src/deploy/tests.rs", "Command::new(\"sh\")\n"),
5726                ("bynk/src/test_support.rs", "Command::new(\"sh\")\n"),
5727                ("bynk/src/d.rs", "MyCommand::new(x)\n"),
5728            ]),
5729            none
5730        );
5731    }
5732
5733    #[test]
5734    fn cloudflare_client_sites_counts_call_sites_outside_tests_comments_and_the_module() {
5735        let count =
5736            |src: &str| cloudflare_client_sites_violations(&files_of(&[("deploy/kv.rs", src)]));
5737        // A wrangler spawn built at the call site, the delegate's, and a REST construction.
5738        let src = "let Some(c) = workers::wrangler_command(p, \"kv\") else {\n\
5739                   bynk_driver::tools::wrangler::command(provenance, subcommand)\n\
5740                   let rest = Rest {\n\
5741                   Ok(RestListings(Rest {\n";
5742        assert_eq!(count(src), 4);
5743        // A definition, the type's own declarations, a longer name and a mention are not sites.
5744        assert_eq!(
5745            count(
5746                "pub fn wrangler_command(p: &Provenance, s: &str) -> Option<Command> {\n\
5747                 pub(crate) struct Rest {\nimpl Rest {\nimpl Cloudflare for Rest {\n\
5748                 my_wrangler_command(p);\nlet r = RestError {\n"
5749            ),
5750            0
5751        );
5752        // A comment, a test module and a wholly-test file do not count, nor does the module.
5753        let src = "// wrangler_command(\n#[cfg(test)]\npub(crate) mod tests {\n    fn t() { Rest { a }; }\n}\n";
5754        assert_eq!(count(src), 0);
5755        assert_eq!(
5756            cloudflare_client_sites_violations(&files_of(&[
5757                ("deploy/apply_tests.rs", "wrangler_command(p, \"kv\");\n"),
5758                ("cloudflare/process.rs", "tools::wrangler::command(p, s)\n"),
5759                ("test_support.rs", "wrangler_command(p, \"kv\");\n"),
5760                ("tail.rs", "wrangler_command(&probe.provenance, \"tail\")\n"),
5761            ])),
5762            1
5763        );
5764    }
5765
5766    #[test]
5767    fn binding_kind_homes_counts_files_that_construct_a_kind_or_deserialise_one() {
5768        let homes = |files: &[(&str, &str)]| binding_kind_homes_files(&files_of(files)).len();
5769        // A construction in a field, and in a match arm, each count their file once.
5770        let field = "WorkerBinding { name, source: BindingSource::Kv }\n";
5771        let arm = "match d {\n    (a, b) => BindingSource::KvInstance { capability },\n}\n";
5772        assert_eq!(homes(&[("bynk-emit/src/a.rs", field)]), 1);
5773        assert_eq!(homes(&[("bynk-emit/src/a.rs", arm)]), 1);
5774        assert_eq!(
5775            homes(&[("bynk-emit/src/a.rs", &format!("{field}{field}{arm}"))]),
5776            1
5777        );
5778        assert_eq!(
5779            homes(&[("bynk-emit/src/a.rs", field), ("bynk-driver/src/b.rs", arm)]),
5780            2
5781        );
5782        // A path-qualified construction counts too.
5783        let qualified = "source: crate::worker_bindings::BindingSource::Kv,\n";
5784        assert_eq!(homes(&[("bynk-emit/src/a.rs", qualified)]), 1);
5785        // A `Deserialize` struct named for a binding counts; one that does not derive
5786        // it, or is named otherwise, does not.
5787        let stanza = "#[derive(Debug, Deserialize)]\nstruct KvNamespaceBinding {\n}\n";
5788        let plain = "#[derive(Debug)]\nstruct KvNamespaceBinding {\n}\n";
5789        let other = "#[derive(Deserialize)]\nstruct Resources {\n}\n";
5790        assert_eq!(homes(&[("bynk/src/c.rs", stanza)]), 1);
5791        assert_eq!(homes(&[("bynk/src/c.rs", plain)]), 0);
5792        assert_eq!(homes(&[("bynk/src/c.rs", other)]), 0);
5793        let stacked = "#[derive(Deserialize)]\n/// A doc line.\n#[serde(rename_all = \"camelCase\")]\n#[serde(deny_unknown_fields)]\n#[allow(dead_code)]\n#[cfg_attr(test, derive(Debug))]\nstruct HyperdriveStanza {\n}\n";
5794        assert_eq!(homes(&[("bynk/src/c.rs", stacked)]), 1);
5795        // The derive of the struct above does not carry over a blank line or an item.
5796        let apart =
5797            "#[derive(Deserialize)]\nstruct Resources {\n}\n\nstruct KvNamespaceBinding {\n}\n";
5798        assert_eq!(homes(&[("bynk/src/c.rs", apart)]), 0);
5799        let manifest = "#[derive(Deserialize)]\n#[serde(rename_all = \"camelCase\")]\nstruct VectorizeManifestEntry {\n}\n";
5800        assert_eq!(homes(&[("bynk/src/c.rs", manifest)]), 1);
5801    }
5802
5803    #[test]
5804    fn binding_kind_homes_skips_the_vocabulary_tests_and_comments() {
5805        let homes = |files: &[(&str, &str)]| binding_kind_homes_files(&files_of(files)).len();
5806        let field = "WorkerBinding { name, source: BindingSource::Kv }\n";
5807        // The vocabulary is the one file that may define a kind.
5808        assert_eq!(homes(&[("bynk-check/src/worker_bindings.rs", field)]), 0);
5809        // A test module, a wholly-test file and a comment do not count.
5810        let in_tests = format!("fn real() {{}}\n#[cfg(test)]\nmod tests {{\n    {field}}}\n");
5811        assert_eq!(homes(&[("bynk-emit/src/a.rs", &in_tests)]), 0);
5812        let deploy_tests = format!("#[cfg(test)]\npub(crate) mod tests {{\n    {field}}}\n");
5813        assert_eq!(homes(&[("bynk/src/deploy/a.rs", &deploy_tests)]), 0);
5814        assert_eq!(homes(&[("bynk-emit/src/tests.rs", field)]), 0);
5815        assert_eq!(
5816            homes(&[("bynk-emit/src/a.rs", "// source: BindingSource::Kv\n")]),
5817            0
5818        );
5819        // A pattern, not a construction, is rendering and does not count.
5820        let pattern =
5821            "match s {\n    BindingSource::Kv => 1,\n    BindingSource::Agent { .. } => 2,\n}\n";
5822        assert_eq!(homes(&[("bynk-emit/src/a.rs", pattern)]), 0);
5823    }
5824
5825    #[test]
5826    fn wrangler_key_literals_counts_a_key_in_a_toml_position_only() {
5827        let count =
5828            |src: &str| wrangler_key_literals_count(&files_of(&[("bynk-emit/src/a.rs", src)]));
5829        // A header, a lookup, an index and a list each count; a multi-line header too.
5830        assert_eq!(count("TomlBlock::array_table(\"services\", e)\n"), 1);
5831        assert_eq!(
5832            count("TomlBlock::array_table(\n    \"queues.producers\",\n"),
5833            1
5834        );
5835        assert_eq!(count("doc.get(\"vectorize\")\n"), 1);
5836        assert_eq!(count("doc.get_mut(\"d1_databases\").x\n"), 1);
5837        assert_eq!(count("doc.entry(\"vars\")\n"), 1);
5838        assert_eq!(count("doc.remove( \"hyperdrive\" );\n"), 1);
5839        assert_eq!(count("let x = parsed[\"env\"][\"kv_namespaces\"];\n"), 1);
5840        assert_eq!(
5841            count("for key in [\"durable_objects\", \"exports\"] {}\n"),
5842            1
5843        );
5844        // Through the vocabulary, or in another position: not a key spelled.
5845        assert_eq!(count("doc.get(WranglerKey::Vectorize.top_key())\n"), 0);
5846        assert_eq!(
5847            count("Command::new(\"wrangler\").args([\"vectorize\", \"list\"])\n"),
5848            0
5849        );
5850        assert_eq!(count("let label = \"queues\";\n"), 0);
5851        // `name` is too generic, and a singleton's table is the registry's.
5852        assert_eq!(count("doc.get(\"name\")\n"), 0);
5853        assert_eq!(count("doc.get(\"images\")\n"), 0);
5854    }
5855
5856    #[test]
5857    fn wrangler_key_literals_skips_tests_comments_and_test_files() {
5858        let count = |path: &str, src: &str| wrangler_key_literals_count(&files_of(&[(path, src)]));
5859        let key = "doc.get(\"services\")";
5860        assert_eq!(count("bynk/src/a.rs", &format!("// {key}\n")), 0);
5861        assert_eq!(
5862            count(
5863                "bynk/src/a.rs",
5864                &format!("#[cfg(test)]\nmod tests {{\n    {key}\n}}\n")
5865            ),
5866            0
5867        );
5868        assert_eq!(
5869            count(
5870                "bynk/src/a.rs",
5871                &format!("#[cfg(test)]\npub(crate) mod tests {{\n    {key}\n}}\n")
5872            ),
5873            0
5874        );
5875        assert_eq!(count("bynk/src/tests.rs", key), 0);
5876        assert_eq!(
5877            count(
5878                "bynk/src/a.rs",
5879                &format!("fn f() {{\n    {key};\n}}\n{key}\n")
5880            ),
5881            2
5882        );
5883    }
5884
5885    #[test]
5886    fn deploy_ledger_writes_counts_write_sites_outside_tests_comments_and_revert() {
5887        let count = |src: &str| deploy_ledger_writes_violations(&files_of(&[("ledger.rs", src)]));
5888        // A write, and each of the 1D.1 context's writes.
5889        let src = "write_lock(self.path, self.lock)\n\
5890                   cx.record(binding, record, &done)?;\n\
5891                   cx.change(|env| f(env), &done)\n\
5892                   cx.commit(&failure)?;\n";
5893        assert_eq!(count(src), 4);
5894        // The definition, a longer name, another receiver and a mention are not writes.
5895        assert_eq!(
5896            count(
5897                "pub(crate) fn write_lock(path: &Path, lock: &DeployLock) {}\n\
5898                 my_write_lock(p);\nwriter.commit(e, c)?;\ncx.recording(b, r, d);\nlet w = write_lock;\n"
5899            ),
5900            0
5901        );
5902        // A comment, a test module (deploy's are `pub(crate)`) and a wholly-test file do not count.
5903        let src = "// write_lock(\n#[cfg(test)]\npub(crate) mod tests {\n    fn t() { write_lock(p, l).unwrap(); }\n}\n";
5904        assert_eq!(count(src), 0);
5905        assert_eq!(
5906            deploy_ledger_writes_violations(&files_of(&[
5907                ("apply_tests.rs", "write_lock(p, l);\n"),
5908                ("revert.rs", "write_lock(lock_path, lock)\n"),
5909                ("apply.rs", "write_lock(self.path, self.lock)\n"),
5910            ])),
5911            1,
5912            "`bynk revert`'s write is not the apply's"
5913        );
5914    }
5915
5916    #[test]
5917    fn node_builder_defs_counts_one_constructor_wrappers_and_ts_build_renames() {
5918        let count = |src: &str| node_builder_defs_count(&files_of(&[("emitter/a.rs", src)]));
5919        // A wrapper over one constructor, in the spellings the emitter had: a variant, a
5920        // struct variant, an associated function, a `bynk_ts::`-qualified one, and a body on
5921        // one line.
5922        let wrappers = "fn ident(s: impl Into<String>) -> TsExpr {\n    TsExpr::Ident(s.into())\n}\n\
5923                        fn member(object: TsExpr, property: &str) -> TsExpr {\n    \
5924                        TsExpr::Member {\n        object: Box::new(object),\n        \
5925                        property: property.to_string(),\n    }\n}\n\
5926                        pub(super) fn block(stmts: Vec<TsStmt>) -> TsStmt { TsStmt::block(stmts, None) }\n\
5927                        fn hist_id(name: &str) -> bynk_ts::TsExpr {\n    \
5928                        bynk_ts::TsExpr::Ident(name.to_string())\n}\n\
5929                        fn strict_eq(a: TsExpr, b: TsExpr) -> TsExpr {\n    \
5930                        TsExpr::Binary { op: TsBinaryOp::StrictEq, left: Box::new(a), right: Box::new(b) }\n}\n";
5931        assert_eq!(count(wrappers), 5);
5932        // A delegation to a builder counts (`id` over `ident_node`, `ne` over `binary`), once
5933        // the helper is one; a delegation to something unknown does not.
5934        let delegations = "fn ident_node(n: &str) -> TsExpr {\n    TsExpr::Ident(n.to_string())\n}\n\
5935                           fn id(n: &str) -> TsExpr {\n    ident_node(n)\n}\n\
5936                           fn ne(a: TsExpr, b: TsExpr) -> TsExpr {\n    \
5937                           binary(TsBinaryOp::StrictNotEq, a, b)\n}\n\
5938                           fn other(a: TsExpr) -> TsExpr {\n    somewhere_else(a)\n}\n";
5939        assert_eq!(count(delegations), 2);
5940        // Composed helpers (two constructors) are not wrappers.
5941        let composed = "fn applied(f: TsExpr, x: TsExpr) -> TsExpr {\n    call(paren(f), vec![x])\n}\n\
5942                        fn if_then(c: TsExpr, body: Vec<TsStmt>) -> TsStmt {\n    \
5943                        TsStmt::if_stmt(c, block(body), None)\n}\n";
5944        assert_eq!(count(composed), 0);
5945        // A string constant, a constant origin, a clone, a branch and another return type are
5946        // not functions of their parameters alone.
5947        let others = "fn undefined() -> TsExpr {\n    TsExpr::Ident(\"undefined\".to_string())\n}\n\
5948                      fn specs(s: String) -> TsExpr {\n    \
5949                      TsExpr::VerbatimExpr(s, VerbatimOrigin::FormFieldSpecs)\n}\n\
5950                      fn field(e: &TsExpr) -> TsExpr {\n    TsExpr::Paren(Box::new(e.clone()))\n}\n\
5951                      fn pick(c: bool, e: TsExpr) -> TsExpr {\n    if c { TsExpr::Paren(Box::new(e)) } else { e }\n}\n\
5952                      fn any_ty() -> TsType {\n    TsType::named(x)\n}\n";
5953        assert_eq!(count(others), 0);
5954        // A helper with no parameters is a constant, not a builder.
5955        let constant = "fn empty_deps() -> TsExpr {\n    TsExpr::object_entries(Vec::new())\n}\n";
5956        assert_eq!(count(constant), 0);
5957        // A `#[cfg(test)]` copy and a comment do not count; nor does `ts_build.rs` itself.
5958        let in_tests = "#[cfg(test)]\nmod tests {\n    fn ident(s: &str) -> TsExpr {\n        \
5959                        TsExpr::Ident(s.to_string())\n    }\n}\n// fn id(n: &str) -> TsExpr { TsExpr::Ident(n) }\n";
5960        assert_eq!(count(in_tests), 0);
5961        let builders = files_of(&[(
5962            "ts_build.rs",
5963            "pub(crate) fn ident(s: impl Into<String>) -> TsExpr {\n    TsExpr::Ident(s.into())\n}\n",
5964        )]);
5965        assert_eq!(node_builder_defs_count(&builders), 0);
5966        // A helper over a `ts_build` builder counts, because `ts_build` names it one.
5967        let mixed = files_of(&[
5968            (
5969                "ts_build.rs",
5970                "pub(crate) fn binary(op: TsBinaryOp, l: TsExpr, r: TsExpr) -> TsExpr {\n    \
5971                 TsExpr::Binary { op, left: Box::new(l), right: Box::new(r) }\n}\n",
5972            ),
5973            (
5974                "a.rs",
5975                "fn ne(a: TsExpr, b: TsExpr) -> TsExpr {\n    binary(TsBinaryOp::StrictNotEq, a, b)\n}\n",
5976            ),
5977        ]);
5978        assert_eq!(node_builder_defs_count(&mixed), 1);
5979        // Each `as` rename in a `ts_build` import counts, in a clause or on its own line; a plain
5980        // import and a rename from another module do not.
5981        let uses = "use crate::ts_build::{ident as id, str_lit as lit_str, member};\n\
5982                    use crate::ts_build::{\n    call as call_built,\n    paren,\n};\n\
5983                    use super::ts_build::block as stmts;\n\
5984                    use crate::ts_build::{call, index};\n\
5985                    use crate::other::{thing as that};\n";
5986        assert_eq!(count(uses), 4);
5987        let in_test_use = "#[cfg(test)]\nmod tests {\n    use crate::ts_build::ident as id;\n}\n";
5988        assert_eq!(count(in_test_use), 0);
5989        // The same wrapper in two files is two definitions.
5990        assert_eq!(
5991            node_builder_defs_count(&files_of(&[("a.rs", wrappers), ("b.rs", wrappers)])),
5992            10
5993        );
5994    }
5995
5996    #[test]
5997    fn import_prediction_fns_counts_prediction_names_outside_tests_comments_and_the_allowlist() {
5998        let count = |src: &str| import_prediction_fns_violations(&files_of(&[("a.rs", src)]));
5999        // Each of the three segments, with the visibility and qualifier forms a declaration takes.
6000        let src = "fn agent_needs_rehydrate() {}\n\
6001                   pub(crate) fn type_ref_mentions(t: &T) -> bool { true }\n\
6002                   pub const fn uses_json_codec() {}\n\
6003                   async fn file_mentions_http_result() {}\n";
6004        assert_eq!(count(src), 4);
6005        // The allowlist is the resolved-fact queries, exact names only.
6006        assert_eq!(
6007            count("pub fn unit_table_uses_emit() {}\nfn mentions_decimal() {}\n"),
6008            0
6009        );
6010        assert_eq!(count("fn mentions_decimal_extra() {}\n"), 1);
6011        // A segment, not a substring: `causes`, `focuses` and `reuses_x` name no prediction.
6012        assert_eq!(
6013            count("fn causes() {}\nfn focuses_on() {}\nfn reuses_x() {}\n"),
6014            0
6015        );
6016        // A call, a comment and a test module do not declare a function in production.
6017        let src = "fn f() { agent_needs_rehydrate(); }\n// fn uses_codec() {}\n\n\
6018                   #[cfg(test)]\nmod tests {\n    fn needs_x() {}\n}\n";
6019        assert_eq!(count(src), 0);
6020        // Counted across files.
6021        let one = "fn uses_codec() {}\n";
6022        assert_eq!(
6023            import_prediction_fns_violations(&files_of(&[("a.rs", one), ("b.rs", one)])),
6024            2
6025        );
6026    }
6027
6028    #[test]
6029    fn ts_raw_sites_excludes_cfg_test_ranges() {
6030        let src = "fn p() { TsStmt::raw(a, s); }\n\n#[cfg(test)]\nmod tests {\n    \
6031                   fn t() { TsStmt::raw(b, s); }\n}\n";
6032        assert_eq!(
6033            ts_raw_sites_violations(&files_of(&[("a.rs", src)]), false),
6034            1
6035        );
6036    }
6037
6038    #[test]
6039    fn ts_raw_sites_splits_production_from_test_harness_generation() {
6040        let src = "fn f() { let a = TsStmt::raw(text, span); }\n";
6041        let files = files_of(&[
6042            ("emitter/emit.rs", src),
6043            ("emitter/http_client.rs", src),
6044            ("testgen/test_module.rs", src),
6045            ("testgen/test_runtime/x.rs", src),
6046            ("testgen/harness.rs", src),
6047            ("emitter/testgen/stubs.rs", src),
6048            ("testgen.rs", src),
6049            ("emitter/commons_barrel.rs", src),
6050            ("project.rs", src),
6051        ]);
6052        // A `testgen` module or file is the harness (1B.2a moved it from the driver's
6053        // `project/tests_emit/**`, which is no longer a harness path).
6054        assert_eq!(ts_raw_sites_violations(&files, true), 5);
6055        // Everything else, the commons barrel and the driver's `project.rs` orchestration
6056        // included, is emission.
6057        assert_eq!(ts_raw_sites_violations(&files, false), 4);
6058        // Together they are the old combined probe: a reclassification, not a fall.
6059        assert_eq!(
6060            ts_raw_sites_violations(&files, true) + ts_raw_sites_violations(&files, false),
6061            files.len()
6062        );
6063    }
6064
6065    /// 1B.2b (#4028), from the 1B.2a review: removes its directory when dropped, so a failing
6066    /// assertion does not leave a temp tree behind for the next run's process id to meet.
6067    struct TempTree(PathBuf);
6068
6069    impl TempTree {
6070        fn new(name: &str) -> Self {
6071            let dir = std::env::temp_dir().join(format!("{name}-{}", std::process::id()));
6072            let _ = std::fs::remove_dir_all(&dir);
6073            TempTree(dir)
6074        }
6075    }
6076
6077    impl Drop for TempTree {
6078        fn drop(&mut self) {
6079            let _ = std::fs::remove_dir_all(&self.0);
6080        }
6081    }
6082
6083    /// 1B.2a (Decision D of #4028): the four production probes that read `bynk-emit/src` skip
6084    /// 1B.5e (Decision H): `emit_print_calls` reads the whole crate, the harness included.
6085    #[test]
6086    fn the_print_probe_reads_the_harness_too() {
6087        let tree = TempTree::new("bynk-testgen-split");
6088        let dir = tree.0.clone();
6089        let src = dir.join("bynk-emit/src");
6090        for (rel, text) in [
6091            ("emitter/emit.rs", "fn f() { print_stmt(&s); }\n"),
6092            (
6093                "testgen.rs",
6094                "fn g() {\n print_expr(&e);\n print_type(&t);\n}\n",
6095            ),
6096            ("testgen/harness.rs", "fn h() { print_stmt(&s); }\n"),
6097        ] {
6098            let path = src.join(rel);
6099            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
6100            std::fs::write(path, text).unwrap();
6101        }
6102        assert_eq!(emit_print_calls(&dir).reads, "4");
6103    }
6104
6105    /// 1B.5e (Decision H): the harness's prediction functions and silent fallbacks are read
6106    /// with production emission's, because the harness predicts no import and draws no silent
6107    /// `undefined` any more. Only `ast_importers` still skips it: it reads the AST by design.
6108    #[test]
6109    fn the_prediction_and_fallback_probes_read_the_harness_too() {
6110        let tree = TempTree::new("bynk-testgen-skip");
6111        let dir = tree.0.clone();
6112        let src = dir.join("bynk-emit/src");
6113        let body = "use bynk_syntax::ast::Expr;\nfn block_uses_run_id() {}\n\
6114                    fn f() { x.unwrap_or_else(|| ident(\"undefined\")); }\n";
6115        for rel in ["emitter/emit.rs", "testgen/stubs.rs", "testgen.rs"] {
6116            let path = src.join(rel);
6117            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
6118            std::fs::write(path, body).unwrap();
6119        }
6120        assert_eq!(import_prediction_fns(&dir).reads, "3");
6121        assert_eq!(emit_silent_fallbacks(&dir).reads, "3");
6122        assert_eq!(ast_importer_files(&dir).len(), 1);
6123    }
6124
6125    #[test]
6126    fn is_testgen_path_names_the_module_not_the_old_driver_directory() {
6127        assert!(is_testgen_path(Path::new("testgen.rs")));
6128        assert!(is_testgen_path(Path::new("testgen/system_support.rs")));
6129        assert!(is_testgen_path(Path::new("testgen/test_runtime/x.rs")));
6130        assert!(!is_testgen_path(Path::new("emitter/commons_barrel.rs")));
6131        assert!(!is_testgen_path(Path::new("project/tests_emit/harness.rs")));
6132        assert!(!is_testgen_path(Path::new("project/tests_emit.rs")));
6133    }
6134
6135    /// 1B.2b (#4028), from the 1B.2a review: a component that merely *starts with* `testgen`
6136    /// is not the module, so a production helper named that way is still production emission.
6137    #[test]
6138    fn is_testgen_path_matches_the_component_not_a_prefix() {
6139        assert!(!is_testgen_path(Path::new("emitter/testgen_helpers.rs")));
6140        assert!(!is_testgen_path(Path::new("testgen_helpers/x.rs")));
6141        assert!(!is_testgen_path(Path::new("emitter/testgenerator.rs")));
6142        assert!(is_testgen_path(Path::new("testgen/test_runtime/x.rs")));
6143    }
6144
6145    #[test]
6146    fn emit_thread_locals_counts_unconditional_declarations_only() {
6147        let src = "thread_local! {\n    static A: Cell<u8> = const { Cell::new(0) };\n}\n\n\
6148                   #[cfg(test)]\nthread_local! {\n    static B: Cell<u8> = const { Cell::new(0) };\n}\n\n\
6149                   #[cfg(any(test, feature = \"counters\"))]\n\nthread_local! {\n    static C: Cell<u8> = const { Cell::new(0) };\n}\n\n\
6150                   #[cfg(windows)]\nthread_local! {\n    static D: Cell<u8> = const { Cell::new(0) };\n}\n\n\
6151                   #[cfg(not(test))]\nthread_local! {\n    static E: Cell<u8> = const { Cell::new(0) };\n}\n\n\
6152                   #[cfg(feature = \"attestation\")]\nthread_local! {\n    static F: Cell<u8> = const { Cell::new(0) };\n}\n\n\
6153                   // thread_local! in a comment\n\
6154                   fn f() { let x = my_thread_local!(1); }\n";
6155        assert_eq!(
6156            emit_thread_locals_violations(&files_of(&[("a.rs", src)])),
6157            4,
6158            "the bare one and the `windows`-, `not(test)`- and `attestation`-gated ones; test-gated, commented and longer names excluded"
6159        );
6160    }
6161
6162    #[test]
6163    fn emit_silent_fallbacks_counts_a_fallback_position_followed_by_any_or_undefined() {
6164        let counted = [
6165            "let t = r.map(f).unwrap_or_else(|| \"any\");",
6166            "let t = r.unwrap_or_else(any_ty);",
6167            "        _ => any_ty(),",
6168            "        _ => (any_ty(), any_ty()),",
6169            "        None => ident(\"undefined\"),",
6170            "let p = s.as_deref().map_or(ident(\"undefined\"), probe);",
6171            "    .unwrap_or_else(|| \"undefined as never\".to_string())",
6172            "    .unwrap_or_else(|| \"undefined\".to_string());",
6173            "        Err(_) => TsType::named(\"any\"),",
6174            "        None => return pre.finish_text(\"undefined /* mock */\".to_string()),",
6175            "let slot = all.pop().unwrap_or_else(undefined);",
6176            "let n = x.unwrap_or(\"any\");",
6177        ];
6178        for line in counted {
6179            assert!(line_is_silent_fallback(line), "should count: {line}");
6180        }
6181        let clean = [
6182            // a legitimate default, rendered once
6183            "mock_value_of(ty, cx, depth, at).unwrap_or_else(undefined_node)",
6184            "let previous = s.map_or_else(undefined_node, probe);",
6185            // a reported fault
6186            "None => cx.missing_fact(span, \"type for a call\"),",
6187            ".unwrap_or_else(|| cx.missing_fact_ty(e.span, \"type\"))",
6188            // the named widening: a function body, no fallback position on the line
6189            "    TsType::named(\"any\")",
6190            "pub(crate) fn unnameable_receiver_type_arg() -> TsType { any_ty() }",
6191            // a plain construction that is not in a fallback position
6192            "let ty = any_ty();",
6193            "TsExpr::Ident(\"undefined\".to_string())",
6194            // the other fallbacks, and the construction before the position
6195            ".unwrap_or_else(|| \"unknown\".to_string())",
6196            "let a = \"any\"; let b = r.unwrap_or_else(|| 1);",
6197        ];
6198        for line in clean {
6199            assert!(!line_is_silent_fallback(line), "should not count: {line}");
6200        }
6201    }
6202
6203    #[test]
6204    fn emit_silent_fallbacks_skips_comments_and_cfg_test_modules() {
6205        let src = "// _ => any_ty(),\n\
6206                   fn f() { let a = r.unwrap_or_else(|| \"any\"); }\n\n\
6207                   #[cfg(test)]\nmod tests {\n    fn t() { let a = r.unwrap_or_else(|| \"any\"); }\n}\n";
6208        assert_eq!(
6209            emit_silent_fallbacks_violations(&files_of(&[("a.rs", src)])),
6210            1
6211        );
6212    }
6213
6214    #[test]
6215    fn emit_print_calls_counts_calls_and_paths_outside_tests_and_comments() {
6216        let count = |src: &str| emit_print_calls_violations(&files_of(&[("a.rs", src)]));
6217        // A call of each of the three printers, and one as a path, each on its own line.
6218        let src = "fn f() {\n\
6219                   \x20   let a = bynk_ts::print_expr(&e);\n\
6220                   \x20   let b = bynk_ts::print_stmt(&s, 0);\n\
6221                   \x20   let c = print_type(&t);\n\
6222                   \x20   let d = ts.iter().map(bynk_ts::print_type).collect();\n\
6223                   }\n";
6224        assert_eq!(count(src), 4);
6225        // Two calls on one line count once; another function's name does not match.
6226        assert_eq!(count("let a = print_expr(&x) + print_expr(&y);\n"), 1);
6227        assert_eq!(count("let a = bynk_ts::print_stmt_with_spans(&s, 0);\n"), 0);
6228        // A rename of the import and a path passed before the last argument count.
6229        assert_eq!(count("use bynk_ts::print_expr as pe;\n"), 1);
6230        assert_eq!(count("let a = apply(print_type, &t);\n"), 1);
6231        assert_eq!(count("let a = my_print_expr(&x);\n"), 0);
6232        // Comments and `#[cfg(test)]` modules do not count.
6233        assert_eq!(count("// print_expr(&x)\nfn f() {}\n"), 0);
6234        assert_eq!(
6235            count("fn p() {}\n\n#[cfg(test)]\nmod tests {\n    fn t() { print_expr(&x); }\n}\n"),
6236            0
6237        );
6238    }
6239
6240    #[test]
6241    fn emit_thread_locals_excludes_cfg_test_modules() {
6242        let src = "#[cfg(test)]\nmod tests {\n    thread_local! {\n        static A: u8 = 0;\n    }\n}\n\
6243                   thread_local! {\n    static B: u8 = 0;\n}\n";
6244        assert_eq!(
6245            emit_thread_locals_violations(&files_of(&[("a.rs", src)])),
6246            1
6247        );
6248    }
6249
6250    #[test]
6251    fn ts_text_idents_counts_both_forms_and_documents_the_multiline_gap() {
6252        let qualified = "fn f() { let a = TsExpr::Ident(format!(\"{x}.y\")); }\n";
6253        let bare = "use TsExpr::Ident;\nfn f() { let a = Ident(format!(\"{x}\")); }\n";
6254        let multiline =
6255            "fn f() {\n    let a = TsExpr::Ident(\n        format!(\"{x}\"),\n    );\n}\n";
6256        let comment = "// TsExpr::Ident(format!(\"x\"))\nfn f() {}\n";
6257        let longer = "fn f() { let a = NotIdent(format!(\"x\")); }\n";
6258        let tests = "fn p() {}\n\n#[cfg(test)]\nmod tests {\n    \
6259                     fn t() { TsExpr::Ident(format!(\"x\")); }\n}\n";
6260        let count = |src: &str| ts_text_idents_violations(&files_of(&[("a.rs", src)]));
6261        assert_eq!(count(qualified), 1);
6262        assert_eq!(count(bare), 1);
6263        assert_eq!(count(multiline), 0, "documented multi-line gap");
6264        assert_eq!(count(comment), 0);
6265        assert_eq!(count(longer), 0);
6266        assert_eq!(count(tests), 0);
6267    }
6268
6269    const STAMP_TABLE: &str = "| Probe | Gated | Reads |\n|---|---|---|\n\
6270                               | `ts_writes` | yes | 850 |\n\
6271                               | `ts_any` | yes | 26 |\n";
6272
6273    #[test]
6274    fn stamp_refresh_rewrites_named_moves() {
6275        let ack: BTreeSet<String> = ["ts_writes".to_string()].into();
6276        let out = refresh_for_stamp(
6277            STAMP_TABLE,
6278            &[gated("ts_writes", "851"), gated("ts_any", "26")],
6279            &ack,
6280        )
6281        .unwrap();
6282        assert!(out.contains("| `ts_writes` | yes | 851 |"));
6283        assert!(out.contains("| `ts_any` | yes | 26 |"));
6284    }
6285
6286    #[test]
6287    fn stamp_refresh_refuses_an_unnamed_move() {
6288        let ack: BTreeSet<String> = ["ts_writes".to_string()].into();
6289        let err = refresh_for_stamp(
6290            STAMP_TABLE,
6291            &[gated("ts_writes", "851"), gated("ts_any", "27")],
6292            &ack,
6293        )
6294        .unwrap_err();
6295        assert!(err.contains("ts_any"), "{err}");
6296        assert!(!err.contains("ts_writes"), "{err}");
6297    }
6298
6299    #[test]
6300    fn refresh_errors_on_a_missing_gated_row() {
6301        let err = refresh_gated_rows("| Probe | Gated | Reads |\n", &[gated("ts_any", "26")])
6302            .unwrap_err();
6303        assert!(err.contains("ts_any"));
6304    }
6305
6306    fn trend(name: &'static str, reads: &str) -> Probe {
6307        Probe {
6308            name,
6309            gated: false,
6310            reads: reads.to_string(),
6311        }
6312    }
6313
6314    #[test]
6315    fn refresh_trend_rewrites_trend_rows_and_leaves_the_rest() {
6316        let committed = "# Greenfield status\n\n| Probe | Gated | Reads |\n|---|---|---|\n\
6317                         | `ts_writes` | yes | 850 |\n\
6318                         | `wildcard_arms` | no (trend) | 355 |\n\nfooter\n";
6319        let out = refresh_trend_rows(committed, &[trend("wildcard_arms", "747")]).unwrap();
6320        assert!(out.contains("| `wildcard_arms` | no (trend) | 747 |\n"));
6321        assert!(out.contains("| `ts_writes` | yes | 850 |\n"));
6322        assert!(out.ends_with("\nfooter\n"));
6323        assert_eq!(out.lines().count(), committed.lines().count());
6324    }
6325
6326    #[test]
6327    fn refresh_trend_ignores_gated_probes_and_is_idempotent() {
6328        let committed = "| `ts_writes` | yes | 850 |\n| `wildcard_arms` | no (trend) | 747 |\n";
6329        let probes = [gated("ts_writes", "999"), trend("wildcard_arms", "747")];
6330        assert_eq!(refresh_trend_rows(committed, &probes).unwrap(), committed);
6331    }
6332
6333    #[test]
6334    fn refresh_trend_errors_on_a_missing_trend_row() {
6335        let err = refresh_trend_rows(
6336            "| Probe | Gated | Reads |\n",
6337            &[trend("wildcard_arms", "747")],
6338        )
6339        .unwrap_err();
6340        assert!(err.contains("wildcard_arms"));
6341    }
6342
6343    #[test]
6344    fn refresh_trend_refuses_a_failed_probe_reading() {
6345        let committed = "| `wildcard_arms` | no (trend) | 747 |\n";
6346        let err = refresh_trend_rows(
6347            committed,
6348            &[trend("wildcard_arms", "error running clippy: boom")],
6349        )
6350        .unwrap_err();
6351        assert!(err.contains("error running clippy"), "{err}");
6352    }
6353
6354    // --- emit_diagnostics (#999 Decision A) ---------------------------------
6355
6356    /// A standalone `"bynk.foo"` literal is found — the ordinary case.
6357    #[test]
6358    fn bynk_dotted_literals_finds_standalone_literal() {
6359        let src = r#"code("bynk.check.something", "a message")"#;
6360        assert_eq!(bynk_dotted_literals(src), vec!["bynk.check.something"]);
6361    }
6362
6363    /// The bug this slice found in its own first draft: a longer message that merely
6364    /// *starts* with "bynk." must not be truncated into a fake code literal. Regression
6365    /// test for `bynk.map itself uses bynk.list, so list must be injected too: {paths:?}`
6366    /// (`bynk-emit/src/project.rs`), which an earlier, less careful version of this scan
6367    /// wrongly counted as the literal `"bynk.map"`.
6368    #[test]
6369    fn bynk_dotted_literals_ignores_prefix_of_a_longer_message() {
6370        let src = r#"assert!(cond, "bynk.map itself uses bynk.list, so list must be injected too: {paths:?}");"#;
6371        assert!(bynk_dotted_literals(src).is_empty());
6372    }
6373
6374    /// Regression test for the other half of the same bug: a `\`-continued string
6375    /// literal (`"bynk.emit.unresolved_cross_context_signature: no signature for \`,
6376    /// continued on the next source line) is one string, not a diagnostic-code literal,
6377    /// even though its first segment matches the identifier charset — because the
6378    /// character after the run is `:`, never a closing quote, on either line.
6379    #[test]
6380    fn bynk_dotted_literals_ignores_a_line_continued_message() {
6381        let src =
6382            "\"bynk.emit.unresolved_cross_context_signature: no signature for \\\n     the rest\"";
6383        assert!(bynk_dotted_literals(src).is_empty());
6384    }
6385
6386    /// The whole point of Decision A: cross-referencing the real registry, not a
6387    /// hand-maintained exclusion list, correctly separates a real diagnostic code from
6388    /// a commons/namespace path that merely looks like one.
6389    #[test]
6390    fn emit_diagnostics_cross_references_the_real_registry() {
6391        let registry: BTreeSet<&str> = bynk_syntax::diagnostics::REGISTRY
6392            .iter()
6393            .map(|d| d.code)
6394            .collect();
6395        // A code this registry is known to carry (bynk-syntax/src/diagnostics.rs).
6396        assert!(registry.contains("bynk.parse.expected_expression"));
6397        // A commons/namespace path, not a diagnostic code — #999's own verified survey.
6398        assert!(!registry.contains("bynk.locale"));
6399    }
6400
6401    // --- ast_importers (#1176) ------------------------------------------------
6402
6403    /// The exclusion is named, not prefixed: `project/tests_emit.rs` is the
6404    /// Q7-settled `Ir → String` half that keeps hand-writing TypeScript by calling
6405    /// straight into `emitter.rs`'s own body-rendering, and
6406    /// keeps reading a handler's declared param/return `TypeRef` with no `TyId`
6407    /// available at that call site — but `project.rs` (which also imports
6408    /// `bynk_syntax::ast`, via `EmitProjectCtx`) must stay counted, and so, per
6409    /// review of #1210, must `emitter.rs`/`emitter/lower.rs` themselves: both still
6410    /// hold live AST-*declaration* reads (`emitter.rs`'s `CommonsItem::Service`/
6411    /// `svc.protocol` walk, `emitter/lower.rs`'s `cap_op_param_names`) that are the
6412    /// still-open R6.13 defect this probe tracks, not the Q7 kind — excluding either
6413    /// file would hide that real work the same way a path-prefix rule would. A
6414    /// path-prefix rule (e.g. "only `emitter/**` counts") would have excluded
6415    /// `project.rs` right along with the legitimate ones, silently undercounting
6416    /// real work. (`ir.rs`/`ir/lower.rs`, the lowering pass's own former `Ast → Ir`
6417    /// exclusion, left this list at Arc D's P7.12 crate carve — they left
6418    /// `bynk-emit/src` entirely, not merely this list.)
6419    #[test]
6420    fn ast_importer_exclusion_is_named_not_prefixed() {
6421        // `project/tests_emit.rs` left `bynk-emit/src` with `project` (D1, #2982).
6422        assert!(!is_named_ast_importer(Path::new("project/tests_emit.rs")));
6423        assert!(is_named_ast_importer(Path::new("emitter/serialisation.rs")));
6424        // A file split out of it is excluded through the origin table; a file that is not in
6425        // the table is not, whatever directory it sits in.
6426        assert!(is_named_ast_importer(Path::new(
6427            "emitter/serialisation/expr.rs"
6428        )));
6429        assert!(is_named_ast_importer(Path::new(
6430            "emitter/serialisation/field.rs"
6431        )));
6432        assert!(!is_named_ast_importer(Path::new(
6433            "emitter/serialisation/other.rs"
6434        )));
6435        assert!(!is_named_ast_importer(Path::new("project.rs")));
6436        assert!(!is_named_ast_importer(Path::new("emitter.rs")));
6437        assert!(!is_named_ast_importer(Path::new("emitter/lower.rs")));
6438        assert!(!is_named_ast_importer(Path::new("emitter/workers.rs")));
6439        assert!(!is_named_ast_importer(Path::new("ir.rs")));
6440        assert!(!is_named_ast_importer(Path::new("ir/lower.rs")));
6441    }
6442
6443    /// #1184 review: an `AST_IMPORTER_EXCEPTIONS` entry going stale (renamed or split,
6444    /// e.g. `ir/lower.rs` becoming `ir/lower/mod.rs`) must fail loud here, not surface
6445    /// as a silent `ast_importers` regression in `greenfield_status_table_is_current` —
6446    /// mirrors [`file_is_named_fs_floor`]'s own "fail loud, not quiet" discipline.
6447    #[test]
6448    fn ast_importer_exceptions_still_exist_and_still_import_the_ast() {
6449        let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
6450            .join("..")
6451            .join("bynk-emit/src");
6452        for rel in AST_IMPORTER_EXCEPTIONS {
6453            let contents = std::fs::read_to_string(dir.join(rel)).unwrap_or_else(|e| {
6454                panic!("AST_IMPORTER_EXCEPTIONS entry {rel:?} does not exist: {e}")
6455            });
6456            assert!(
6457                contents.contains("bynk_syntax::ast"),
6458                "AST_IMPORTER_EXCEPTIONS entry {rel:?} no longer imports bynk_syntax::ast \
6459                 — it excludes nothing and should be removed"
6460            );
6461        }
6462    }
6463
6464    /// #1184 review, extended by #1187's own closing scoping pass (and narrowed by
6465    /// review of #1210, which found `emitter.rs`/`emitter/lower.rs` still hold live,
6466    /// in-scope AST-declaration reads and must stay counted) and by P6.33's own
6467    /// re-settling (`emitter/serialisation.rs`, a phase boundary rather than a
6468    /// declaration-read exemption): exercises the real filter over the live tree, not
6469    /// just the pure predicate — the survivor set the PR's own named-vs-prefix
6470    /// argument depends on: the named exclusions drop out
6471    /// (`project/tests_emit.rs`'s Q7-settled `Ir → String` case and
6472    /// `emitter/serialisation.rs`'s phase-7 codec renderer), while `emitter.rs`/
6473    /// `emitter/lower.rs`/`emitter/workers.rs` do not. `ir.rs`/`ir/lower.rs` (the
6474    /// lowering pass's own former `Ast → Ir` pair, excluded here until Arc D's
6475    /// P7.12 crate carve) are asserted absent below for a different reason now:
6476    /// they left `bynk-emit/src` entirely, so `ast_importer_files` never walks
6477    /// them at all, named exclusion or not.
6478    ///
6479    /// P6.49 (phase 6's own §6b): `project.rs` and `project/diagnostics.rs`
6480    /// join the *excluded* side of this assertion — the opposite of what this test
6481    /// checked before. `project.rs` cleared without joining
6482    /// [`AST_IMPORTER_EXCEPTIONS`]: nine slices (P6.42–P6.49) either relocated its
6483    /// remaining declaration reads to the `bynk-check`/`bynk-project` crates that
6484    /// already own the data, or re-exported a type from a `bynk-check` module whose
6485    /// own public API was already parameterised by it (the P6.27 `ExprId` precedent,
6486    /// applied to `TypeDecl`/`FnDecl`/`Visibility`/`ActorDecl`) — real, verified
6487    /// movement, not a probe exemption. `project/diagnostics.rs` rides on it, per the
6488    /// same super-glob rule this file's own regression guard below pins.
6489    #[test]
6490    fn ast_importers_excludes_the_named_pairs_and_project_rs() {
6491        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
6492        let dir = root.join("bynk-emit/src");
6493        let counted: BTreeSet<String> = ast_importer_files(&root)
6494            .into_iter()
6495            .map(|path| {
6496                path.strip_prefix(&dir)
6497                    .unwrap_or(&path)
6498                    .to_string_lossy()
6499                    .replace('\\', "/")
6500            })
6501            .collect();
6502        assert!(!counted.contains("ir.rs"), "moved to bynk-ir at P7.12");
6503        assert!(
6504            !counted.contains("ir/lower.rs"),
6505            "moved to bynk-lower at P7.12"
6506        );
6507        assert!(!counted.contains("project/tests_emit.rs"));
6508        assert!(!counted.contains("emitter/serialisation.rs"));
6509        assert!(!counted.contains("emitter/serialisation/expr.rs"));
6510        assert!(!counted.contains("emitter/serialisation/field.rs"));
6511        assert!(!counted.contains("project.rs"));
6512        assert!(!counted.contains("project/diagnostics.rs"));
6513        assert!(counted.contains("emitter.rs"));
6514        assert!(counted.contains("emitter/lower.rs"));
6515        assert!(counted.contains("emitter/workers.rs"));
6516    }
6517
6518    /// P6.26 review (#1259): a module-level `use super::*;` is a real inheritance
6519    /// channel (Rust's own privacy rule makes a parent's private `use` visible to
6520    /// descendants) — must be detected — but a `use super::*;` nested inside a
6521    /// `#[cfg(test)] mod tests { .. }` block glob-imports its own *immediately
6522    /// enclosing* module, not the grandparent file on disk, and must not
6523    /// false-positive.
6524    #[test]
6525    fn module_level_super_glob_detection_ignores_nested_test_mod() {
6526        assert!(has_module_level_super_glob(
6527            "use std::fmt;\nuse super::*;\n"
6528        ));
6529        assert!(!has_module_level_super_glob(
6530            "fn f() {}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n}\n"
6531        ));
6532    }
6533
6534    /// P6.26 review (#1259): pins the real scenario the review found —
6535    /// `emitter/emit.rs` and `emitter/lower.rs` both carry a live, module-level
6536    /// `use super::*;` inheriting from `emitter.rs`, which itself still imports
6537    /// `bynk_syntax::ast` directly. Regression guard: if a future slice deletes
6538    /// either child's own explicit AST import while this inheritance channel and
6539    /// the parent's own AST dependency both remain, [`ast_importer_files`] must
6540    /// keep counting it rather than silently dropping the probe.
6541    #[test]
6542    fn super_glob_children_of_an_ast_importing_parent_are_detected() {
6543        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
6544        let dir = root.join("bynk-emit/src");
6545        for rel in ["emitter/emit.rs", "emitter/lower.rs"] {
6546            let contents = std::fs::read_to_string(dir.join(rel))
6547                .unwrap_or_else(|e| panic!("{rel:?} does not exist: {e}"));
6548            assert!(
6549                has_module_level_super_glob(&contents),
6550                "{rel:?} no longer carries a module-level `use super::*;` — this \
6551                 regression guard (and the false-zero hazard it pins) no longer applies \
6552                 and may be deleted"
6553            );
6554            assert_eq!(
6555                super_glob_parent_imports_ast(&dir, Path::new(rel)),
6556                Some(true),
6557                "{rel:?}'s parent (`emitter.rs`) no longer imports bynk_syntax::ast — \
6558                 update this guard's expectation"
6559            );
6560        }
6561        // A file directly under `bynk-emit/src` (no directory component) has no
6562        // `use super::*;` parent to inherit from.
6563        assert_eq!(
6564            super_glob_parent_imports_ast(&dir, Path::new("emitter.rs")),
6565            None
6566        );
6567    }
6568
6569    // --- fs_below_driver / test_density (trailing `#[cfg(test)] mod tests {}`) ---
6570
6571    #[test]
6572    fn production_std_fs_usage_is_detected() {
6573        let src = "fn load(p: &Path) -> String {\n    std::fs::read_to_string(p).unwrap()\n}\n";
6574        assert!(has_production_std_fs(src));
6575    }
6576
6577    #[test]
6578    fn std_fs_inside_a_trailing_test_mod_is_not_production() {
6579        let src = "fn load(p: &Path) -> String {\n    String::new()\n}\n\n#[cfg(test)]\nmod tests {\n    #[test]\n    fn t() {\n        std::fs::write(\"x\", \"y\").unwrap();\n    }\n}\n";
6580        assert!(!has_production_std_fs(src));
6581    }
6582
6583    /// Regression test for the other real bug this slice found: `bynk-emit/src/lib.rs`
6584    /// has `#[cfg(test)] pub(crate) mod testkit;` — an external-file module
6585    /// *declaration* (ends in `;`), not an inline block. It must not be mistaken for a
6586    /// scope-opening `mod tests { ... }`, or the (genuinely production) code after it in
6587    /// the same file would be wrongly excluded.
6588    #[test]
6589    fn cfg_test_external_mod_declaration_does_not_open_a_test_region() {
6590        let src = "#[cfg(test)]\npub(crate) mod testkit;\n\nfn load(p: &Path) -> String {\n    std::fs::read_to_string(p).unwrap()\n}\n";
6591        assert!(has_production_std_fs(src));
6592    }
6593
6594    // --- unconsumed_ir_items (Slice D3 of #1542) ----------------------------
6595
6596    fn files(entries: &[(&str, &str, &str)]) -> Vec<(String, PathBuf, String)> {
6597        entries
6598            .iter()
6599            .map(|(k, p, c)| (k.to_string(), PathBuf::from(p), c.to_string()))
6600            .collect()
6601    }
6602
6603    /// The ordinary case: a `pub` item read from another crate's production
6604    /// code is consumed; one read from nowhere is not.
6605    #[test]
6606    fn unconsumed_pub_items_reports_only_items_with_no_other_crate_reader() {
6607        let owners = files(&[(
6608            "bynk-ir",
6609            "lib.rs",
6610            "pub struct Used;\npub struct Unused;\npub fn helper() {}\n",
6611        )]);
6612        let consumers = files(&[
6613            (
6614                "bynk-ir",
6615                "lib.rs",
6616                "pub struct Used;\npub struct Unused;\npub fn helper() {}\n",
6617            ),
6618            (
6619                "bynk-emit",
6620                "a.rs",
6621                "fn f(x: bynk_model::Used) { helper(); }\n",
6622            ),
6623        ]);
6624        assert_eq!(
6625            unconsumed_pub_items(&["bynk-ir"], &owners, &consumers),
6626            vec!["bynk-ir::Unused"]
6627        );
6628    }
6629
6630    /// A mention in a comment, inside a `#[cfg(test)]` module, or in the
6631    /// owning crate itself is not a consumer.
6632    #[test]
6633    fn unconsumed_pub_items_ignores_comments_tests_and_the_owning_crate() {
6634        let owners = files(&[(
6635            "bynk-lower",
6636            "lib.rs",
6637            "pub fn lower_x() {}\npub fn lower_y() {}\npub fn lower_z() {}\n",
6638        )]);
6639        let consumers = files(&[
6640            (
6641                "bynk-lower",
6642                "lib.rs",
6643                "pub fn lower_x() {}\nfn own() { lower_x(); }\n",
6644            ),
6645            (
6646                "bynk-emit",
6647                "a.rs",
6648                "// lower_y() used to be called here\n/// and [`lower_y`] linked here\n",
6649            ),
6650            (
6651                "bynk-emit",
6652                "b.rs",
6653                "fn prod() {}\n\n#[cfg(test)]\nmod tests {\n    fn t() { lower_z(); }\n}\n",
6654            ),
6655        ]);
6656        assert_eq!(
6657            unconsumed_pub_items(&["bynk-lower"], &owners, &consumers),
6658            vec![
6659                "bynk-lower::lower_x",
6660                "bynk-lower::lower_y",
6661                "bynk-lower::lower_z"
6662            ]
6663        );
6664    }
6665
6666    /// Whole-word matching: `IrExpr` inside `IrExprKind` is not a read of
6667    /// `IrExpr`, and `pub(crate)`/indented items are not offered to other
6668    /// crates so are never counted either way.
6669    #[test]
6670    fn unconsumed_pub_items_matches_whole_words_and_skips_non_public_items() {
6671        let owners = files(&[(
6672            "bynk-ir",
6673            "lib.rs",
6674            "pub struct IrExpr;\npub enum IrExprKind {}\npub(crate) fn internal() {}\nimpl IrExpr {\n    pub fn method() {}\n}\n",
6675        )]);
6676        let consumers = files(&[("bynk-emit", "a.rs", "fn f(k: IrExprKind) {}\n")]);
6677        assert_eq!(
6678            unconsumed_pub_items(&["bynk-ir"], &owners, &consumers),
6679            vec!["bynk-ir::IrExpr"]
6680        );
6681    }
6682
6683    /// The two IR crates do not vouch for each other (review of #1581): a
6684    /// `bynk-ir` type read only from `bynk-lower` is unconsumed, and so is a
6685    /// `bynk-lower` helper read only from `bynk-ir` — pre-D0 `main`'s exact
6686    /// shape, where `bynk-lower`'s own unconsumed constructors named every
6687    /// unconsumed `bynk-ir` type.
6688    #[test]
6689    fn unconsumed_pub_items_does_not_let_owner_crates_vouch_for_each_other() {
6690        let owners = files(&[
6691            (
6692                "bynk-ir",
6693                "lib.rs",
6694                "pub struct IrExpr;\npub struct Shape;\n",
6695            ),
6696            (
6697                "bynk-lower",
6698                "lib.rs",
6699                "pub fn lower_expr_ir() -> IrExpr { IrExpr }\npub fn shape() -> Shape { Shape }\n",
6700            ),
6701        ]);
6702        let consumers = files(&[
6703            (
6704                "bynk-ir",
6705                "lib.rs",
6706                "pub struct IrExpr;\npub struct Shape;\n",
6707            ),
6708            (
6709                "bynk-lower",
6710                "lib.rs",
6711                "pub fn lower_expr_ir() -> IrExpr { IrExpr }\npub fn shape() -> Shape { Shape }\n",
6712            ),
6713            (
6714                "bynk-emit",
6715                "a.rs",
6716                "fn f() -> Shape { bynk_model::shape() }\n",
6717            ),
6718        ]);
6719        assert_eq!(
6720            unconsumed_pub_items(&["bynk-ir", "bynk-lower"], &owners, &consumers),
6721            vec!["bynk-ir::IrExpr", "bynk-lower::lower_expr_ir"]
6722        );
6723    }
6724
6725    /// Crate-hygiene B1 (#2939), M-3: `bynk-emit`'s reads don't count toward
6726    /// `model_readers_beyond_emit`, a reader in any other crate does, and the
6727    /// reading's count parses back for the floor test.
6728    #[test]
6729    fn model_readers_beyond_emit_counts_only_readers_past_the_emitter() {
6730        let owners = files(&[
6731            (
6732                "bynk-ir",
6733                "lib.rs",
6734                "pub enum Kind { A }\npub struct Shape;\n",
6735            ),
6736            (
6737                "bynk-lower",
6738                "lib.rs",
6739                "pub fn lower_kind() -> Kind { Kind::A }\n",
6740            ),
6741        ]);
6742        let consumers = files(&[
6743            (
6744                "bynk-lower",
6745                "lib.rs",
6746                "pub fn lower_kind() -> Kind { Kind::A }\n",
6747            ),
6748            (
6749                "bynk-emit",
6750                "a.rs",
6751                "fn f(s: Shape) -> Kind { bynk_model::lower_kind() }\n",
6752            ),
6753            (
6754                "bynk-ide",
6755                "b.rs",
6756                "// Shape is mentioned only in a comment\nfn g() -> bynk_model::Kind { bynk_model::lower_kind() }\n",
6757            ),
6758        ]);
6759        let excluded = ["bynk-ir", "bynk-lower", "bynk-emit"];
6760        let (read, unread) =
6761            pub_items_by_readership(&["bynk-ir", "bynk-lower"], &excluded, &owners, &consumers);
6762        assert_eq!(read, vec!["bynk-ir::Kind", "bynk-lower::lower_kind"]);
6763        assert_eq!(unread, vec!["bynk-ir::Shape"]);
6764        let reading = model_readers_reading(&read);
6765        assert_eq!(reading, "2 (bynk-ir::Kind, bynk-lower::lower_kind)");
6766        assert_eq!(model_readers_count(&reading), Some(2));
6767        assert_eq!(model_readers_count("0"), Some(0));
6768    }
6769
6770    /// Review of #2954: the production shape since B1 (3b). One owner crate,
6771    /// `bynk-model`, holds both the vocabulary and the builder as modules. An
6772    /// item read only by the same crate's `lower.rs` is still unconsumed, and an
6773    /// item read only by `bynk-emit` is consumed but not read beyond the emitter.
6774    #[test]
6775    fn a_single_owner_with_two_modules_does_not_vouch_for_itself() {
6776        let owners = files(&[
6777            (
6778                "bynk-model",
6779                "vocabulary.rs",
6780                "pub struct IrExpr;\npub struct Shape;\npub enum IrHandlerKind {}\n",
6781            ),
6782            (
6783                "bynk-model",
6784                "lower.rs",
6785                "pub fn lower_expr_ir() -> IrExpr { IrExpr }\n",
6786            ),
6787        ]);
6788        let mut consumers = owners.clone();
6789        consumers.extend(files(&[
6790            (
6791                "bynk-emit",
6792                "a.rs",
6793                "fn f(s: Shape) { bynk_model::lower_expr_ir(); }\n",
6794            ),
6795            ("bynk-ide", "b.rs", "fn g(k: IrHandlerKind) {}\n"),
6796        ]));
6797        assert_eq!(
6798            unconsumed_pub_items(&["bynk-model"], &owners, &consumers),
6799            vec!["bynk-model::IrExpr"]
6800        );
6801        let (read, unread) = pub_items_by_readership(
6802            &["bynk-model"],
6803            &["bynk-model", "bynk-emit"],
6804            &owners,
6805            &consumers,
6806        );
6807        assert_eq!(read, vec!["bynk-model::IrHandlerKind"]);
6808        assert_eq!(
6809            unread,
6810            vec![
6811                "bynk-model::IrExpr",
6812                "bynk-model::Shape",
6813                "bynk-model::lower_expr_ir"
6814            ]
6815        );
6816    }
6817
6818    /// One item declared in two files of the same crate (a split module) is
6819    /// reported once, not twice.
6820    #[test]
6821    fn unconsumed_pub_items_deduplicates_a_name_declared_in_two_files() {
6822        let owners = files(&[
6823            ("bynk-lower", "a.rs", "pub fn twice() {}\n"),
6824            ("bynk-lower", "b.rs", "pub fn twice() {}\n"),
6825        ]);
6826        assert_eq!(
6827            unconsumed_pub_items(&["bynk-lower"], &owners, &[]),
6828            vec!["bynk-lower::twice"]
6829        );
6830    }
6831
6832    #[test]
6833    fn column_zero_pub_item_name_accepts_every_item_kind_and_fn_qualifier() {
6834        assert_eq!(column_zero_pub_item_name("pub fn f(x: i32) {}"), Some("f"));
6835        assert_eq!(column_zero_pub_item_name("pub struct S<'a> {"), Some("S"));
6836        assert_eq!(column_zero_pub_item_name("pub enum E {"), Some("E"));
6837        assert_eq!(
6838            column_zero_pub_item_name("pub type T = (u8, u8);"),
6839            Some("T")
6840        );
6841        assert_eq!(
6842            column_zero_pub_item_name("pub const C: &[&str] = &[];"),
6843            Some("C")
6844        );
6845        assert_eq!(
6846            column_zero_pub_item_name("pub static S: &[&str] = &[];"),
6847            Some("S")
6848        );
6849        assert_eq!(column_zero_pub_item_name("pub trait Tr {}"), Some("Tr"));
6850        assert_eq!(column_zero_pub_item_name("pub union U {"), Some("U"));
6851        // `fn` qualifiers, alone and stacked (review of #1581).
6852        assert_eq!(column_zero_pub_item_name("pub async fn a() {}"), Some("a"));
6853        assert_eq!(column_zero_pub_item_name("pub unsafe fn u() {}"), Some("u"));
6854        assert_eq!(column_zero_pub_item_name("pub const fn c() {}"), Some("c"));
6855        assert_eq!(
6856            column_zero_pub_item_name("pub extern \"C\" fn x() {}"),
6857            Some("x")
6858        );
6859        assert_eq!(
6860            column_zero_pub_item_name("pub const unsafe fn cu() {}"),
6861            Some("cu")
6862        );
6863        assert_eq!(
6864            column_zero_pub_item_name("pub unsafe extern \"C\" fn ue() {}"),
6865            Some("ue")
6866        );
6867        assert_eq!(
6868            column_zero_pub_item_name("pub async unsafe fn au() {}"),
6869            Some("au")
6870        );
6871        // Not items offered to another crate.
6872        assert_eq!(column_zero_pub_item_name("pub(crate) fn g() {}"), None);
6873        assert_eq!(column_zero_pub_item_name("pub(super) struct P;"), None);
6874        assert_eq!(column_zero_pub_item_name("    pub fn method() {}"), None);
6875        assert_eq!(column_zero_pub_item_name("pub use foo::Bar;"), None);
6876        assert_eq!(column_zero_pub_item_name("pub mod m;"), None);
6877        assert_eq!(column_zero_pub_item_name("pub impl Foo {}"), None);
6878    }
6879
6880    /// [`workspace_crate_src_files`] tags each file with its crate directory
6881    /// and only walks directories that are actually crates (a `Cargo.toml`
6882    /// *and* a `src/`), so a stray directory with one but not the other is
6883    /// neither an owner nor a consumer.
6884    #[test]
6885    fn workspace_crate_src_files_tags_files_by_crate_and_skips_non_crates() {
6886        let root = std::env::temp_dir().join(format!(
6887            "bynk-xtask-unconsumed-{}-{}",
6888            std::process::id(),
6889            std::time::SystemTime::now()
6890                .duration_since(std::time::UNIX_EPOCH)
6891                .map(|d| d.as_nanos())
6892                .unwrap_or(0)
6893        ));
6894        let mk = |rel: &str, contents: &str| {
6895            let p = root.join(rel);
6896            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
6897            std::fs::write(p, contents).unwrap();
6898        };
6899        mk("alpha/Cargo.toml", "[package]\nname = \"alpha\"\n");
6900        mk("alpha/src/lib.rs", "pub fn a() {}\n");
6901        mk("alpha/src/inner/mod.rs", "pub fn b() {}\n");
6902        mk("beta/Cargo.toml", "[package]\nname = \"beta\"\n");
6903        mk("beta/src/lib.rs", "fn c() { alpha::a() }\n");
6904        mk("no-src/Cargo.toml", "[package]\nname = \"no-src\"\n");
6905        mk("no-manifest/src/lib.rs", "pub fn d() {}\n");
6906        let files = workspace_crate_src_files(&root);
6907        let _ = std::fs::remove_dir_all(&root);
6908        let mut tagged: Vec<(String, String)> = files
6909            .iter()
6910            .map(|(k, p, _)| (k.clone(), p.to_string_lossy().replace('\\', "/")))
6911            .collect();
6912        tagged.sort();
6913        assert_eq!(
6914            tagged,
6915            vec![
6916                ("alpha".to_string(), "inner/mod.rs".to_string()),
6917                ("alpha".to_string(), "lib.rs".to_string()),
6918                ("beta".to_string(), "lib.rs".to_string()),
6919            ]
6920        );
6921    }
6922
6923    /// Regression test for the bug caught in review: a file with **two** scattered
6924    /// `#[cfg(test)] mod ... { ... }` blocks, with real production code between them —
6925    /// exactly `bynk-emit/src/emitter/lower.rs`'s shape (two test modules, 1031
6926    /// production lines apart). A single "everything from the first/last `#[cfg(test)]`
6927    /// onward" cutoff would misclassify `lower_lambda` here as test-scope; the fix must
6928    /// close each block at its own boundary and resume production scanning after it.
6929    #[test]
6930    fn production_code_between_two_scattered_test_mods_is_detected() {
6931        let src = "\
6932#[cfg(test)]
6933mod decode_map_key_tests {
6934    #[test]
6935    fn t() {
6936        assert_eq!(1, 1);
6937    }
6938}
6939
6940fn lower_lambda(p: &Path) -> String {
6941    std::fs::read_to_string(p).unwrap()
6942}
6943
6944#[cfg(test)]
6945mod idempotency_scoping_tests {
6946    #[test]
6947    fn t2() {
6948        assert_eq!(2, 2);
6949    }
6950}
6951";
6952        assert!(has_production_std_fs(src));
6953    }
6954
6955    // --- workspace_lints: opted-in crates ---------------------------------
6956
6957    fn lints_manifest(lints: &str) -> String {
6958        format!("[package]\nname = \"x\"\n\n[dependencies]\na = \"1\"\n\n{lints}")
6959    }
6960
6961    #[test]
6962    fn workspace_lints_lists_a_crate_that_opts_in() {
6963        let m = vec![(
6964            "bynk-ts".to_string(),
6965            lints_manifest("[lints]\nworkspace = true\n"),
6966        )];
6967        assert_eq!(opted_in_crates(&m), vec!["bynk-ts"]);
6968    }
6969
6970    #[test]
6971    fn workspace_lints_does_not_list_a_crate_with_its_own_lints_table() {
6972        let m = vec![
6973            (
6974                "own".to_string(),
6975                lints_manifest("[lints.clippy]\nall = \"warn\"\n"),
6976            ),
6977            (
6978                "own2".to_string(),
6979                lints_manifest("[lints]\nrust = \"warn\"\n"),
6980            ),
6981            ("none".to_string(), lints_manifest("")),
6982            (
6983                "elsewhere".to_string(),
6984                "[lints.rust]\nworkspace = true\n".to_string(),
6985            ),
6986        ];
6987        assert!(opted_in_crates(&m).is_empty());
6988    }
6989
6990    #[test]
6991    fn workspace_lints_ignores_trailing_comments() {
6992        let m = vec![
6993            (
6994                "a".to_string(),
6995                "[lints] # inherit\nworkspace = true  # from the root\n".to_string(),
6996            ),
6997            (
6998                "b".to_string(),
6999                "[lints]\n# workspace = true\nrust = \"warn\"\n".to_string(),
7000            ),
7001        ];
7002        assert_eq!(opted_in_crates(&m), vec!["a"]);
7003    }
7004
7005    #[test]
7006    fn workspace_lints_accepts_the_dotted_top_level_form() {
7007        let m = vec![
7008            (
7009                "dotted".to_string(),
7010                "lints.workspace = true\n\n[package]\nname = \"x\"\n".to_string(),
7011            ),
7012            // Under another table the dotted key belongs to that table.
7013            (
7014                "nested".to_string(),
7015                "[package]\nlints.workspace = true\n".to_string(),
7016            ),
7017        ];
7018        assert_eq!(opted_in_crates(&m), vec!["dotted"]);
7019    }
7020
7021    #[test]
7022    fn workspace_lints_opted_in_list_is_sorted() {
7023        let on = lints_manifest("[lints]\nworkspace = true\n");
7024        let m = vec![
7025            ("bynk-ts".to_string(), on.clone()),
7026            ("bynk-model".to_string(), on.clone()),
7027            ("bynk-emit".to_string(), lints_manifest("")),
7028            ("a-first".to_string(), on),
7029        ];
7030        assert_eq!(
7031            opted_in_crates(&m),
7032            vec!["a-first", "bynk-model", "bynk-ts"]
7033        );
7034    }
7035
7036    #[test]
7037    fn workspace_lints_reading_comes_from_real_manifests() {
7038        let root = std::env::temp_dir().join(format!("xtask-ws-lints-{}", std::process::id()));
7039        let _ = std::fs::remove_dir_all(&root);
7040        std::fs::create_dir_all(&root).unwrap();
7041        std::fs::write(
7042            root.join("Cargo.toml"),
7043            "[workspace.lints.clippy]\nwildcard_enum_match_arm = \"warn\"\n",
7044        )
7045        .unwrap();
7046        for (name, lints) in [
7047            ("zeta", "[lints]\nworkspace = true\n"),
7048            ("alpha", "[lints]\nworkspace = true\n"),
7049            ("plain", ""),
7050        ] {
7051            std::fs::create_dir_all(root.join(name).join("src")).unwrap();
7052            std::fs::write(root.join(name).join("Cargo.toml"), lints_manifest(lints)).unwrap();
7053        }
7054        let reads = workspace_lints(&root).reads;
7055        let _ = std::fs::remove_dir_all(&root);
7056        assert_eq!(
7057            reads,
7058            "present — wildcard_enum_match_arm = \"warn\"; opted in: alpha, zeta"
7059        );
7060    }
7061
7062    #[test]
7063    fn ast_importer_origins_count_each_origin_once() {
7064        let rels: Vec<String> = [
7065            "emitter/a.rs",
7066            "emitter/a/x.rs",
7067            "emitter/a/y.rs",
7068            "emitter/b.rs",
7069        ]
7070        .map(String::from)
7071        .to_vec();
7072        // No table: every file counts.
7073        assert_eq!(distinct_ast_importer_origins(&rels, &[]), 4);
7074        // Two children of `emitter/a.rs` fold into it.
7075        let table = [
7076            ("emitter/a/x.rs", "emitter/a.rs"),
7077            ("emitter/a/y.rs", "emitter/a.rs"),
7078        ];
7079        assert_eq!(distinct_ast_importer_origins(&rels, &table), 2);
7080        // A row for a file that is not an importer is inert.
7081        assert_eq!(
7082            distinct_ast_importer_origins(&rels[..1], &[("emitter/z.rs", "emitter/a.rs")]),
7083            1
7084        );
7085    }
7086
7087    /// Every row of the origin table names `bynk-emit/src`
7088    /// files that exist, so a row cannot rot silently.
7089    #[test]
7090    fn ast_importer_origin_rows_name_existing_files() {
7091        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
7092        for (child, origin) in AST_IMPORTER_ORIGINS {
7093            assert!(root.join("bynk-emit/src").join(child).is_file(), "{child}");
7094            assert!(
7095                root.join("bynk-emit/src").join(origin).is_file(),
7096                "{origin}"
7097            );
7098        }
7099    }
7100
7101    // --- module_lines -----------------------------------------------------
7102
7103    fn module_lines_reading_t(files: &[(String, usize)]) -> String {
7104        module_lines_reading(files, 0)
7105    }
7106
7107    #[test]
7108    fn module_lines_threshold_counts_exactly_2000() {
7109        let at = |n| vec![("bynk-emit/src/a.rs".to_string(), n)];
7110        assert!(module_lines_reading_t(&at(2000)).starts_with("≥2000: 1 (≥3000: 0, ≥5000: 0)"));
7111        assert!(module_lines_reading_t(&at(1999)).starts_with("≥2000: 0 "));
7112        assert!(module_lines_reading_t(&at(3000)).contains("≥3000: 1"));
7113        assert!(module_lines_reading_t(&at(5000)).contains("≥5000: 1"));
7114    }
7115
7116    #[test]
7117    fn module_lines_reading_counts_back_half_files_at_the_exit_cap_and_the_ceilings() {
7118        let f = |p: &str, l| (p.to_string(), l);
7119        let files = vec![
7120            f("bynk-emit/src/a.rs", 3000),
7121            f("bynk-emit/src/b.rs", 2999),
7122            f("bynk-check/src/front.rs", 9000),
7123        ];
7124        let reading = module_lines_reading(&files, 7);
7125        assert!(
7126            reading.ends_with("back half ≥3000: 1; ceilings: 7"),
7127            "{reading}"
7128        );
7129    }
7130
7131    #[test]
7132    fn module_lines_names_the_three_largest_back_half_files_in_order() {
7133        let f = |p: &str, l| (p.to_string(), l);
7134        let files = vec![
7135            f("bynk-emit/src/small.rs", 10),
7136            f("bynk-ts/src/b.rs", 300),
7137            f("bynk-emit/src/a.rs", 500),
7138            f("bynk-driver/src/c.rs", 200),
7139            f("bynk-model/src/d.rs", 400),
7140        ];
7141        let reading = module_lines_reading(&files, 0);
7142        assert!(
7143            reading.contains(
7144                "back half: bynk-emit/src/a.rs 500, bynk-model/src/d.rs 400, bynk-ts/src/b.rs 300;"
7145            ),
7146            "{reading}"
7147        );
7148    }
7149
7150    #[test]
7151    fn module_lines_back_half_list_ignores_front_half_crates_but_largest_does_not() {
7152        let f = |p: &str, l| (p.to_string(), l);
7153        let files = vec![
7154            f("bynk-check/src/big.rs", 900),
7155            f("bynk-emit/src/a.rs", 100),
7156        ];
7157        let reading = module_lines_reading(&files, 0);
7158        assert!(
7159            reading.contains("largest: bynk-check/src/big.rs 900;"),
7160            "{reading}"
7161        );
7162        assert!(
7163            reading.contains("back half: bynk-emit/src/a.rs 100;"),
7164            "{reading}"
7165        );
7166    }
7167
7168    /// A visibility prefix on the test module does not hide it (`pub(crate) mod tests {`),
7169    /// but a `#[cfg(test)]` item that is not a module still opens no range.
7170    #[test]
7171    fn test_mod_ranges_accepts_a_visibility_prefix() {
7172        let src = "\
7173#[cfg(test)]
7174pub(crate) mod tests {
7175    fn x() {}
7176}
7177#[cfg(test)]
7178pub mod y {
7179}
7180#[cfg(test)]
7181pub(crate) fn helper() {
7182}
7183#[cfg(test)]
7184pub(in crate::a) mod z {
7185}
7186#[cfg(test)]
7187pub mod w;
7188";
7189        let lines: Vec<&str> = src.lines().collect();
7190        assert_eq!(test_mod_ranges(&lines), vec![(1, 3), (5, 6), (11, 12)]);
7191    }
7192
7193    /// The same fixture's `test_mod_ranges` shape, checked directly: two disjoint
7194    /// ranges, not one span from the first block to the last.
7195    #[test]
7196    fn test_mod_ranges_finds_each_block_separately() {
7197        let src = "\
7198#[cfg(test)]
7199mod a {
7200    fn x() {}
7201}
7202
7203fn production() {}
7204
7205#[cfg(test)]
7206mod b {
7207    fn y() {}
7208}
7209";
7210        let lines: Vec<&str> = src.lines().collect();
7211        let ranges = test_mod_ranges(&lines);
7212        assert_eq!(
7213            ranges.len(),
7214            2,
7215            "expected two disjoint test-mod ranges: {ranges:?}"
7216        );
7217        // Line 5 (0-indexed) is `fn production() {}`, between the two blocks.
7218        assert!(
7219            !in_test_range(5, &ranges),
7220            "production() must not read as test-scope"
7221        );
7222    }
7223
7224    /// Regression test for the bug in the *fix* for the above: a column-0-`}`
7225    /// shortcut (tried and reverted during review) truncates a test module the moment
7226    /// its body embeds a multi-line fixture string containing a `}` flush against the
7227    /// left margin — exactly `bynk-ide/src/sequence.rs`'s shape, whose test mod embeds
7228    /// `.bynk` source fixtures. The real brace-depth scanner must see through the
7229    /// string and find the module's *actual* closing brace, hundreds of lines later.
7230    /// Uses a raw string for the outer fixture so the embedded `"..."` doesn't need
7231    /// escaping, and locates the real end by content rather than a hand-counted index
7232    /// — a hand-counted line number is exactly the kind of easy-to-miscount detail
7233    /// this codebase's own convention (verify, don't assume) warns against.
7234    #[test]
7235    fn test_mod_ranges_is_not_fooled_by_a_column_zero_brace_inside_a_string() {
7236        let src = r#"#[cfg(test)]
7237mod tests {
7238    const FIXTURE: &str = "
7239commons app.demo {
7240}
7241";
7242
7243    fn real_end_of_module() {}
7244}
7245"#;
7246        let lines: Vec<&str> = src.lines().collect();
7247        let ranges = test_mod_ranges(&lines);
7248        assert_eq!(ranges.len(), 1, "expected exactly one range: {ranges:?}");
7249        let (_, end) = ranges[0];
7250        // `str::lines()` drops the trailing newline, so the module's real closing
7251        // brace — the fixture's last line — is at `lines.len() - 1`. The string's
7252        // embedded `}` (an earlier line) must not be mistaken for it.
7253        assert_eq!(
7254            end,
7255            lines.len() - 1,
7256            "closed too early — mistook the string's `}}` for the module's: {ranges:?}"
7257        );
7258    }
7259
7260    // --- fs_below_driver: import resolution through `use super::*;` (#1013) ---
7261
7262    /// Run [`production_std_fs_files`] over an in-memory crate layout and name the
7263    /// flagged files, so each case reads as "these files, and only these".
7264    fn flagged(files: &[(&str, &str)]) -> Vec<String> {
7265        let owned: Vec<(PathBuf, String)> = files
7266            .iter()
7267            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
7268            .collect();
7269        production_std_fs_files(&owned)
7270            .into_iter()
7271            .map(|i| files[i].0.to_string())
7272            .collect()
7273    }
7274
7275    /// The concrete #1013 instance, in miniature: `project.rs` has a module-level
7276    /// `use std::fs;` (ancestor-scoped, so visible to descendants), `discovery.rs`
7277    /// glob-imports it via `use super::*;` and calls bare `fs::read_to_string` —
7278    /// touching `std::fs` in production while never spelling it. The text scan alone
7279    /// reads only `project.rs`; the resolved probe must read both.
7280    #[test]
7281    fn bare_fs_reached_through_a_glob_imported_parent_is_flagged() {
7282        let files = [
7283            ("lib.rs", "mod project;\n"),
7284            ("project.rs", "use std::fs;\n\nmod discovery;\n"),
7285            (
7286                "project/discovery.rs",
7287                "use super::*;\n\nfn read_source(path: &std::path::Path) -> String {\n    fs::read_to_string(path).unwrap()\n}\n",
7288            ),
7289        ];
7290        assert!(
7291            !has_production_std_fs(files[2].1),
7292            "the text scan alone must miss it"
7293        );
7294        assert_eq!(flagged(&files), vec!["project.rs", "project/discovery.rs"]);
7295    }
7296
7297    /// Without `use super::*;` there is no path from the bare `fs::` to the parent's
7298    /// binding — the probe must not guess one into existence.
7299    #[test]
7300    fn bare_fs_without_a_glob_super_import_is_not_flagged() {
7301        let files = [
7302            ("lib.rs", "mod project;\n"),
7303            ("project.rs", "use std::fs;\n\nmod discovery;\n"),
7304            (
7305                "project/discovery.rs",
7306                "fn read_source(path: &std::path::Path) -> String {\n    fs::read_to_string(path).unwrap()\n}\n",
7307            ),
7308        ];
7309        assert_eq!(flagged(&files), vec!["project.rs"]);
7310    }
7311
7312    /// Glob chains re-reach ancestors transitively — grandparent binds `fs`, both
7313    /// hops glob-import `super::*` — and the `mod.rs` layout maps to the same module
7314    /// tree as the `name.rs` one. The middle file sees `fs` but never uses it, so
7315    /// only the leaf joins the (text-flagged) root.
7316    #[test]
7317    fn glob_super_resolution_is_transitive_across_mod_rs_parents() {
7318        let files = [
7319            ("lib.rs", "use std::fs;\n\nmod a;\n"),
7320            ("a/mod.rs", "use super::*;\n\nmod b;\n"),
7321            (
7322                "a/b.rs",
7323                "use super::*;\n\nfn walk() {\n    let _ = fs::read_dir(\".\");\n}\n",
7324            ),
7325        ];
7326        assert_eq!(flagged(&files), vec!["lib.rs", "a/b.rs"]);
7327    }
7328
7329    /// A break anywhere in the chain stops resolution: the middle module does not
7330    /// glob-import `super::*`, so the leaf's `use super::*;` reaches a module with no
7331    /// `fs` binding to offer.
7332    #[test]
7333    fn a_break_in_the_glob_chain_stops_resolution() {
7334        let files = [
7335            ("lib.rs", "use std::fs;\n\nmod a;\n"),
7336            ("a/mod.rs", "mod b;\n"),
7337            (
7338                "a/b.rs",
7339                "use super::*;\n\nfn walk() {\n    let _ = fs::read_dir(\".\");\n}\n",
7340            ),
7341        ];
7342        assert_eq!(flagged(&files), vec!["lib.rs"]);
7343    }
7344
7345    /// Nearest binding wins, as in Rust: the child re-binds `fs` to something that is
7346    /// not `std::fs`, so its bare `fs::` calls are that something's, not std's.
7347    #[test]
7348    fn a_local_non_std_binding_shadows_the_ancestors_std_fs() {
7349        let files = [
7350            ("lib.rs", "mod project;\n"),
7351            ("project.rs", "use std::fs;\n\nmod overlay;\nmod d;\n"),
7352            ("project/overlay.rs", "pub fn read(_p: &str) {}\n"),
7353            (
7354                "project/d.rs",
7355                "use super::*;\nuse crate::project::overlay as fs;\n\nfn f() {\n    let _ = fs::read(\"x\");\n}\n",
7356            ),
7357        ];
7358        assert_eq!(flagged(&files), vec!["project.rs"]);
7359    }
7360
7361    /// An aliased module binding resolves under its alias — the call site never
7362    /// contains the substring `fs::` at all.
7363    #[test]
7364    fn an_aliased_std_fs_binding_resolves_through_the_glob() {
7365        let files = [
7366            ("lib.rs", "mod p;\n"),
7367            ("p.rs", "use std::fs as stdfs;\n\nmod c;\n"),
7368            (
7369                "p/c.rs",
7370                "use super::*;\n\nfn f() {\n    stdfs::write(\"a\", \"b\").unwrap();\n}\n",
7371            ),
7372        ];
7373        assert_eq!(flagged(&files), vec!["p.rs", "p/c.rs"]);
7374    }
7375
7376    /// `use std::{fs, io};` binds `fs` without ever containing the substring
7377    /// `std::fs` — the same blind spot as #1013's, one file deep. Resolution applies
7378    /// in the file's own scope, no glob import required.
7379    #[test]
7380    fn a_group_imported_fs_binding_is_resolved_in_its_own_file() {
7381        let src = "use std::{fs, io};\n\nfn f() -> io::Result<()> {\n    fs::metadata(\"x\").map(|_| ())\n}\n";
7382        assert!(
7383            !has_production_std_fs(src),
7384            "the text scan alone must miss it"
7385        );
7386        let files = [("thing.rs", src)];
7387        assert_eq!(flagged(&files), vec!["thing.rs"]);
7388    }
7389
7390    /// The item-import shape #1013 scope-checked (zero current instances), at the
7391    /// granularity this probe can reach: an ancestor's `use std::fs::File;` used as a
7392    /// bare path root `File::open` in a glob-importing child resolves and flags. (A
7393    /// bare *call* of an imported fn — `read_to_string(p)`, no `::` — presents no
7394    /// path root and remains out of a text-level scanner's reach, per the doc.)
7395    #[test]
7396    fn an_item_import_under_std_fs_resolves_as_a_path_root() {
7397        let files = [
7398            ("lib.rs", "mod p;\n"),
7399            ("p.rs", "use std::fs::File;\n\nmod c;\n"),
7400            (
7401                "p/c.rs",
7402                "use super::*;\n\nfn f() {\n    let _ = File::open(\"x\");\n}\n",
7403            ),
7404        ];
7405        assert_eq!(flagged(&files), vec!["p.rs", "p/c.rs"]);
7406    }
7407
7408    /// A test module's `use super::*;` and tempdir `fs::` calls are test-scope — the
7409    /// `bynk-ide` files' shape (`architecture.rs`, `sequence.rs`), which must stay
7410    /// unflagged exactly as they were under the text-only scan.
7411    #[test]
7412    fn glob_and_bare_fs_inside_a_test_mod_stay_test_scope() {
7413        let files = [
7414            ("lib.rs", "use std::fs;\n\nmod w;\n"),
7415            (
7416                "w.rs",
7417                "fn production() {}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use std::fs;\n\n    #[test]\n    fn t() {\n        let _ = fs::read_dir(\".\");\n    }\n}\n",
7418            ),
7419        ];
7420        assert_eq!(flagged(&files), vec!["lib.rs"]);
7421    }
7422
7423    /// The module-tree mapping behind the resolution, checked directly: `name.rs` and
7424    /// `mod.rs` layouts, a preferred `a.rs` over `a/mod.rs`, and rootless roots.
7425    #[test]
7426    fn module_parent_maps_both_file_layouts() {
7427        let files: Vec<(PathBuf, String)> = ["lib.rs", "a.rs", "a/b.rs", "c/mod.rs", "c/d.rs"]
7428            .iter()
7429            .map(|p| (PathBuf::from(p), String::new()))
7430            .collect();
7431        let idx = |name: &str| {
7432            files
7433                .iter()
7434                .position(|(p, _)| p == Path::new(name))
7435                .unwrap()
7436        };
7437        assert_eq!(module_parent(Path::new("lib.rs"), &files), None);
7438        assert_eq!(
7439            module_parent(Path::new("a.rs"), &files),
7440            Some(idx("lib.rs"))
7441        );
7442        assert_eq!(
7443            module_parent(Path::new("a/b.rs"), &files),
7444            Some(idx("a.rs"))
7445        );
7446        assert_eq!(
7447            module_parent(Path::new("c/mod.rs"), &files),
7448            Some(idx("lib.rs"))
7449        );
7450        assert_eq!(
7451            module_parent(Path::new("c/d.rs"), &files),
7452            Some(idx("c/mod.rs"))
7453        );
7454    }
7455
7456    // --- fs_below_driver: #1016 review findings ------------------------------
7457
7458    /// Finding 1: a `super::`-qualified path needs no glob import — module privacy is
7459    /// ancestor-scoped, so `super::fs` names the parent's private `use std::fs;` from
7460    /// any child. One disambiguating edit away from `discovery.rs:39`'s bare call,
7461    /// and it must not drop the file out of the count.
7462    #[test]
7463    fn a_super_qualified_path_resolves_without_a_glob_import() {
7464        let files = [
7465            ("lib.rs", "mod project;\n"),
7466            ("project.rs", "use std::fs;\n\nmod discovery;\n"),
7467            (
7468                "project/discovery.rs",
7469                "fn read_source(path: &std::path::Path) -> String {\n    super::fs::read_to_string(path).unwrap()\n}\n",
7470            ),
7471        ];
7472        assert_eq!(flagged(&files), vec!["project.rs", "project/discovery.rs"]);
7473    }
7474
7475    /// Finding 1, the `crate::`-rooted form: the walk descends the module tree from
7476    /// the crate root file by file, then resolves the leaf against that module's
7477    /// bindings — from anywhere in the crate, glob import or not.
7478    #[test]
7479    fn a_crate_qualified_path_resolves_through_the_module_tree() {
7480        let files = [
7481            ("lib.rs", "mod other;\nmod project;\n"),
7482            (
7483                "other.rs",
7484                "fn f() {\n    let _ = crate::project::fs::read_dir(\".\");\n}\n",
7485            ),
7486            ("project.rs", "use std::fs;\n"),
7487        ];
7488        assert_eq!(flagged(&files), vec!["other.rs", "project.rs"]);
7489    }
7490
7491    /// Finding 1, stacked hops: `super::super::` climbs two parents (through a
7492    /// glob-free middle module — qualified paths don't need the glob chain).
7493    #[test]
7494    fn stacked_super_hops_climb_the_parent_chain() {
7495        let files = [
7496            ("lib.rs", "use std::fs;\n\nmod a;\n"),
7497            ("a/mod.rs", "mod b;\n"),
7498            (
7499                "a/b.rs",
7500                "fn f() {\n    let _ = super::super::fs::read_dir(\".\");\n}\n",
7501            ),
7502        ];
7503        assert_eq!(flagged(&files), vec!["lib.rs", "a/b.rs"]);
7504    }
7505
7506    /// Finding 1, `self::` composed with the glob chain: `self::fs` resolves in the
7507    /// file's own namespace, which includes what its `use super::*;` pulled in.
7508    #[test]
7509    fn a_self_qualified_path_resolves_through_the_files_own_glob_chain() {
7510        let files = [
7511            ("lib.rs", "mod p;\n"),
7512            ("p.rs", "use std::fs;\n\nmod c;\n"),
7513            (
7514                "p/c.rs",
7515                "use super::*;\n\nfn f() {\n    let _ = self::fs::read_dir(\".\");\n}\n",
7516            ),
7517        ];
7518        assert_eq!(flagged(&files), vec!["p.rs", "p/c.rs"]);
7519    }
7520
7521    /// Finding 1's negatives: a qualified path to a name the parent binds to
7522    /// something other than `std::fs` stops at that binding, and a path through a
7523    /// module that doesn't exist resolves nowhere.
7524    #[test]
7525    fn a_qualified_path_to_a_non_std_binding_or_missing_module_is_not_flagged() {
7526        let files = [
7527            ("lib.rs", "mod overlay;\nmod p;\n"),
7528            ("overlay.rs", "pub fn read_dir(_p: &str) {}\n"),
7529            ("p.rs", "use crate::overlay as fs;\n\nmod d;\n"),
7530            (
7531                "p/d.rs",
7532                "fn f() {\n    let _ = super::fs::read_dir(\".\");\n    let _ = crate::missing::fs::read_dir(\".\");\n}\n",
7533            ),
7534        ];
7535        assert_eq!(flagged(&files), Vec::<String>::new());
7536    }
7537
7538    /// Finding 2: a locally-declared type-namespace item beats a glob-imported name
7539    /// in real Rust — a child with its own `mod fs;` calling `fs::…` is calling its
7540    /// own submodule, not the ancestor's `std::fs`.
7541    #[test]
7542    fn a_locally_declared_module_shadows_the_ancestors_std_fs() {
7543        let files = [
7544            ("lib.rs", "mod p;\n"),
7545            ("p.rs", "use std::fs;\n\nmod c;\n"),
7546            (
7547                "p/c.rs",
7548                "use super::*;\n\nmod fs;\n\nfn f() {\n    let _ = fs::read_dir(\".\");\n}\n",
7549            ),
7550            ("p/c/fs.rs", "pub fn read_dir(_p: &str) {}\n"),
7551        ];
7552        assert_eq!(flagged(&files), vec!["p.rs"]);
7553    }
7554
7555    /// Finding 3: a trailing `//` comment on a `use` line must not sever the edge —
7556    /// neither the glob (`use super::*; // …`) nor the binding (`use std::fs; // …`).
7557    #[test]
7558    fn a_trailing_comment_on_a_use_line_does_not_sever_resolution() {
7559        let files = [
7560            ("lib.rs", "mod p;\n"),
7561            (
7562                "p.rs",
7563                "use std::fs; // read_source's disk fallback\n\nmod c;\n",
7564            ),
7565            (
7566                "p/c.rs",
7567                "use super::*; // parent's fs, PathBuf\n\nfn f() {\n    let _ = fs::read_dir(\".\");\n}\n",
7568            ),
7569        ];
7570        assert_eq!(flagged(&files), vec!["p.rs", "p/c.rs"]);
7571    }
7572
7573    /// Finding 4: the nested-group + `::self` normalisation branches, pinned
7574    /// directly — `use std::{fs::{self, File}, io};` binds `fs` *and* `File` to
7575    /// `std::fs`, and `io` only to the shadow set. Getting `::self` wrong would
7576    /// silently under-count, which is exactly this probe's failure mode.
7577    #[test]
7578    fn a_nested_group_with_self_binds_the_module_and_its_items() {
7579        let facts = fs_import_facts("use std::{fs::{self, File}, io};\n");
7580        let bound: Vec<&str> = facts.std_fs_bindings.iter().map(String::as_str).collect();
7581        assert_eq!(bound, vec!["File", "fs"]);
7582        assert!(facts.use_bound_names.contains("io"));
7583        assert!(!facts.std_fs_bindings.contains("io"));
7584    }
7585
7586    /// Finding 4, the children half of [`FsImportFacts`]' contract: a parent whose
7587    /// *only* `use std::fs;` lives in its `#[cfg(test)] mod` hands no binding to a
7588    /// glob-importing child — `bynk-ide/src/symbols.rs`' shape, latent until it
7589    /// grows a submodule.
7590    #[test]
7591    fn a_parents_test_mod_use_std_fs_does_not_reach_its_children() {
7592        let files = [
7593            ("lib.rs", "mod p;\n"),
7594            (
7595                "p.rs",
7596                "mod c;\n\nfn production() {}\n\n#[cfg(test)]\nmod tests {\n    use std::fs;\n\n    #[test]\n    fn t() {\n        let _ = fs::read_dir(\".\");\n    }\n}\n",
7597            ),
7598            (
7599                "p/c.rs",
7600                "use super::*;\n\nfn f() {\n    let _ = fs::read_dir(\".\");\n}\n",
7601            ),
7602        ];
7603        assert_eq!(flagged(&files), Vec::<String>::new());
7604    }
7605
7606    // --- fs_below_driver: named-floor classification (#1104) -----------------
7607
7608    #[test]
7609    fn fn_name_on_line_strips_modifiers() {
7610        assert_eq!(fn_name_on_line("fn foo() {"), Some("foo".to_string()));
7611        assert_eq!(
7612            fn_name_on_line("pub(crate) fn read_adapter_binding("),
7613            Some("read_adapter_binding".to_string())
7614        );
7615        assert_eq!(
7616            fn_name_on_line("pub async unsafe fn go() {"),
7617            Some("go".to_string())
7618        );
7619    }
7620
7621    #[test]
7622    fn fn_name_on_line_ignores_non_fn_lines() {
7623        assert_eq!(fn_name_on_line("    let f = foo();"), None);
7624        assert_eq!(fn_name_on_line("/// calls fn bar somewhere"), None);
7625    }
7626
7627    /// A signature whose `{` arrives lines after the `fn` line — `read_adapter_binding`'s
7628    /// own real shape — must still resolve to the correct body range: `started` can't
7629    /// flip true on the parameter list, which has no braces of its own.
7630    #[test]
7631    fn production_fn_ranges_handles_a_wrapped_signature() {
7632        let src = "pub(crate) fn read_adapter_binding(\n    path: &Path,\n) -> std::io::Result<String> {\n    fs::read_to_string(path)\n}\n";
7633        let lines: Vec<&str> = src.lines().collect();
7634        let ranges = production_fn_ranges(&lines, &[]);
7635        assert_eq!(ranges.len(), 1);
7636        let (name, start, end) = &ranges[0];
7637        assert_eq!(name, "read_adapter_binding");
7638        assert_eq!(*start, 0);
7639        assert_eq!(*end, lines.len() - 1);
7640        assert_eq!(
7641            enclosing_fn(3, &ranges),
7642            Some("read_adapter_binding".to_string())
7643        );
7644    }
7645
7646    /// #1561: [`NAMED_FS_EXCEPTIONS`] itself is empty (P4.0 moved every file it used to
7647    /// name out of `bynk-emit` entirely — see the const's own doc comment), so the tests
7648    /// below that exercise a *match* use these synthetic tuples instead of real,
7649    /// currently-empty production data — same crate as the real #1104 shape, but a
7650    /// file/fn pair invented for this test and never a real production exception.
7651    const SYNTHETIC_EXCEPTIONS: &[(&str, &str, &str)] = &[
7652        (
7653            "bynk-emit",
7654            "project/synthetic_example.rs",
7655            "synthetic_named_fn_a",
7656        ),
7657        (
7658            "bynk-emit",
7659            "project/synthetic_example.rs",
7660            "synthetic_named_fn_b",
7661        ),
7662    ];
7663
7664    /// Build the `facts`/`parents` vectors [`file_is_named_fs_floor`] now takes as
7665    /// caller-supplied arguments, the same way [`fs_below_driver`] does, so each test
7666    /// below reads as "classify this file" rather than repeating the setup.
7667    fn classify(
7668        krate: &str,
7669        files: &[(PathBuf, String)],
7670        i: usize,
7671        exceptions: &[(&str, &str, &str)],
7672    ) -> bool {
7673        let facts: Vec<FsImportFacts> = files.iter().map(|(_, s)| fs_import_facts(s)).collect();
7674        let parents: Vec<Option<usize>> =
7675            files.iter().map(|(p, _)| module_parent(p, files)).collect();
7676        file_is_named_fs_floor(krate, files, &facts, &parents, i, exceptions)
7677    }
7678
7679    /// The concrete #1104 shape, in miniature (#1561: against [`SYNTHETIC_EXCEPTIONS`],
7680    /// `NAMED_FS_EXCEPTIONS` itself being empty): `project.rs`'s bare `use std::fs;` (no
7681    /// enclosing fn — never itself a violation) plus `synthetic_example.rs`'s two
7682    /// named-exception functions. The whole file must read as a named floor, not
7683    /// residual.
7684    #[test]
7685    fn file_is_named_fs_floor_true_for_a_file_of_only_named_exceptions() {
7686        let files = [
7687            (
7688                PathBuf::from("project.rs"),
7689                "use std::fs;\n\nmod synthetic_example;\n".to_string(),
7690            ),
7691            (
7692                PathBuf::from("project/synthetic_example.rs"),
7693                "use super::*;\n\npub(crate) fn synthetic_named_fn_a() {\n    let _ = fs::read_dir(\".\");\n}\n\npub(crate) fn synthetic_named_fn_b(path: &Path) -> std::io::Result<String> {\n    fs::read_to_string(path)\n}\n".to_string(),
7694            ),
7695        ];
7696        assert!(classify("bynk-emit", &files, 1, SYNTHETIC_EXCEPTIONS));
7697    }
7698
7699    /// A new, unlisted fn touching `std::fs` in the *same file* as two named exceptions
7700    /// must flip the whole file to residual — no partial credit, since "named floor"
7701    /// must mean every touch is accounted for, not most of them.
7702    #[test]
7703    fn file_is_named_fs_floor_false_when_an_unnamed_fn_also_touches_fs() {
7704        let files = [
7705            (
7706                PathBuf::from("project.rs"),
7707                "use std::fs;\n\nmod synthetic_example;\n".to_string(),
7708            ),
7709            (
7710                PathBuf::from("project/synthetic_example.rs"),
7711                "use super::*;\n\npub(crate) fn synthetic_named_fn_a() {\n    let _ = fs::read_dir(\".\");\n}\n\nfn some_new_helper() {\n    let _ = fs::write(\"x\", \"y\");\n}\n".to_string(),
7712            ),
7713        ];
7714        assert!(!classify("bynk-emit", &files, 1, SYNTHETIC_EXCEPTIONS));
7715    }
7716
7717    /// A file whose only production-scope touch is a bare `use std::fs;` import — no
7718    /// enclosing fn at all — is trivially a named floor: the import performs no I/O by
7719    /// itself, and the descendant it enables is checked (and named) separately. No
7720    /// named exceptions needed at all here — nothing to match against.
7721    #[test]
7722    fn file_is_named_fs_floor_true_for_an_import_only_file() {
7723        let files = [(
7724            PathBuf::from("project.rs"),
7725            "use std::fs;\n\nmod discovery;\n".to_string(),
7726        )];
7727        assert!(classify("bynk-emit", &files, 0, &[]));
7728    }
7729
7730    /// The same synthetic-example shape under the wrong crate label must not read as a
7731    /// floor — [`NAMED_FS_EXCEPTIONS`] is keyed on `(crate, file, fn)`, not `(file, fn)`
7732    /// alone, so a same-named file/fn pair in a different crate isn't accidentally
7733    /// covered.
7734    #[test]
7735    fn file_is_named_fs_floor_false_under_the_wrong_crate() {
7736        let files = [
7737            (
7738                PathBuf::from("project.rs"),
7739                "use std::fs;\n\nmod synthetic_example;\n".to_string(),
7740            ),
7741            (
7742                PathBuf::from("project/synthetic_example.rs"),
7743                "use super::*;\n\npub(crate) fn synthetic_named_fn_a() {\n    let _ = fs::read_dir(\".\");\n}\n".to_string(),
7744            ),
7745        ];
7746        assert!(!classify("bynk-ide", &files, 1, SYNTHETIC_EXCEPTIONS));
7747    }
7748
7749    /// Review finding (#1106): a module-scope `std::fs` touch that isn't an import
7750    /// declaration — a `static` initialiser doing real I/O — has no enclosing fn either,
7751    /// but is a genuine R2.3 violation and must not be waved through as a floor just
7752    /// because it sits outside every known fn range.
7753    #[test]
7754    fn file_is_named_fs_floor_false_for_a_module_scope_static_that_reads() {
7755        let files = [(
7756            PathBuf::from("project.rs"),
7757            "use std::fs;\n\nstatic ROOT: once_cell::sync::Lazy<String> = once_cell::sync::Lazy::new(|| fs::read_to_string(\"x\").unwrap());\n"
7758                .to_string(),
7759        )];
7760        assert!(!classify("bynk-emit", &files, 0, &[]));
7761    }
7762
7763    /// Same review finding, the [`fn_name_on_line`] half: an `extern "C" fn` (a modifier
7764    /// combination the parser doesn't strip) produces no [`production_fn_ranges`] entry
7765    /// at all, so its whole body would fall into the "no enclosing fn" branch. It must
7766    /// still read as residual, not floor, once it touches `std::fs`.
7767    #[test]
7768    fn file_is_named_fs_floor_false_for_an_unparsed_extern_fn_body() {
7769        let files = [(
7770            PathBuf::from("project.rs"),
7771            "use std::fs;\n\nextern \"C\" fn callback() {\n    let _ = fs::read_dir(\".\");\n}\n"
7772                .to_string(),
7773        )];
7774        assert!(!classify("bynk-emit", &files, 0, &[]));
7775    }
7776
7777    /// #1587: [`NAMED_FS_EXCEPTIONS`] is empty today (#1561 cleared the three entries
7778    /// that outlived their files' P4.0 move out of `bynk-emit` for weeks, unnoticed,
7779    /// while `fs_below_driver`'s `0 named floor` reading stayed vacuously "healthy"),
7780    /// so this loop is vacuous now — but guards whatever named exception is decided
7781    /// next the same way [`ts_writes_excluded_files_still_exist`] and
7782    /// [`ast_importer_exceptions_still_exist_and_still_import_the_ast`] guard their own
7783    /// lists: a future entry going stale must fail loud here, not silently surface as
7784    /// a falsely-healthy `fs_below_driver` count. The tuple's third field is checked
7785    /// too (review of #1591), not just discarded — [`file_is_named_fs_floor`] matches
7786    /// on the full `(crate, file, fn)` key, so a refactor that keeps the file but
7787    /// renames or deletes the named function would otherwise leave a silently dead
7788    /// entry, the same recurrence shape #1561's three entries took.
7789    #[test]
7790    fn named_fs_exceptions_still_exist() {
7791        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
7792        for (krate, rel, fn_name) in NAMED_FS_EXCEPTIONS {
7793            let path = root.join(krate).join("src").join(rel);
7794            let contents = std::fs::read_to_string(&path).unwrap_or_else(|e| {
7795                panic!("NAMED_FS_EXCEPTIONS entry {krate:?}/{rel:?} does not exist: {e}")
7796            });
7797            assert!(
7798                contents.contains(fn_name),
7799                "NAMED_FS_EXCEPTIONS entry {krate:?}/{rel:?}/{fn_name:?} no longer names \
7800                 a function in that file — it excludes nothing and should be removed"
7801            );
7802        }
7803    }
7804
7805    // --- emit_abi_shapes (#999 Decision E) ----------------------------------
7806
7807    /// A binding's ordinary capability-interface imports, and the emit-ABI tag-layout
7808    /// names, must not be flagged — the exact failure mode Decision E rebuilt the probe
7809    /// to avoid (the original single-allowlist definition read 29-33 here, not 1).
7810    ///
7811    /// Exercises the real production allowlists via [`is_enumerated_emit_abi_or_capability_surface`]
7812    /// — not a local re-declaration. A test with its own copy of `EMIT_ABI` would still
7813    /// pass if the real one lost an entry (e.g. deleting `Uuid` from the production
7814    /// list), proving nothing about the probe it claims to cover.
7815    #[test]
7816    fn emit_abi_shapes_does_not_flag_capability_or_tag_layout_imports() {
7817        let src = "import type { Clock, Fetch, Locale } from \"./bynk.js\";\n\
7818                    import { FetchError, Uuid } from \"./bynk.js\";\n\
7819                    import { Err, None, Ok, Some, type Option, type Result } from \"./runtime.js\";\n";
7820        let imports = ts_named_imports_from_runtime_modules(src);
7821        let leaks: Vec<&String> = imports
7822            .iter()
7823            .filter(|i| !is_enumerated_emit_abi_or_capability_surface(i))
7824            .collect();
7825        assert!(leaks.is_empty(), "unexpected leaks: {leaks:?}");
7826    }
7827
7828    /// The falsifier from #999 Decision E, checked directly: deleting an entry from the
7829    /// real production allowlist must be detectable by *some* test — this one flags
7830    /// `Uuid` as a leak the moment it's removed from [`EMIT_ABI`], which the test above
7831    /// (using the real const) would also start failing on.
7832    #[test]
7833    fn is_enumerated_checks_the_real_production_allowlist() {
7834        assert!(is_enumerated_emit_abi_or_capability_surface("Uuid"));
7835        assert!(is_enumerated_emit_abi_or_capability_surface("LocaleTag"));
7836        assert!(!is_enumerated_emit_abi_or_capability_surface(
7837            "negotiateLocale"
7838        ));
7839    }
7840
7841    /// The real, current-tree finding this probe exists to surface: `negotiateLocale`,
7842    /// a plain value helper from `./runtime.js` alongside the tag-layout constructors,
7843    /// is neither an enumerated emit-ABI shape nor a capability-interface import.
7844    #[test]
7845    fn emit_abi_shapes_flags_a_non_enumerated_runtime_helper() {
7846        let src = "import { Err, None, Ok, Some, negotiateLocale, type Option, type Result } from \"./runtime.js\";\n";
7847        let imports = ts_named_imports_from_runtime_modules(src);
7848        assert!(imports.contains(&"negotiateLocale".to_string()));
7849    }
7850
7851    /// `FetchError` is `import type` in one binding and a plain value import in
7852    /// another (`FetchError.Timeout`) — Decision E's rejected type-vs-value
7853    /// discriminator. Confirms the extractor treats both forms as the same identifier,
7854    /// so the allowlist check doesn't depend on which form a given file happens to use.
7855    #[test]
7856    fn ts_import_extraction_ignores_type_only_vs_value_distinction() {
7857        let type_only = "import type { FetchError } from \"./bynk.js\";\n";
7858        let value = "import { FetchError, Uuid } from \"./bynk.js\";\n";
7859        assert_eq!(
7860            ts_named_imports_from_runtime_modules(type_only),
7861            vec!["FetchError".to_string()]
7862        );
7863        assert!(ts_named_imports_from_runtime_modules(value).contains(&"FetchError".to_string()));
7864    }
7865
7866    // --- options_sources -----------------------------------------------------
7867
7868    #[test]
7869    fn struct_body_finds_a_field_by_name() {
7870        let src = "struct Foo {\n    pub sources: Option<HashMap<PathBuf, String>>,\n    pub other: bool,\n}\n";
7871        let body = struct_body(src, "Foo").expect("struct body found");
7872        assert!(body.contains("sources"));
7873    }
7874
7875    #[test]
7876    fn struct_body_does_not_match_an_unrelated_struct() {
7877        let src =
7878            "struct Bar {\n    pub sources: bool,\n}\n\nstruct Foo {\n    pub other: bool,\n}\n";
7879        let body = struct_body(src, "Foo").expect("struct body found");
7880        assert!(!body.contains("sources"));
7881    }
7882
7883    // --- render_table's "Rules closed" section (#1001) ------------------------
7884
7885    fn empty_report() -> Report {
7886        Report { probes: Vec::new() }
7887    }
7888
7889    /// The section is static text — no count, no existence check — precisely
7890    /// because nothing regenerates `design/greenfield-status.md` when `stamp`
7891    /// writes the ledger, so a computed count would silently go stale the
7892    /// moment the first `closes_rule` landed (the drift a first draft of this
7893    /// section introduced, caught in #1001's review). This test pins "static"
7894    /// as the actual behaviour, not just the intent in a comment.
7895    #[test]
7896    fn render_table_rules_closed_section_is_static_regardless_of_the_tree() {
7897        let out = render_table(&empty_report());
7898        assert!(out.contains("greenfield-status-rules.md"), "{out}");
7899        assert!(
7900            out.contains("may not exist yet"),
7901            "the wording must not claim to know whether the ledger exists: {out}"
7902        );
7903    }
7904
7905    /// The stamp rewrites the gated rows and the weekly workflow the trend rows;
7906    /// adjacent changed lines conflict in git, so the two blocks must always have
7907    /// an unchanged line between them.
7908    #[test]
7909    fn render_table_separates_gated_and_trend_blocks() {
7910        let probe = |name, gated| Probe {
7911            name,
7912            gated,
7913            reads: "1".to_string(),
7914        };
7915        let report = Report {
7916            probes: vec![
7917                probe("ts_writes", true),
7918                probe("explained_codes", true),
7919                probe("wildcard_arms", false),
7920                probe("keep_in_sync", false),
7921            ],
7922        };
7923        let out = render_table(&report);
7924        let lines: Vec<&str> = out.lines().collect();
7925        let is_row = |l: &str, gated: bool| {
7926            l.starts_with("| `") && l.contains(if gated { "| yes |" } else { "| no (trend) |" })
7927        };
7928        for (i, l) in lines.iter().enumerate() {
7929            if is_row(l, true) {
7930                assert!(
7931                    !lines.get(i + 1).is_some_and(|n| is_row(n, false)),
7932                    "a gated row is directly above a trend row: {l}"
7933                );
7934            }
7935        }
7936        assert!(out.contains("## Trend probes (not gated)"), "{out}");
7937        // Both refreshers still find their rows in the rendered table.
7938        let g = refresh_gated_rows(&out, &report.probes).unwrap();
7939        let t = refresh_trend_rows(&out, &report.probes).unwrap();
7940        assert_eq!(g, out);
7941        assert_eq!(t, out);
7942    }
7943
7944    /// A whole test file is test code, so the family probes skip it: a module's tests
7945    /// moving out to `foo/tests.rs` must not raise `ts_writes`. Run through
7946    /// [`codegen_family_from`], so deleting its filter fails this test.
7947    #[test]
7948    fn family_probes_skip_whole_test_files() {
7949        let write = "fn f() { let _ = format!(\"x\"); }\n".to_string();
7950        let file = |rel: &str| (PathBuf::from(rel), write.clone());
7951        let family = codegen_family_from(
7952            vec![
7953                file("emitter/lower.rs"),
7954                file("emitter/tests.rs"),
7955                file("emitter/tests/golden.rs"),
7956            ],
7957            vec![
7958                file("project/entry.rs"),
7959                file("project/tests.rs"),
7960                file("project/entry_scope_tests.rs"),
7961            ],
7962        );
7963        let kept: Vec<_> = family.iter().map(|(p, _)| p.to_string_lossy()).collect();
7964        assert_eq!(kept, ["emitter/lower.rs", "project/entry.rs"]);
7965        assert_eq!(ts_writes_violations(&family), 2);
7966    }
7967
7968    /// A module declared `#[cfg(test)] mod x;` is test code wherever it lives, as `module_lines`
7969    /// reads it: every probe that skips whole test files skips it too, and a file that is not
7970    /// declared that way still counts.
7971    #[test]
7972    fn a_declaration_gated_module_is_test_code_for_every_probe() {
7973        use crate::module_lines::{gated_stems, is_test_only_file};
7974        let files = files_of(&[
7975            (
7976                "bynk/src/dev.rs",
7977                "#[cfg(test)]\nmod test_support;\nmod run;\n",
7978            ),
7979            ("bynk/src/dev/test_support.rs", ""),
7980            ("bynk/src/dev/run.rs", ""),
7981            ("bynk/src/dev/tests.rs", ""),
7982        ]);
7983        let gated = gated_stems(&files);
7984        assert!(is_test_only_file("bynk/src/dev/test_support.rs", &gated));
7985        assert!(is_test_only_file("bynk/src/dev/tests.rs", &gated));
7986        assert!(!is_test_only_file("bynk/src/dev/run.rs", &gated));
7987        assert!(!is_test_only_file("bynk/src/dev.rs", &gated));
7988        // The binding probe: a construction in the gated file is not a home; in `run.rs` it is.
7989        let field = "WorkerBinding { name, source: BindingSource::Kv }\n";
7990        let parent = "#[cfg(test)]\nmod test_support;\nmod run;\n";
7991        let homes = |support: &str, run: &str| {
7992            binding_kind_homes_files(&files_of(&[
7993                ("bynk/src/dev.rs", parent),
7994                ("bynk/src/dev/test_support.rs", support),
7995                ("bynk/src/dev/run.rs", run),
7996            ]))
7997            .len()
7998        };
7999        assert_eq!(homes(field, ""), 0);
8000        assert_eq!(homes("", field), 1);
8001        // The family probes: the same rule, read against each half's own paths.
8002        let write = "fn f() { let _ = format!(\"x\"); }\n".to_string();
8003        let file = |rel: &str, body: &str| (PathBuf::from(rel), body.to_string());
8004        let family = codegen_family_from(
8005            vec![
8006                file("emitter.rs", "#[cfg(test)]\nmod fixtures;\n"),
8007                file("emitter/fixtures.rs", &write),
8008                file("emitter/lower.rs", &write),
8009            ],
8010            vec![],
8011        );
8012        let kept: Vec<_> = family.iter().map(|(p, _)| p.to_string_lossy()).collect();
8013        assert_eq!(kept, ["emitter.rs", "emitter/lower.rs"]);
8014    }
8015
8016    // --- ts_writes / ts_any (P7.0, #1296; testability + widening, review of #1297) --
8017
8018    /// Run [`ts_writes_violations`] over an in-memory file list — mirrors
8019    /// [`flagged`]'s own role for `production_std_fs_files`.
8020    fn ts_writes_over(files: &[(&str, &str)]) -> usize {
8021        let owned: Vec<(PathBuf, String)> = files
8022            .iter()
8023            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
8024            .collect();
8025        ts_writes_violations(&owned)
8026    }
8027
8028    /// Run [`ts_any_violations`] over an in-memory file list.
8029    fn ts_any_over(files: &[(&str, &str)]) -> usize {
8030        let owned: Vec<(PathBuf, String)> = files
8031            .iter()
8032            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
8033            .collect();
8034        ts_any_violations(&owned)
8035    }
8036
8037    /// Run [`verbatim_origins_violations`] over an in-memory file list.
8038    fn verbatim_origins_over(files: &[(&str, &str)]) -> usize {
8039        let owned: Vec<(PathBuf, String)> = files
8040            .iter()
8041            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
8042            .collect();
8043        verbatim_origins_violations(&owned)
8044    }
8045
8046    /// Run [`verbatim_sites_violations`] over an in-memory file list.
8047    fn verbatim_sites_over(files: &[(&str, &str)]) -> usize {
8048        let owned: Vec<(PathBuf, String)> = files
8049            .iter()
8050            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
8051            .collect();
8052        verbatim_sites_violations(&owned)
8053    }
8054
8055    #[test]
8056    fn ts_writes_excluded_files_are_recognised() {
8057        assert!(is_ts_writes_excluded_file(Path::new("emitter/wrangler.rs")));
8058        assert!(is_ts_writes_excluded_file(Path::new("emitter/secrets.rs")));
8059        assert!(is_ts_writes_excluded_file(Path::new(
8060            "emitter/contracts.rs"
8061        )));
8062        // `testkit.rs` left the list in 1B.2b: it holds no `format!` any more.
8063        assert!(!is_ts_writes_excluded_file(Path::new("testkit.rs")));
8064        // Name proximity to a file that used to be excluded must not false-positive:
8065        // `emitter/lower.rs` (the emitter's own lowering pass) is genuinely
8066        // TS-producing and must stay counted — unlike `ir/lower.rs` (the checker→IR
8067        // pass), which isn't a name-proximity risk at all any more: it left
8068        // `bynk-emit/src` entirely at Arc D's P7.12 crate carve. `emitter/source_map.rs`
8069        // is the same shape (#1561): it left for `bynk-ts/src/source_map.rs` at P7.5
8070        // (#1308), so it's no longer excluded either — there's nothing left to exclude.
8071        assert!(!is_ts_writes_excluded_file(Path::new("emitter/lower.rs")));
8072        assert!(!is_ts_writes_excluded_file(Path::new("ir/lower.rs")));
8073        assert!(!is_ts_writes_excluded_file(Path::new(
8074            "emitter/source_map.rs"
8075        )));
8076        assert!(!is_ts_writes_excluded_file(Path::new("emitter.rs")));
8077        assert!(!is_ts_writes_excluded_file(Path::new("project.rs")));
8078        assert!(!is_ts_writes_excluded_file(Path::new(
8079            "project/tests_emit.rs"
8080        )));
8081    }
8082
8083    /// #1587: the exact failure #1561 fixed for [`NAMED_FS_EXCEPTIONS`] (an entry
8084    /// outliving its file by weeks while the gated probe kept reading a vacuous,
8085    /// falsely-healthy number) applies just as well to [`TS_WRITES_EXCLUDED_FILES`] —
8086    /// nothing previously caught a stale entry here either. Must fail loud, not surface
8087    /// as a silent `ts_writes`/`ts_any` regression in `greenfield_status_table_is_current`
8088    /// — mirrors [`ast_importer_exceptions_still_exist_and_still_import_the_ast`]'s own
8089    /// discipline for the sibling list: existence alone isn't enough (review of #1591)
8090    /// — a file that survives but stops containing any `write!`/`writeln!`/`format!`
8091    /// site would excludes nothing, and removing it would change no probe count, so
8092    /// [`ts_writes_violations`] must actually see a nonzero count over each entry's real
8093    /// content. Scored under a dummy, non-excluded path so the exclusion filter itself
8094    /// doesn't short-circuit the check.
8095    #[test]
8096    fn ts_writes_excluded_files_still_exist() {
8097        let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8098            .join("..")
8099            .join("bynk-emit/src");
8100        for rel in TS_WRITES_EXCLUDED_FILES {
8101            let contents = std::fs::read_to_string(dir.join(rel)).unwrap_or_else(|e| {
8102                panic!("TS_WRITES_EXCLUDED_FILES entry {rel:?} does not exist: {e}")
8103            });
8104            let dummy = [(PathBuf::from("__not_excluded__.rs"), contents)];
8105            assert!(
8106                ts_writes_violations(&dummy) > 0,
8107                "TS_WRITES_EXCLUDED_FILES entry {rel:?} no longer contains a \
8108                 write!/writeln!/format! call outside a test module — it excludes \
8109                 nothing and should be removed"
8110            );
8111        }
8112    }
8113
8114    /// Regression for a real mistake this slice's own grounding found: an earlier
8115    /// survey during phase 7's own track-opening research treated
8116    /// `project/tests_emit.rs` as excludable "test-assertion" noise. It is real
8117    /// production code (`process_tests`/`process_integration_tests`) per
8118    /// `semantics-in-the-checker.md`'s own settling finding for a different probe on
8119    /// the same file. Exercises the real probe, not just the predicate (review of
8120    /// #1297 — a first cut of this test called `is_ts_writes_excluded_file` directly,
8121    /// which can't catch a bug in [`ts_writes_violations`]'s own use of it).
8122    #[test]
8123    fn ts_writes_does_not_exclude_tests_emit_rs_wholesale() {
8124        let count = ts_writes_over(&[(
8125            "project/tests_emit.rs",
8126            "fn process_tests() {\n    let _ = format!(\"const x = 1;\");\n    let _ = writeln!(out, \"const y = 2;\");\n}\n",
8127        )]);
8128        assert_eq!(
8129            count, 2,
8130            "tests_emit.rs's own production emission code must be counted, not excluded wholesale"
8131        );
8132    }
8133
8134    #[test]
8135    fn is_path_construction_line_catches_the_idiom_not_ordinary_format_calls() {
8136        assert!(is_path_construction_line(
8137            "let p = PathBuf::from(format!(\"workers/{dashes}/index.ts\"));"
8138        ));
8139        assert!(is_path_construction_line(
8140            "root.join(format!(\"tests/integration_{sanitized}.test.ts\"))"
8141        ));
8142        assert!(is_path_construction_line(
8143            "output_path.with_file_name(format!(\"{name}.{suffix}\"))"
8144        ));
8145        // An ordinary TS-producing `format!` call, no path construction, must not be
8146        // excluded by this idiom.
8147        assert!(!is_path_construction_line(
8148            "writeln!(out, \"{}\", format!(\"const {name} = 1;\"))"
8149        ));
8150    }
8151
8152    #[test]
8153    fn line_violates_ts_any_catches_the_cast_and_the_bare_annotation() {
8154        assert!(line_violates_ts_any("let x = (value as any).field;"));
8155        assert!(line_violates_ts_any("format!(\"{}: any\", name)"));
8156        assert!(line_violates_ts_any(
8157            "\"(seq: any[]) => ({ns} as any).drive(seq)\""
8158        ));
8159        assert!(!line_violates_ts_any("let x: unknown = value;"));
8160    }
8161
8162    /// Regression for review of #1297, finding 1: `any` in generic type-argument
8163    /// position (`Record<string, any[]>`, the live `emitter/lower.rs`
8164    /// `joinOn`/`leftJoin`/`groupBy` shape) contains neither `as any` nor `: any` and
8165    /// was silently uncounted by the round-one predicate.
8166    #[test]
8167    fn line_violates_ts_any_catches_generic_position_any() {
8168        assert!(line_violates_ts_any(
8169            "\"{{ const __h: Record<string, any[]> = {{}}; ...}}\""
8170        ));
8171        assert!(line_violates_ts_any("\"Array<any>\""));
8172        assert!(line_violates_ts_any("\"Promise<any>\""));
8173        // Must not regress the round-one patterns while widening.
8174        assert!(line_violates_ts_any("(value as any).field"));
8175        assert!(line_violates_ts_any("(e: any) => {}"));
8176    }
8177
8178    /// Regression for review of #1322, finding 2: once a site builds a real
8179    /// `bynk_ts::TsType` node instead of writing TypeScript text directly, the
8180    /// emitted `any` no longer appears as Rust-source `as any`/`: any` — the round-
8181    /// one/round-two patterns above all match *emitted-text* spellings, none of
8182    /// which appear in `TsType::named("any")`. `workers.rs`'s own three real sites
8183    /// (#1321) were silently uncounted until this pattern was added.
8184    #[test]
8185    fn line_violates_ts_any_catches_the_named_any_construction_spelling() {
8186        assert!(line_violates_ts_any(
8187            "    let mut args = vec![as_expr(ident(\"payload\"), TsType::named(\"any\"))];"
8188        ));
8189        assert!(line_violates_ts_any(
8190            "        Some(TsType::named(\"any\")),"
8191        ));
8192        // Must not regress the round-one/round-two patterns while widening.
8193        assert!(line_violates_ts_any("(value as any).field"));
8194        assert!(line_violates_ts_any("\"Array<any>\""));
8195    }
8196
8197    /// A comment mentioning either pattern in prose — the same self-reference-shaped
8198    /// hazard [`bynk_dotted_literals`]'s own regression tests guard against for a
8199    /// different probe — must not count.
8200    #[test]
8201    fn line_violates_ts_any_ignores_comments() {
8202        assert!(!line_violates_ts_any(
8203            "/// lowering machinery, same as any other subexpression."
8204        ));
8205        assert!(!line_violates_ts_any(
8206            "// TODO: stop emitting `: any` here once bynk-ts exists"
8207        ));
8208    }
8209
8210    /// `#[cfg(test)]`-gated write!-family calls (a file's own unit tests constructing a
8211    /// fixture string) must not count toward either probe — mirrors
8212    /// [`has_production_std_fs`]'s own test-range exclusion for a different probe.
8213    /// Exercises the real probes end to end, not a re-implementation of their loop
8214    /// (review of #1297, finding 2): deleting either probe's `in_test_range` guard, its
8215    /// `is_ts_writes_excluded_file` `continue`, or (for `ts_writes`) its
8216    /// `is_path_construction_line` `continue` now fails one of these tests.
8217    #[test]
8218    fn ts_writes_and_ts_any_exclude_cfg_test_ranges() {
8219        let src = "fn production() {\n    let _ = format!(\"const x = 1;\");\n}\n\n\
8220                    #[cfg(test)]\nmod tests {\n    #[test]\n    fn t() {\n        \
8221                    let _ = format!(\"(v as any)\");\n    }\n}\n";
8222        assert_eq!(
8223            ts_writes_over(&[("emitter.rs", src)]),
8224            1,
8225            "only the production format! call counts"
8226        );
8227        assert_eq!(
8228            ts_any_over(&[("emitter.rs", src)]),
8229            0,
8230            "the test-only `as any` site must be excluded"
8231        );
8232    }
8233
8234    /// Exercises the real probes' file-exclusion `continue`, not just the predicate:
8235    /// a whole file on [`TS_WRITES_EXCLUDED_FILES`] must contribute 0 to either count
8236    /// even when its content would otherwise match both.
8237    #[test]
8238    fn ts_writes_and_ts_any_exclude_named_non_ts_files_end_to_end() {
8239        let files = [(
8240            "emitter/wrangler.rs",
8241            "fn write_toml(out: &mut String) {\n    let _ = writeln!(out, \"name = {v}\");\n    let __x: any = 1;\n}\n",
8242        )];
8243        assert_eq!(ts_writes_over(&files), 0);
8244        assert_eq!(ts_any_over(&files), 0);
8245    }
8246
8247    /// Exercises the real probes' [`is_path_construction_line`] `continue` end to end,
8248    /// not just the predicate in isolation.
8249    #[test]
8250    fn ts_writes_excludes_path_construction_end_to_end() {
8251        let files = [(
8252            "project.rs",
8253            "fn out_path(dashes: &str) -> PathBuf {\n    PathBuf::from(format!(\"workers/{dashes}/index.ts\"))\n}\n\nfn emit(out: &mut String) {\n    let _ = writeln!(out, \"export const x = 1;\");\n}\n",
8254        )];
8255        assert_eq!(
8256            ts_writes_over(&files),
8257            1,
8258            "the path-construction line must not count; the genuine emission line must"
8259        );
8260    }
8261
8262    #[test]
8263    fn verbatim_origins_counts_distinct_variants_not_construction_sites() {
8264        let files = [(
8265            "emitter/contracts.rs",
8266            "fn a() { TsStmt::verbatim(VerbatimOrigin::Contracts, \"x\", None) }\nfn b() { TsStmt::verbatim(VerbatimOrigin::Contracts, \"y\", None) }\nfn c() { TsStmt::verbatim(VerbatimOrigin::Secrets, \"z\", None) }\n",
8267        )];
8268        // Three construction sites, but only two distinct origins.
8269        assert_eq!(verbatim_origins_over(&files), 2);
8270        assert_eq!(verbatim_sites_over(&files), 3);
8271    }
8272
8273    #[test]
8274    fn verbatim_origins_and_sites_ignore_comments() {
8275        let files = [(
8276            "emitter/contracts.rs",
8277            "// TsStmt::verbatim(VerbatimOrigin::Contracts, \"x\", None)\n/// Mentions VerbatimOrigin::Secrets in prose.\n",
8278        )];
8279        assert_eq!(verbatim_origins_over(&files), 0);
8280        assert_eq!(verbatim_sites_over(&files), 0);
8281    }
8282
8283    #[test]
8284    fn verbatim_origins_and_sites_read_zero_over_an_empty_tree() {
8285        let files: [(&str, &str); 0] = [];
8286        assert_eq!(verbatim_origins_over(&files), 0);
8287        assert_eq!(verbatim_sites_over(&files), 0);
8288    }
8289
8290    /// Review of #1308, finding 6: without stripping `#[cfg(test)]` ranges,
8291    /// a single `bynk-emit` unit test fixture constructing a `TsStmt::
8292    /// verbatim(...)` for its own coverage would pin `verbatim_sites` above
8293    /// its documented 0 floor permanently, for a reason unrelated to
8294    /// residual production emission.
8295    #[test]
8296    fn verbatim_origins_and_sites_exclude_cfg_test_ranges() {
8297        let src = "fn production() {\n    TsStmt::verbatim(VerbatimOrigin::Contracts, \"x\", None);\n}\n\n\
8298                    #[cfg(test)]\nmod tests {\n    #[test]\n    fn t() {\n        \
8299                    TsStmt::verbatim(VerbatimOrigin::Secrets, \"y\", None);\n    }\n}\n";
8300        assert_eq!(
8301            verbatim_origins_over(&[("emitter/contracts.rs", src)]),
8302            1,
8303            "only the production-code origin counts"
8304        );
8305        assert_eq!(
8306            verbatim_sites_over(&[("emitter/contracts.rs", src)]),
8307            1,
8308            "the test-only construction site must be excluded"
8309        );
8310    }
8311
8312    /// #1539: `verbatim_sites` widened from a `TsStmt::verbatim(`-only scan
8313    /// to also count `TsExpr::VerbatimExpr(` construction sites — the same
8314    /// escape hatch, now closed at the expression level too. Pins that both
8315    /// needles are counted (and both still respect the comment/`#[cfg(test)]`
8316    /// exclusions the sibling tests above already establish for the
8317    /// `TsStmt` half).
8318    #[test]
8319    fn verbatim_sites_counts_the_expr_level_needle_too() {
8320        let src = "fn f() {\n    let x = TsExpr::VerbatimExpr(\"a\".to_string(), VerbatimOrigin::Emit);\n    let y = TsStmt::verbatim(VerbatimOrigin::Emit, \"b\", None);\n}\n";
8321        assert_eq!(
8322            verbatim_sites_over(&[("emitter/emit.rs", src)]),
8323            2,
8324            "one TsExpr::VerbatimExpr( site plus one TsStmt::verbatim( site"
8325        );
8326        assert_eq!(
8327            verbatim_origins_over(&[("emitter/emit.rs", src)]),
8328            1,
8329            "both reference the same VerbatimOrigin::Emit variant"
8330        );
8331    }
8332
8333    // --- incremental_query_types (P8.0, #1510; re-settled by #1537) ----------
8334
8335    fn owned(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
8336        files
8337            .iter()
8338            .map(|(p, s)| (PathBuf::from(p), (*s).to_string()))
8339            .collect()
8340    }
8341
8342    #[test]
8343    fn unit_signature_present_recognises_the_real_struct_and_ignores_a_comment() {
8344        assert!(unit_signature_present(&owned(&[(
8345            "unit_signature.rs",
8346            "pub struct UnitSignature {\n    types: HashMap<String, Arc<TypeDecl>>,\n}\n",
8347        )])));
8348        assert!(!unit_signature_present(&owned(&[(
8349            "lib.rs",
8350            "// TODO: build a struct UnitSignature here eventually\n",
8351        )])));
8352        assert!(!unit_signature_present(&[]));
8353    }
8354
8355    /// The committed reading after #1537: neither deleted level is back.
8356    #[test]
8357    fn deleted_levels_present_is_empty_when_neither_level_exists() {
8358        assert!(deleted_levels_present(&[]).is_empty());
8359    }
8360
8361    /// Re-adding `ProjectGraph` anywhere flips the reading — the whole workspace is
8362    /// scanned (review of #1582) because P8.3 (ADR 0415) already landed it in a
8363    /// different crate from the one first assumed, and R3.13's table names a third
8364    /// (`bynk-resolve`) that does not exist yet.
8365    #[test]
8366    fn deleted_levels_present_sees_project_graph_wherever_it_lands() {
8367        let graph = "pub struct ProjectGraph {\n    units: HashMap<UnitId, Unit>,\n}\n";
8368        assert_eq!(
8369            deleted_levels_present(&owned(&[("project_graph.rs", graph)])),
8370            vec!["ProjectGraph"]
8371        );
8372        assert_eq!(
8373            deleted_levels_present(&owned(&[("resolve/graph.rs", graph)])),
8374            vec!["ProjectGraph"]
8375        );
8376        assert!(
8377            deleted_levels_present(&owned(&[(
8378                "lib.rs",
8379                "// a struct ProjectGraph used to live here\n"
8380            )]))
8381            .is_empty()
8382        );
8383    }
8384
8385    /// **The empirically-confirmed false positive #1510's own first run caught** (see
8386    /// [`defid_query_fn_present`]): `bynk-check/src/checker.rs` has an ordinary,
8387    /// pre-existing `fn type_of(expr: &Expr, ..)` with no `DefId` anywhere in its
8388    /// signature. After #1537 the direction of the mistake reverses — it would now
8389    /// read as the deleted level having been *re-added* — so it is pinned against the
8390    /// real function's own signature text here too.
8391    #[test]
8392    fn deleted_levels_present_does_not_count_checkers_pre_existing_type_of() {
8393        let found = deleted_levels_present(&owned(&[(
8394            "checker.rs",
8395            "pub(crate) fn type_of(expr: &Expr, expected: Option<TyId>, ctx: &mut Ctx) -> Option<TyId> {\n",
8396        )]));
8397        assert!(
8398            found.is_empty(),
8399            "checker.rs's own type_of has no DefId parameter and must not count: {found:?}"
8400        );
8401    }
8402
8403    #[test]
8404    fn deleted_levels_present_sees_a_real_defid_keyed_body_and_type_of() {
8405        let queries = "pub fn body(id: DefId) -> Body {\n    todo!()\n}\n\npub fn type_of(id: DefId) -> TypeOf {\n    todo!()\n}\n";
8406        assert_eq!(
8407            deleted_levels_present(&owned(&[("queries.rs", queries)])),
8408            vec!["Body", "TypeOf"]
8409        );
8410    }
8411
8412    #[test]
8413    fn shared_cache_migrated_is_false_while_project_unit_cache_still_exists() {
8414        let ide_src: Vec<(PathBuf, String)> = vec![(
8415            PathBuf::from("completion.rs"),
8416            "static PROJECT_UNIT_CACHE: LazyLock<Mutex<HashMap<PathBuf, CachedUnit>>> = ..;"
8417                .to_string(),
8418        )];
8419        let project_src: Vec<(PathBuf, String)> = vec![(
8420            PathBuf::from("cache.rs"),
8421            "pub struct SharedUnitCache { .. }".to_string(),
8422        )];
8423        assert!(!shared_cache_migrated(&ide_src, &project_src));
8424    }
8425
8426    #[test]
8427    fn shared_cache_migrated_is_true_once_project_unit_cache_is_gone_and_a_shared_cache_lands() {
8428        let ide_src: Vec<(PathBuf, String)> = vec![(
8429            PathBuf::from("completion.rs"),
8430            "fn cached_project_unit(path: &Path, content: &str) -> Option<Arc<SourceUnit>> { .. }"
8431                .to_string(),
8432        )];
8433        let project_src: Vec<(PathBuf, String)> = vec![(
8434            PathBuf::from("cache.rs"),
8435            "pub struct SharedUnitCache { units: HashMap<FileId, Arc<SourceUnit>> }".to_string(),
8436        )];
8437        assert!(shared_cache_migrated(&ide_src, &project_src));
8438    }
8439
8440    /// **The real hole finding 1 caught**: absence of `PROJECT_UNIT_CACHE` from
8441    /// `bynk-ide` alone used to read "migrated" even when nothing shared replaced it —
8442    /// a rename or deletion with no cache anywhere in `bynk-project` satisfied the old
8443    /// clause. Now requires a cache-shaped item to actually land in
8444    /// `bynk-project/src` too.
8445    #[test]
8446    fn shared_cache_migrated_is_false_when_project_unit_cache_is_gone_but_nothing_shared_replaces_it()
8447     {
8448        let ide_src: Vec<(PathBuf, String)> = vec![(
8449            PathBuf::from("completion.rs"),
8450            "fn cached_project_unit(path: &Path, content: &str) -> Option<Arc<SourceUnit>> { .. }"
8451                .to_string(),
8452        )];
8453        assert!(!shared_cache_migrated(&ide_src, &[]));
8454    }
8455
8456    /// The needle is anchored on `static PROJECT_UNIT_CACHE`, not a bare substring —
8457    /// `PROJECT_UNIT_CACHE_CAP` (a real, unrelated `const` in
8458    /// `bynk-ide/src/completion.rs`) must not hold this false on its own.
8459    #[test]
8460    fn shared_cache_migrated_is_not_confused_by_project_unit_cache_cap() {
8461        let ide_src: Vec<(PathBuf, String)> = vec![(
8462            PathBuf::from("completion.rs"),
8463            "const PROJECT_UNIT_CACHE_CAP: usize = 4096;".to_string(),
8464        )];
8465        let project_src: Vec<(PathBuf, String)> = vec![(
8466            PathBuf::from("cache.rs"),
8467            "pub struct SharedUnitCache { .. }".to_string(),
8468        )];
8469        assert!(shared_cache_migrated(&ide_src, &project_src));
8470    }
8471
8472    #[test]
8473    fn stability_test_present_recognises_a_matching_test_name() {
8474        let check_tests: Vec<(PathBuf, String)> = vec![(
8475            PathBuf::from("unit_signature.rs"),
8476            "#[test]\nfn unit_signature_is_stable_under_a_body_edit() { .. }\n".to_string(),
8477        )];
8478        assert!(stability_test_present(&check_tests));
8479    }
8480
8481    #[test]
8482    fn stability_test_present_recognises_test_attribute_separated_by_other_attributes() {
8483        let check_tests: Vec<(PathBuf, String)> = vec![(
8484            PathBuf::from("unit_signature.rs"),
8485            "#[test]\n#[should_panic]\nfn unit_signature_panics_when_stability_is_violated() { .. }\n"
8486                .to_string(),
8487        )];
8488        assert!(stability_test_present(&check_tests));
8489    }
8490
8491    #[test]
8492    fn stability_test_present_is_false_for_an_unrelated_test() {
8493        let check_tests: Vec<(PathBuf, String)> = vec![(
8494            PathBuf::from("differential_analysis.rs"),
8495            "#[test]\nfn new_entry_point_matches_analyse_project_with() { .. }\n".to_string(),
8496        )];
8497        assert!(!stability_test_present(&check_tests));
8498    }
8499
8500    #[test]
8501    fn stability_test_present_ignores_a_comment_mentioning_it() {
8502        let check_tests: Vec<(PathBuf, String)> = vec![(
8503            PathBuf::from("lib.rs"),
8504            "// TODO: add a unit_signature stability test (P8.2)\n".to_string(),
8505        )];
8506        assert!(!stability_test_present(&check_tests));
8507    }
8508
8509    /// **The real hole finding 3 caught**: the old match required only
8510    /// `fn `+`unit_signature`+`stab` on one line, with no check for an actual
8511    /// `#[test]` attribute — a plain, non-test helper used to satisfy the clause with
8512    /// no passing test in existence.
8513    #[test]
8514    fn stability_test_present_is_false_for_a_non_test_helper_with_a_matching_name() {
8515        let check_tests: Vec<(PathBuf, String)> = vec![(
8516            PathBuf::from("unit_signature.rs"),
8517            "fn unit_signature_stability_fixture(edit: &Edit) -> UnitSignature { .. }\n"
8518                .to_string(),
8519        )];
8520        assert!(!stability_test_present(&check_tests));
8521    }
8522
8523    // --- unused_deps (A4, #2976) --------------------------------------------------
8524
8525    type TestCrate<'a> = (&'a str, &'a str, &'a [(&'a str, &'a str)]);
8526
8527    fn deps_over(root: &str, crates: &[TestCrate<'_>]) -> Vec<String> {
8528        let crates: Vec<UnusedDepsCrate> = crates
8529            .iter()
8530            .map(|(dir, manifest, files)| {
8531                (
8532                    dir.to_string(),
8533                    manifest.to_string(),
8534                    files
8535                        .iter()
8536                        .map(|(p, c)| (PathBuf::from(p), c.to_string()))
8537                        .collect(),
8538                )
8539            })
8540            .collect();
8541        let raw = unused_deps_over(root, &crates);
8542        let mut out: Vec<String> = raw
8543            .iter()
8544            .map(|(k, d, kind)| format!("{k}:{d}:{kind}"))
8545            .collect();
8546        out.sort();
8547        out
8548    }
8549
8550    const ROOT: &str = "[workspace]\nmembers = [\"a\"]\n";
8551
8552    fn manifest(deps: &str) -> String {
8553        format!("[package]\nname = \"a\"\n{deps}")
8554    }
8555
8556    #[test]
8557    #[should_panic(expected = "a/Cargo.toml does not parse")]
8558    fn unused_deps_panics_on_a_malformed_member_manifest() {
8559        deps_over(ROOT, &[("a", "not toml [", &[])]);
8560    }
8561
8562    #[test]
8563    #[should_panic(expected = "lists no [workspace] members")]
8564    fn unused_deps_panics_on_empty_members() {
8565        workspace_members("[workspace]\nmembers = []\n");
8566    }
8567
8568    #[test]
8569    #[should_panic(expected = "is a glob")]
8570    fn unused_deps_panics_on_a_glob_member() {
8571        workspace_members("[workspace]\nmembers = [\"crates/*\"]\n");
8572    }
8573
8574    #[test]
8575    fn unused_deps_normal_dependency_is_not_used_by_the_build_script_alone() {
8576        let m = manifest("[dependencies]\nx = \"1\"\n");
8577        let r = deps_over(ROOT, &[("a", &m, &[("build.rs", "use x::f;")])]);
8578        assert_eq!(r, vec!["a:x:".to_string()]);
8579    }
8580
8581    #[test]
8582    fn unused_deps_skips_target_node_modules_and_fixture_trees() {
8583        for dir in ["target", "node_modules", "fixtures"] {
8584            assert!(unused_deps_skips(
8585                &Path::new("tests").join(dir).join("x.rs")
8586            ));
8587        }
8588        assert!(!unused_deps_skips(Path::new("src/lib.rs")));
8589    }
8590
8591    #[test]
8592    fn unused_deps_flags_a_dependency_with_no_use_and_passes_a_used_one() {
8593        let m = manifest("[dependencies]\nused = \"1\"\nunused = \"1\"\n");
8594        let got = deps_over(ROOT, &[("a", &m, &[("src/lib.rs", "use used::f;\n")])]);
8595        assert_eq!(got, ["a:unused:"]);
8596    }
8597
8598    #[test]
8599    fn unused_deps_ignores_a_comment_and_a_longer_identifier() {
8600        let m = manifest("[dependencies]\nserde = \"1\"\n");
8601        let src =
8602            "// serde is not used\n/// serde either\nuse serde_json::Value;\nlet my_serde = 1;\n";
8603        assert_eq!(
8604            deps_over(ROOT, &[("a", &m, &[("src/lib.rs", src)])]),
8605            ["a:serde:"]
8606        );
8607        // A macro, a derive path and a re-export are uses.
8608        for used in [
8609            "serde::de();",
8610            "#[derive(serde::Serialize)] struct S;",
8611            "pub use serde::Serialize;",
8612            "m!(serde::x);",
8613        ] {
8614            assert!(deps_over(ROOT, &[("a", &m, &[("src/lib.rs", used)])]).is_empty());
8615        }
8616    }
8617
8618    #[test]
8619    fn unused_deps_reads_a_renamed_dependency_by_its_alias() {
8620        let m = manifest("[dependencies]\nalias = { package = \"real-name\", version = \"1\" }\n");
8621        assert!(deps_over(ROOT, &[("a", &m, &[("src/lib.rs", "use alias::f;")])]).is_empty());
8622        assert_eq!(
8623            deps_over(ROOT, &[("a", &m, &[("src/lib.rs", "use real_name::f;")])]),
8624            ["a:alias:"]
8625        );
8626    }
8627
8628    #[test]
8629    fn unused_deps_counts_dev_dependencies_in_tests_but_not_normal_ones() {
8630        let m = manifest("[dependencies]\nn = \"1\"\n[dev-dependencies]\nd = \"1\"\n");
8631        let files: &[(&str, &str)] = &[
8632            ("src/lib.rs", "fn f() {}"),
8633            ("tests/t.rs", "use n::x; use d::y;"),
8634        ];
8635        // `n` is a normal dependency used only under `tests/`: not a use. `d` is.
8636        assert_eq!(deps_over(ROOT, &[("a", &m, files)]), ["a:n:"]);
8637    }
8638
8639    #[test]
8640    fn unused_deps_reads_a_build_dependency_in_the_build_script_only() {
8641        let m = manifest("build = \"bindings/rust/build.rs\"\n[build-dependencies]\ncc = \"1\"\n");
8642        let ok: &[(&str, &str)] = &[("bindings/rust/build.rs", "cc::Build::new();")];
8643        assert!(deps_over(ROOT, &[("a", &m, ok)]).is_empty());
8644        let elsewhere: &[(&str, &str)] = &[("src/lib.rs", "use cc::Build;")];
8645        assert_eq!(deps_over(ROOT, &[("a", &m, elsewhere)]), ["a:cc:build"]);
8646    }
8647
8648    #[test]
8649    fn unused_deps_reads_target_tables_and_optional_dependencies() {
8650        let m = manifest(
8651            "[target.'cfg(unix)'.dependencies]\nlibc = \"1\"\n[dependencies]\nschemars = { version = \"1\", optional = true }\n[features]\nschema = [\"dep:schemars\"]\n",
8652        );
8653        // `dep:schemars` in `[features]` is not a use; a `cfg(feature)` use is.
8654        assert_eq!(
8655            deps_over(ROOT, &[("a", &m, &[("src/lib.rs", "fn f() {}")])]),
8656            ["a:libc:", "a:schemars:"]
8657        );
8658        let src = "#[cfg(unix)] use libc::c_int;\n#[cfg(feature = \"schema\")] use schemars::JsonSchema;\n";
8659        assert!(deps_over(ROOT, &[("a", &m, &[("src/lib.rs", src)])]).is_empty());
8660    }
8661
8662    #[test]
8663    fn unused_deps_flags_a_workspace_entry_no_member_references() {
8664        let root = "[workspace]\nmembers = [\"a\"]\n[workspace.dependencies]\nused = \"1\"\norphan = \"1\"\n";
8665        let m = manifest("[dependencies]\nused.workspace = true\n");
8666        let got = deps_over(root, &[("a", &m, &[("src/lib.rs", "use used::f;")])]);
8667        assert_eq!(got, ["[workspace]:orphan:"]);
8668    }
8669
8670    #[test]
8671    fn unused_deps_offenders_apply_the_allowlist_and_label_dev_and_build() {
8672        let raw = vec![
8673            ("a".to_string(), "x".to_string(), ""),
8674            ("a".to_string(), "y".to_string(), "dev"),
8675            ("a".to_string(), "z".to_string(), "build"),
8676            ("bynk-tests".to_string(), "clap".to_string(), ""),
8677        ];
8678        assert_eq!(
8679            unused_deps_offenders(&raw),
8680            ["a:x", "a:y[dev]", "a:z[build]"]
8681        );
8682        assert_eq!(unused_deps_reading(&[]), "0");
8683        assert_eq!(unused_deps_reading(&["a:x".to_string()]), "1 (a:x)");
8684    }
8685
8686    /// Every allowlist entry names a declared edge that would otherwise be flagged
8687    /// (so a fixed or deleted edge fails here and the entry gets removed) and says why.
8688    #[test]
8689    fn unused_deps_allowlist_entries_are_live() {
8690        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
8691        let raw = unused_deps_raw(&root);
8692        for (krate, dep, reason) in UNUSED_DEPS_ALLOWED {
8693            assert!(!reason.trim().is_empty(), "{krate}:{dep} has no reason");
8694            assert!(
8695                raw.iter().any(|(k, d, _)| k == krate && d == dep),
8696                "allowlisted {krate}:{dep} is no longer an unused edge; remove it"
8697            );
8698        }
8699    }
8700
8701    /// The moved-`project` matcher is component-wise on the relative path: lookalikes
8702    /// (`projects.rs`, `project_lock.rs`, `projects/x.rs`) are not the module.
8703    #[test]
8704    fn moved_project_file_matches_the_module_not_lookalikes() {
8705        assert!(is_moved_project_file(Path::new("project.rs")));
8706        assert!(is_moved_project_file(Path::new(
8707            "project/tests_emit/harness.rs"
8708        )));
8709        assert!(!is_moved_project_file(Path::new("projects.rs")));
8710        assert!(!is_moved_project_file(Path::new("project_lock.rs")));
8711        assert!(!is_moved_project_file(Path::new("projects/x.rs")));
8712        assert!(!is_moved_project_file(Path::new("test_runner.rs")));
8713    }
8714}