diff --git a/AGENTS.md b/AGENTS.md index 66f25871b0..a35fc61b2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -96,7 +96,7 @@ done until its gate is met on the live node and the change is MERGED. | 4 | No monolith | NEW RULE (Joel, 10-20): "No one can edit a large file." Every Rust file a PR touches ends at most 1,000 lines; the only PR that touches a monolith is the one that breaks it apart (CI gate). `source-hygiene::file_size` (lines past 1,000; 159,720 on 10-18) falls every week; split by OWNER, never one-off fixes appended to a monolith | owner of each file | | 5 | No unwraps | `unwrap_justification` (2,135 on 10-18) falls every week; make the state unrepresentable | owner of each file | | 6 | Microkernel | `layer_discipline` (256 upward imports on 10-18) falls; crates by device target; edit-to-proven <15 min | Sneasel — proposed | -| 7 | One budget | everything in a prompt (history, grounding, tools, reasoning, results) is a claim in ONE flex allocation; no fixed number; positron/RAG sources too. NEVER CLIP THE NEWEST END: her latest result is the step that ends the recursion; cut it and her next input can equal her last, so she repeats the act (Benchy, 125 identical acts in an hour on 10-20). Keep the newest interaction whole and the full result reachable; shrink oldest-first to a handle she can expand. `source-hygiene::head_cuts` (179 on 10-20) falls | Sneasel | +| 7 | One budget | everything in a prompt (history, grounding, tools, reasoning, results) is a claim in ONE flex allocation; no fixed number; positron/RAG sources too. NEVER CLIP THE NEWEST END: her latest result is the step that ends the recursion; cut it and her next input can equal her last, so she repeats the act (Benchy, 125 identical acts in an hour on 10-20). Keep the newest interaction whole and the full result reachable; shrink oldest-first to a handle she can expand. `source-hygiene` `self_sized` (one rule for every resource; ONE-BUDGET.md) falls, and a touched file ends with none | Sneasel | | 8 | Learning | a reviewed correction applied on unseen tasks, retained after restart, vs the same base without the gene | Cormac, BigMama | | 9 | One scheduler, the whole grid | every mind on every node (residents and minds leased in from other nodes) is served by ONE RTOS scheduler: one measured activity temperature per mind is its priority, aging means no mind is ever starved, hot minds keep warm KV and cooling minds page to RAM; windows never shrink to seat more; how many minds share the engine at once is the measured admission and sequence-capacity contract of #5188, never a fixed count | Codex — proposed (card b4eed65c) | | 10 | Tools are working sets | the native tool surface is the command-namespace SUBTREES the activity declares (code/**, work/**, a game's controls); stable within a phase, a switch is a cached prefix, the long tail appends via help; tool share of the prompt measured before/after (44% on 10-18) | Sneasel (card ecd5dff3) | diff --git a/CLAUDE.md b/CLAUDE.md index a23eb8ae4f..1f1e5d17a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,7 +117,7 @@ done until its gate is met on the live node and the change is MERGED. | 4 | No monolith | NEW RULE (Joel, 10-20): "No one can edit a large file." Every Rust file a PR touches ends at most 1,000 lines; the only PR that touches a monolith is the one that breaks it apart (CI gate). `source-hygiene::file_size` (lines past 1,000; 159,720 on 10-18) falls every week; split by OWNER, never one-off fixes appended to a monolith | owner of each file | | 5 | No unwraps | `unwrap_justification` (2,135 on 10-18) falls every week; make the state unrepresentable | owner of each file | | 6 | Microkernel | `layer_discipline` (256 upward imports on 10-18) falls; crates by device target; edit-to-proven <15 min | Sneasel — proposed | -| 7 | One budget | everything in a prompt (history, grounding, tools, reasoning, results) is a claim in ONE flex allocation; no fixed number; positron/RAG sources too. NEVER CLIP THE NEWEST END: her latest result is the step that ends the recursion; cut it and her next input can equal her last, so she repeats the act (Benchy, 125 identical acts in an hour on 10-20). Keep the newest interaction whole and the full result reachable; shrink oldest-first to a handle she can expand. The one exception: a newest result that alone exceeds what her window leaves it arrives at its summary plus that handle, because kept whole it stops her acting at all (Aris, 10-26). `source-hygiene::head_cuts` (179 on 10-20) falls | Sneasel | +| 7 | One budget | everything in a prompt (history, grounding, tools, reasoning, results) is a claim in ONE flex allocation; no fixed number; positron/RAG sources too. NEVER CLIP THE NEWEST END: her latest result is the step that ends the recursion; cut it and her next input can equal her last, so she repeats the act (Benchy, 125 identical acts in an hour on 10-20). Keep the newest interaction whole and the full result reachable; shrink oldest-first to a handle she can expand. The one exception: a newest result that alone exceeds what her window leaves it arrives at its summary plus that handle, because kept whole it stops her acting at all (Aris, 10-26). `source-hygiene` `self_sized` (one rule for every resource; ONE-BUDGET.md) falls, and a touched file ends with none | Sneasel | | 8 | Learning | a reviewed correction applied on unseen tasks, retained after restart, vs the same base without the gene | Cormac, BigMama | | 9 | One scheduler, the whole grid | every mind on every node (residents and minds leased in from other nodes) is served by ONE RTOS scheduler: one measured activity temperature per mind is its priority, aging means no mind is ever starved, hot minds keep warm KV and cooling minds page to RAM; windows never shrink to seat more; how many minds share the engine at once is the measured admission and sequence-capacity contract of #5188, never a fixed count | Codex — proposed (card b4eed65c) | | 10 | Tools are working sets | the native tool surface is the command-namespace SUBTREES the activity declares (code/**, work/**, a game's controls); stable within a phase, a switch is a cached prefix, the long tail appends via help; tool share of the prompt measured before/after (44% on 10-18) | Sneasel (card ecd5dff3) | diff --git a/core/continuum-core/src/test_env/mind_integration/source_guards.rs b/core/continuum-core/src/test_env/mind_integration/source_guards.rs index 149f7c0bb6..afa021148f 100644 --- a/core/continuum-core/src/test_env/mind_integration/source_guards.rs +++ b/core/continuum-core/src/test_env/mind_integration/source_guards.rs @@ -4,139 +4,6 @@ //! they guard; the mind crate cannot name core's test environment, so they live here. Each //! asserts exactly what it asserted before the move. -/// From `cognition::context_budget` (its sanctioned home for the calibration). -mod context_budget { - /// what this catches: THE SIXTH TIME. This defect has been fixed and has come back at - /// least five times — #45 (max_tokens clamps), #46 (per-tier context caps), #50 (single- - /// source the effective window), #124 (`EVAL_LANE_CONTEXT = 16_384`, deleted), and then - /// `EXAM_LANE_CTX = 16384` reintroduced the *same* constant in the *same file* three - /// weeks later under a determinism justification. Doc comments and task entries did not - /// stop it; each new author re-derives a "reasonable" number in good faith. - /// - /// So this is a RED TEST, not a doc. It scans the whole crate for the shape — a - /// constant whose name says window/context/token/prompt/chars and whose value is a bare - /// literal — and fails on a new one. Adding a bound is still allowed: put it on - /// [`ContextBudget`] as a FRACTION, where it scales with the served window. If you are - /// here because this test failed, that is the fix; do not add your name to the list above. - /// - /// A constant that genuinely is NOT a window-relative bound (a phrase length, a dedup key - /// prefix, another model's stated REQUIREMENT) declares itself with a - /// `context-budget-exempt: ` comment on the line above. Exemptions are cheap to write - /// and permanently visible in review — which is the point. A silent exemption is not - /// available, because silence is how this came back five times. - /// - /// Weakening this test is the same act as re-introducing the constant. - #[test] - fn no_new_hardcoded_context_or_prompt_size_constant_anywhere_in_the_crate() { - // Crate-wide, not just cognition/: the 4096/2048 adapter floor (#46's own surface) sat - // outside cognition and would not have been caught by a cognition-only scan. - let named = |n: &str| { - // Categorically not size bounds, so they don't need to spend an exemption line: - // a duration (`*_MS`), an identifier (`*_ID`), or a vocabulary offset (`*_OFFSET`). - if n.ends_with("_MS") || n.ends_with("_ID") || n.ends_with("_OFFSET") { - return false; - } - ["WINDOW", "CONTEXT", "CTX", "TOKEN", "PROMPT", "CHARS"] - .iter() - .any(|k| n.contains(k)) - }; - let mut offenders = Vec::new(); - for file in crate::test_env::source_tree::crate_sources() { - // Vendored upstream code (candle/llama ports) is not ours to restyle; its - // constants are the upstream model's own defaults. - if file.rel.split('/').any(|c| c == "vendored") { - continue; - } - // This module IS the sanctioned home for the calibration; its doc table - // quotes the very constants it replaced. - if file.path.file_name().is_some_and(|f| f == "context_budget.rs") { - continue; - } - let (path, src) = (&file.path, &file.text); - let lines: Vec<&str> = src.lines().collect(); - for (i, line) in lines.iter().enumerate() { - let t = line.trim_start(); - // Declared non-bound: the marker appears anywhere in the contiguous - // comment block directly above (a reason worth writing often needs two - // lines, and a doc comment may sit between it and the const). - let exempt = lines[..i] - .iter() - .rev() - .take_while(|l| { - let t = l.trim_start(); - t.starts_with("//") || t.is_empty() - }) - .any(|l| l.contains("context-budget-exempt:")); - if exempt { - continue; - } - // Any visibility, `pub(in crate::path)` included: a split by owner widens - // a moved constant to that form, and a fixed prefix list lost it. - let unscoped = match t.strip_prefix("pub") { - Some(after) if after.starts_with('(') => { - after.split_once(')').map_or(t, |(_, rest)| rest.trim_start()) - } - Some(after) => after.trim_start(), - None => t, - }; - let Some(rest) = unscoped.strip_prefix("const ") else { - continue; - }; - let Some((name, tail)) = rest.split_once(':') else { - continue; - }; - if !named(name.trim()) { - continue; - } - let Some((ty, value)) = tail.split_once('=') else { - continue; - }; - // Only sizes and RATIOS. A &str / bool / Duration named "...CONTEXT..." is - // not a bound. - // - // The float types are here because of a hole this test had for its whole - // life, found 2026-08-20 the first time anyone wrote a window-relative - // constant that wasn't a token COUNT: `WINDOW_COMPARABILITY_FACTOR: f64 = - // 2.0` (#2339, mine). Name matched, value was a bare literal, and it - // sailed through — because the type list stopped at the integers. A guard - // against invented numbers that a `f64` annotation defeats teaches exactly - // one lesson: type your magic number as a float. A ratio over the window is - // as much a fresh guess as a count of its tokens, and is caught the same way. - if !["u32", "usize", "u64", "i32", "i64", "f32", "f64"].contains(&ty.trim()) { - continue; - } - // A bare literal is the defect — decimal or float, since both are equally - // guessed. An expression built from another named bound (`MIN_SERVE_CTX * 8`) - // is a derivation, not a fresh guess. - let v = value.trim().trim_end_matches(';').trim(); - let bare_literal = !v.is_empty() - && v.chars().all(|c| c.is_ascii_digit() || c == '_' || c == '.') - // `.` only as a decimal point: `1.5` yes, `A.b` / `1..2` no. - && v.matches('.').count() <= 1 - && v.starts_with(|c: char| c.is_ascii_digit()); - if bare_literal { - offenders.push(format!( - "{}:{} — const {}: {} = {}", - path.file_name().unwrap_or_default().to_string_lossy(), - i + 1, - name.trim(), - ty.trim(), - v - )); - } - } - } - assert!( - offenders.is_empty(), - "hardcoded context/prompt size constant(s) reintroduced in cognition — express \ - these as a fraction on ContextBudget so they scale with the SERVED window \ - (a 4k-shaped constant makes a 1M-context model useless and deletes the reason \ - to run MoE at all):\n {}", - offenders.join("\n ") - ); - } -} - /// From `cognition::experience` (the lived-turn producer's one caller). mod experience { // what this catches: the lived-turn producer wired per-CALL-SITE again. diff --git a/core/continuum-core/src/test_env/source_tree.rs b/core/continuum-core/src/test_env/source_tree.rs index c9bc49fc0f..373cd4c73c 100644 --- a/core/continuum-core/src/test_env/source_tree.rs +++ b/core/continuum-core/src/test_env/source_tree.rs @@ -56,7 +56,7 @@ impl SourceFile { if self.is_test_file() { return String::new(); } - source_hygiene::production_half(&self.text) + source_hygiene::lexer::production_half(&self.text) .lines() .map(code_only) .collect::>() @@ -93,7 +93,7 @@ impl SourceFile { /// nor trip a guard. Source-hygiene's splitter, which knows string literals: one /// comment rule for the ratchets and these guards. pub(crate) fn code_only(line: &str) -> &str { - source_hygiene::split_code_and_comment(line).0 + source_hygiene::lexer::split_code_and_comment(line).0 } /// The crates cut out of continuum-core whose modules core re-exports under their old diff --git a/core/continuum-kernel/src/gpu/backends/mod.rs b/core/continuum-kernel/src/gpu/backends/mod.rs index 8e144c9d59..3ebbd72155 100644 --- a/core/continuum-kernel/src/gpu/backends/mod.rs +++ b/core/continuum-kernel/src/gpu/backends/mod.rs @@ -51,7 +51,7 @@ mod tests { let src = include_str!("mod.rs"); let code: Vec<&str> = src .lines() - .map(|l| source_hygiene::split_code_and_comment(l).0.trim()) + .map(|l| source_hygiene::lexer::split_code_and_comment(l).0.trim()) .collect(); // For each `pub mod NAME;` remember whether a cfg attribute sits directly above diff --git a/core/source-hygiene/src/bin/ratchets.rs b/core/source-hygiene/src/bin/ratchets.rs index 951d036c8e..568c08af0b 100644 --- a/core/source-hygiene/src/bin/ratchets.rs +++ b/core/source-hygiene/src/bin/ratchets.rs @@ -30,23 +30,37 @@ fn run(base_ref: &str) -> Result { let scratch = std::env::temp_dir().join(format!("source-hygiene-base-{}", std::process::id())); let record = scratch.with_extension("counts"); let head_record = scratch.with_extension("head-counts"); + let touched = scratch.with_extension("touched"); + std::fs::write(&touched, touched_files(&base)?).map_err(|e| format!("cannot write the touched-file list {}: {e}", touched.display()))?; git(&["worktree", "add", "--detach", &scratch.to_string_lossy(), &base])?; eprintln!("ratchets: base {base} ({base_ref}) at {}", scratch.display()); // The base run records; its other tests may fail on the base tree (an uninitialized // submodule for vendor_pin), which is not this PR's to judge, so only its record counts. let _ = cargo_test(&repo, &[("SOURCE_HYGIENE_CORE", scratch.join("core").as_path()), ("SOURCE_HYGIENE_RECORD", record.as_path())]); - let judged = cargo_test(&repo, &[("SOURCE_HYGIENE_BASE", record.as_path()), ("SOURCE_HYGIENE_RECORD", head_record.as_path())]); + let judged = cargo_test( + &repo, + &[("SOURCE_HYGIENE_BASE", record.as_path()), ("SOURCE_HYGIENE_RECORD", head_record.as_path()), ("SOURCE_HYGIENE_TOUCHED", touched.as_path())], + ); print_movement(&record, &head_record); let removed = git(&["worktree", "remove", "--force", &scratch.to_string_lossy()]); let _ = std::fs::remove_file(&record); let _ = std::fs::remove_file(&head_record); + let _ = std::fs::remove_file(&touched); removed?; judged } /// The receipt: every ratchet's base and head count, the moved ones first. +/// The Rust files this change touches, one repository path per line: the working tree against +/// `base` (so a local run judges uncommitted work too) and new files git does not track yet. +fn touched_files(base: &str) -> Result { + let changed = git(&["diff", "--name-only", "--diff-filter=ACMR", base])?; + let untracked = git(&["ls-files", "--others", "--exclude-standard"])?; + Ok(changed.lines().chain(untracked.lines()).filter(|path| path.ends_with(".rs")).collect::>().join("\n")) +} + fn print_movement(base: &Path, head: &Path) { let read = |p: &Path| std::fs::read_to_string(p).map(|t| source_hygiene::ratchet::parse(&t)).unwrap_or_default(); // unwrap_or_default: a run that recorded nothing prints nothing; the judged run already failed loudly let (base, head) = (read(base), read(head)); diff --git a/core/source-hygiene/src/boundary_serialization.rs b/core/source-hygiene/src/boundary_serialization.rs index 40ebb98cb1..2e6dff10fa 100644 --- a/core/source-hygiene/src/boundary_serialization.rs +++ b/core/source-hygiene/src/boundary_serialization.rs @@ -35,7 +35,7 @@ //! one is **the unjustified count may never rise** — every new site names its //! boundary, every old one touched is a chance to ratchet down. -use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; +use super::{lexer::split_code_and_comment, SourceFile, SourceRule, Violation}; /// Same bar as the unwrap rule — a justification has to say something. // context-budget-exempt: bounds the length of a COMMENT a human types, never a diff --git a/core/source-hygiene/src/budget_discipline.rs b/core/source-hygiene/src/budget_discipline.rs new file mode 100644 index 0000000000..f67d9d9441 --- /dev/null +++ b/core/source-hygiene/src/budget_discipline.rs @@ -0,0 +1,52 @@ +//! **Every resource is spent through one budget: VRAM, RAM, disk and a mind's context.** +//! +//! The contract is `docs/architecture/ONE-BUDGET.md`. One authority measures each resource +//! and grants it to typed claims; one allocator (the flexbox, priority/floor/min/max/grow) +//! sizes every grant; a consumer reconciles to its grant and never sizes itself. Joel, +//! 2026-10-30: "Everything must follow a governor or a rag budgeter as a consumer or it will +//! inevitably fail." +//! +//! These rules count the ways around that contract. Each is judged two ways (`ratchet.rs`): +//! the count never rises over the base tree, and a file the change touches ends with none +//! (`SOURCE_HYGIENE_TOUCHED`), the same discipline as the 1,000-line gate. That second +//! judgement is what drives the counts to zero instead of holding them. +//! +//! There is no exemption comment. A site is allowed only by being an OWNER, named here by +//! its repository path: the allocator, the authority's probes, the store. Everything else +//! is a consumer and takes its size from a grant. +//! +//! These are lexical rules, a backstop. The lasting enforcement is the type: once claims +//! and grants exist, a cache, ring, lane or file class is constructed from its grant and an +//! unbudgeted one does not compile. + +mod probes; +mod self_sized; +mod writes; + +#[cfg(test)] +mod tests; + +pub use probes::PrivateProbes; +pub use self_sized::SelfSized; +pub use writes::WritesOutsideAClass; + +use crate::SourceFile; + +/// Does this constant's name say it is a duration or a rate? That is `time_bounds`' class, +/// never `SelfSized`'s; one predicate, so the two rules cannot disagree. A unit is a SUFFIX +/// (`_MS` must not read `MAX_MSGS` as a time). +pub(crate) fn is_duration_name(name: &str) -> bool { + const UNITS: &[&str] = &["_MS", "_US", "_NS", "_SECS", "_SECONDS", "_MINUTES", "_HOURS", "_PER_S", "_TPS", "_HZ"]; + const WORDS: &[&str] = &["TIMEOUT", "INTERVAL", "CADENCE", "DEADLINE"]; + UNITS.iter().any(|u| name.ends_with(u) || name.contains(&format!("{u}_"))) || WORDS.iter().any(|w| name.contains(w)) +} + +/// Upstream code ported verbatim carries upstream's numbers; it is not ours to budget. +fn is_vendored(file: &SourceFile) -> bool { + file.repo.split('/').any(|part| part == "vendored") +} + +/// Does `file` live under one of `owners` (repository path prefixes)? +fn owned_by(file: &SourceFile, owners: &[&str]) -> bool { + owners.iter().any(|owner| file.repo.starts_with(owner)) +} diff --git a/core/source-hygiene/src/budget_discipline/probes.rs b/core/source-hygiene/src/budget_discipline/probes.rs new file mode 100644 index 0000000000..938ad2d25a --- /dev/null +++ b/core/source-hygiene/src/budget_discipline/probes.rs @@ -0,0 +1,47 @@ +//! `private_probes`: a resource measured anywhere but the authority's probes. Five VRAM +//! probes, seven private RAM reads and a sentinel with its own `sysinfo` poll disagreed +//! with each other and with the authority (the inventory on canary 365f70fe4); each +//! consumer then sized itself from its own number. + +use super::{is_vendored, owned_by}; +use crate::{sites, SourceFile, SourceRule, Violation}; + +/// The authority's probes: the only code that measures a resource. +const OWNERS: &[&str] = &[ + "core/continuum-kernel/src/system_resources/memory_pressure", + "core/continuum-kernel/src/system_resources/disk_pressure", + "core/continuum-kernel/src/gpu/monitor.rs", + "core/continuum-kernel/src/gpu/backends/", +]; + +/// Calls and paths that read memory, VRAM or disk capacity or usage. +const MEASUREMENTS: &[&str] = &[ + "sysinfo::", + "System::new", + ".refresh_memory(", + ".available_memory(", + ".total_memory(", + "mem_get_info", + "nvidia-smi", + "recommendedMaxWorkingSetSize", + "statvfs", + "task_info(", + "phys_footprint", + "/proc/meminfo", + "/proc/self/statm", +]; + +pub struct PrivateProbes; + +impl SourceRule for PrivateProbes { + fn name(&self) -> &'static str { + "private_probes" + } + + fn check(&self, file: &SourceFile) -> Vec { + if is_vendored(file) || owned_by(file, OWNERS) { + return Vec::new(); + } + sites(file, self.name(), |code| MEASUREMENTS.iter().find(|m| code.contains(**m)).map(|m| format!("measures with `{m}`"))) + } +} diff --git a/core/source-hygiene/src/budget_discipline/self_sized.rs b/core/source-hygiene/src/budget_discipline/self_sized.rs new file mode 100644 index 0000000000..2e1557e1db --- /dev/null +++ b/core/source-hygiene/src/budget_discipline/self_sized.rs @@ -0,0 +1,168 @@ +//! `self_sized`: a consumer deciding how much of a resource it gets, instead of taking it +//! from its grant. The shapes, each found at many sites on canary 365f70fe4: +//! +//! - a sized constant (`EMBEDDING_CACHE_MAX = 20_000`, `KEEP = 8`, `ECHOED_ARG_CHARS = 600`); +//! - a product of constants (`PREFILL_TARGET_SECONDS × CONSERVATIVE_PREFILL_TOKENS_PER_S` +//! clipped every machine's conversation to a flat 15,000 tokens); +//! - a literal ceiling (`.take(8)`, `.truncate(5)`, `.min(1_500)`, `channel(256)`); +//! - a head cut of text she will read (`.chars().take(`): it drops what happened last, so +//! she acts as if time never moved and repeats herself (Benchy, 125 identical acts, 10-20); +//! - a size read off `ContextBudget`'s fractions of the window, a second budget the turn's +//! one allocation never saw (the 739-probe swing on 10-28). +//! +//! Durations are a different class (`time_bounds`); a constant +//! whose name says it is a time is not counted here. + +use super::{is_duration_name, is_vendored, owned_by}; +use crate::lexer::{constant_product, is_bare_literal, numeric_const}; +use crate::{sites, SourceFile, SourceRule, Violation}; + +/// The allocator: the one place sizes are computed. +const ALLOCATOR: &[&str] = &["core/continuum-grounding/src/rag_budget/flex_allocate.rs"]; + +/// The turn's one allocation: the only caller of the allocator for a mind's prompt. +const TURN_ALLOCATION: &[&str] = &["core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/"]; + +/// Where text is rendered for a mind to read; a head cut there loses her newest end. +const MIND_TEXT: &[&str] = &[ + "core/continuum-cognition/", + "core/continuum-mind/", + "core/continuum-prompt/", + "core/continuum-grounding/", + "core/continuum-context/", + "core/continuum-academy/", + "core/continuum-perception/", + "core/continuum-capture/", + "core/continuum-core/src/commands/tool/", +]; + +/// Module directories whose text reaches a mind wherever their crate is (`head_cuts`' coverage, +/// kept whole: modules/voice_reply_speaker.rs cut spoken text by its head, Codex on #5609). +const MIND_TEXT_MODULES: &[&str] = + &["cognition/", "persona/", "genome/", "rag/", "modules/", "airc/", "positron/", "experience/", "recipe/"]; + +/// Name fragments that say a constant sizes something. +const SIZE_WORDS: &[&str] = &[ + "CAP", "MAX", "MIN_", "FLOOR", "CEILING", "LIMIT", "BOUND", "BUDGET", "QUOTA", "RESERVE", "ALLOWANCE", + "HEADROOM", "KEEP", "RETAIN", "ENTRIES", "WINDOW", "CONTEXT", "CTX", "TOKEN", "PROMPT", "CHARS", "BYTES", + "KIB", "MIB", "GIB", "FRACTION", "SHARE", "DIVISOR", "RATIO", "PCT", "PERCENT", "LANES", "SLOTS", "LINES", + "ROWS", "ITEMS", "SIZE", "LEN", "DEPTH", "GENERATIONS", "STEPS", +]; + +/// Calls that size against `ContextBudget`'s fractions of the window, or allocate outside +/// the turn's one allocation. +const BUDGET_FRACTIONS: &[&str] = &[ + "ContextBudget::live(", + "ContextBudget::live_or_floor(", + "ContextBudget::from_window(", + "ContextBudget::from_window_for(", + "ContextBudget::from_window_unbounded(", + ".recall_tokens(", + ".grounding_tokens(", + ".tool_surface_tokens(", + ".latest_action_chars(", + ".dispatch_result_chars(", + ".render_slice_chars(", + ".catalog_summary_chars(", + ".echoed_arg_chars(", + ".trail_head_chars(", + ".recent_results_chars(", + ".receipt_archive_chars(", + ".default_response_tokens(", + "_SHARE_DENOM", +]; + +/// Calls into the allocator; allowed only in the turn's allocation. +const ALLOCATOR_CALLS: &[&str] = &["flex_allocate(", "budget_claim(", "FlexboxRagBudgetAdapter::new(", "adapter.allocate("]; + +/// Calls that keep the START of text and drop its end. +const HEAD_KEEPERS: &[&str] = &[".chars().take(", "head_to_tokens(", "truncate_chars(", ".lines().next()"]; + +/// Calls whose literal argument is a ceiling on a count or a length. +const LITERAL_CEILINGS: &[&str] = &[".take(", ".truncate(", "[..", "channel(", "bounded("]; + +pub struct SelfSized; + +impl SourceRule for SelfSized { + fn name(&self) -> &'static str { + "self_sized" + } + + fn check(&self, file: &SourceFile) -> Vec { + if is_vendored(file) || owned_by(file, ALLOCATOR) { + return Vec::new(); + } + let turn_allocation = owned_by(file, TURN_ALLOCATION); + let mind_text = owned_by(file, MIND_TEXT) || MIND_TEXT_MODULES.iter().any(|module| file.rel.starts_with(module)); + sites(file, self.name(), |code| shape(code, turn_allocation, mind_text)) + } +} + +/// Which self-sizing shape `code` has, if any. +fn shape(code: &str, turn_allocation: bool, mind_text: bool) -> Option { + if let Some((name, _, value)) = numeric_const(code) { + if names_a_size(name) && is_bare_literal(value) { + return Some(format!("sized constant `{name}`")); + } + } + if let Some((left, right)) = constant_product(code) { + if names_a_size(left) || names_a_size(right) { + return Some(format!("product of constants `{left} * {right}`")); + } + } + if let Some(call) = BUDGET_FRACTIONS.iter().find(|c| code.contains(**c)) { + return Some(format!("a fraction of the window via `{call}`")); + } + if !turn_allocation { + if let Some(call) = ALLOCATOR_CALLS.iter().find(|c| code.contains(**c)) { + return Some(format!("an allocation outside the turn's one allocation via `{call}`")); + } + } + if mind_text { + if let Some(call) = HEAD_KEEPERS.iter().find(|c| code.contains(**c)) { + return Some(format!("a head cut via `{call}`")); + } + } + if let Some(call) = LITERAL_CEILINGS.iter().find(|c| literal_after(code, c)) { + return Some(format!("a literal ceiling via `{call}`")); + } + if names_a_size_in(code) && (literal_after(code, ".min(") || literal_clamp_ceiling(code)) { + return Some("a literal ceiling via `.min`/`.clamp`".to_owned()); + } + None +} + +/// Does this constant's name say it sizes something (and is not a duration)? +fn names_a_size(name: &str) -> bool { + SIZE_WORDS.iter().any(|w| name.contains(w)) && !is_duration_name(name) +} + +/// Does this line talk about a size (so a bare `.min(3)` on it is a ceiling)? +fn names_a_size_in(code: &str) -> bool { + let upper = code.to_ascii_uppercase(); + names_a_size(&upper) +} + +/// Is `call` (`.take(`, `channel(`, `channel::(`) given a literal? +fn literal_after(code: &str, call: &str) -> bool { + let direct = code.match_indices(call).any(|(at, _)| code[at + call.len()..].trim_start().starts_with(|c: char| c.is_ascii_digit())); + direct || call.strip_suffix('(').is_some_and(|name| turbofish_literal(code, &format!("{name}::<"))) +} + +/// `channel::(256)`: a literal capacity after a turbofish. +fn turbofish_literal(code: &str, call: &str) -> bool { + code.match_indices(call).any(|(at, _)| { + let rest = &code[at + call.len()..]; + rest.find(">(").is_some_and(|close| rest[close + 2..].trim_start().starts_with(|c: char| c.is_ascii_digit())) + }) +} + +/// `.clamp(low, N)` with a literal upper bound. +fn literal_clamp_ceiling(code: &str) -> bool { + code.match_indices(".clamp(").any(|(at, _)| { + let args = &code[at + ".clamp(".len()..]; + let Some(close) = args.find(')') else { return false }; + let Some((_, upper)) = args[..close].rsplit_once(',') else { return false }; + upper.trim_start().starts_with(|c: char| c.is_ascii_digit()) + }) +} diff --git a/core/source-hygiene/src/budget_discipline/tests.rs b/core/source-hygiene/src/budget_discipline/tests.rs new file mode 100644 index 0000000000..b44a6224a4 --- /dev/null +++ b/core/source-hygiene/src/budget_discipline/tests.rs @@ -0,0 +1,128 @@ +use super::*; +use crate::{scan, SourceRule}; + +/// A fixture at repository path `repo`, its `rel` the path under its crate's `src/` as the scan +/// would give it. +fn file(repo: &str, code: &str) -> SourceFile { + let rel = repo.split_once("/src/").map_or(repo, |(_, under)| under); + SourceFile { repo: repo.to_owned(), ..SourceFile::for_test(rel, code) } +} + +fn found(rule: &dyn SourceRule, repo: &str, code: &str) -> usize { + rule.check(&file(repo, code)).len() +} + +const CONSUMER: &str = "core/continuum-engine/src/ai/embedding/cache.rs"; +const MIND: &str = "core/continuum-cognition/src/cognition/recall.rs"; + +/// Count `rule` over the tree, hold it against the base, and judge the change's files. +fn judge(rule: &dyn SourceRule, instead: &str) { + let violations = scan(&[rule]); + let count = violations.len(); + let advice = || format!("{instead} The contract: docs/architecture/ONE-BUDGET.md."); + crate::ratchet::touched_clean(rule.name(), &violations, advice); + crate::ratchet::hold(rule.name(), count, || { + format!( + "{} {instead} The contract: docs/architecture/ONE-BUDGET.md.\nFirst {} of {count} (not necessarily new):\n{}", + rule.name(), + count.min(20), + violations.iter().take(20).map(|v| format!(" {}:{} {}", v.file, v.line, v.source)).collect::>().join("\n") + ) + }); +} + +// what this catches: a consumer sizing itself (cache caps, KEEP counts, window fractions, +// head cuts, literal ceilings) while the budget it bypasses believes it owns the resource. +#[test] +fn self_sized_consumers_fall_and_touched_files_have_none() { + judge(&SelfSized, "Take the size from the consumer's grant: claim it (floor = measured need, max = measured want) in the one allocation."); +} + +// what this catches: a second measurement of memory, VRAM or disk that disagrees with the +// authority's (five VRAM probes and seven RAM reads on 365f70fe4). +#[test] +fn private_probes_fall_and_touched_files_have_none() { + judge(&PrivateProbes, "Read the authority's published snapshot or your grant; never measure the resource yourself."); +} + +// what this catches: a writer choosing its own path and retention, so its bytes have no +// owner when the disk fills (460 GB on the M5, 2026-07-13). +#[test] +fn writes_outside_a_class_fall_and_touched_files_have_none() { + judge(&WritesOutsideAClass, "Write through the class handle for the directory (a TrackedDir with a claim) or through the ORM."); +} + +// what this catches: each self-sizing shape the inventory found, and the allocator and the +// turn's allocation staying quiet (a rule that flagged its owners would be deleted as noise). +#[test] +fn each_self_sizing_shape_is_found_and_owners_are_not() { + assert_eq!(found(&SelfSized, CONSUMER, "const EMBEDDING_CACHE_MAX: usize = 20_000;"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "pub(crate) const KEEP: usize = 8;"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "let cap = FILL_TARGET_SECONDS * PREFILL_TOKENS_PER_S;"), 0, "a time product is derived_bounds' class"); + assert_eq!(found(&SelfSized, CONSUMER, "let cap = LANE_COUNT_MAX * SLOT_BYTES;"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "let (tx, rx) = mpsc::channel(256);"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "let (tx, rx) = broadcast::channel::(1024);"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "rows.truncate(5);"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "let shown = budget_chars.min(1_500);"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "let n = retries.min(3);"), 0, "a .min on a line that names no size"); + assert_eq!(found(&SelfSized, CONSUMER, "let b = ContextBudget::live().trail_head_chars();"), 1); + assert_eq!(found(&SelfSized, MIND, "let head: String = text.chars().take(width).collect();"), 1); + assert_eq!(found(&SelfSized, CONSUMER, "let first = text.lines().next();"), 0, "a head read outside her text is parsing"); + assert_eq!(found(&SelfSized, MIND, "let grants = flex_allocate(window, &claims);"), 1); + assert_eq!( + found(&SelfSized, "core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs", "let grants = flex_allocate(window, &claims);"), + 0, + "the turn's allocation calls the allocator" + ); + assert_eq!(found(&SelfSized, "core/continuum-grounding/src/rag_budget/flex_allocate.rs", "const PRIORITY_MAX: u8 = 10;"), 0, "the allocator owns its algorithm"); + assert_eq!(found(&SelfSized, CONSUMER, "const POLL_INTERVAL_MS: u64 = 2_000;"), 0, "a duration is not a size"); + assert_eq!(found(&SelfSized, CONSUMER, "fn cap(&self) -> usize { self.grant.take(8) }"), 1, "a body on the signature's line is code (Codex on #5609)"); + assert_eq!(found(&SelfSized, CONSUMER, "pub fn recall_tokens(&self) -> usize {"), 0, "a signature alone is a definition, not a use"); + assert_eq!(found(&WritesOutsideAClass, CONSUMER, "fn save(p: &Path) -> io::Result<()> { std::fs::write(p, b\"x\") }"), 1, "every rule sees a one-line body"); + assert_eq!(found(&WritesOutsideAClass, CONSUMER, "std::fs::write(path, \"fn main() {}\")?;"), 1, "a fn inside a literal is not a signature (Codex on #5609)"); + assert_eq!(found(&WritesOutsideAClass, CONSUMER, r##"std::fs::write(path, r#"let source = "fn main() {}";"#)?;"##), 1, "nor inside a raw string with embedded quotes (Codex on #5609)"); + assert_eq!(found(&SelfSized, "core/vendored/llama/x.rs", "const N_CTX_MAX: usize = 4096;"), 0, "vendored upstream"); +} + +// what this catches: a private measurement outside the authority, and the authority's own +// probes staying quiet. +#[test] +fn a_private_probe_is_found_and_the_authority_is_not() { + assert_eq!(found(&PrivateProbes, CONSUMER, "let mut sys = sysinfo::System::new();"), 1); + assert_eq!(found(&PrivateProbes, CONSUMER, "let (free, total) = torch.cuda.mem_get_info();"), 1); + assert_eq!(found(&PrivateProbes, CONSUMER, "Command::new(\"nvidia-smi\")"), 1); + assert_eq!(found(&PrivateProbes, "core/continuum-kernel/src/system_resources/memory_pressure/poll.rs", "let mut sys = sysinfo::System::new();"), 0); + assert_eq!(found(&PrivateProbes, "core/continuum-kernel/src/gpu/monitor.rs", "Command::new(\"nvidia-smi\")"), 0); +} + +// what this catches: a write to a path the writer chose, and the ORM and the disk classes +// staying quiet. +#[test] +fn a_write_outside_a_class_is_found_and_the_owners_are_not() { + assert_eq!(found(&WritesOutsideAClass, CONSUMER, "std::fs::write(&path, bytes)?;"), 1); + assert_eq!(found(&WritesOutsideAClass, CONSUMER, "let f = File::create(path)?;"), 1); + assert_eq!(found(&WritesOutsideAClass, CONSUMER, "let f = OpenOptions::new().append(true).open(p)?;"), 1); + assert_eq!(found(&WritesOutsideAClass, "core/continuum-kernel/src/orm/sqlite/file.rs", "std::fs::write(&path, bytes)?;"), 0); + assert_eq!(found(&WritesOutsideAClass, CONSUMER, "let text = std::fs::read_to_string(p)?;"), 0, "a read is not a write"); +} + +// what this catches: the head-cut coverage `head_cuts` had and a crate list alone would lose +// (Codex on #5609): text a mind reads lives in these module directories in any crate. +#[test] +fn a_head_cut_is_found_in_every_directory_head_cuts_covered() { + let cut = "let spoken: String = text.chars().take(MAX_SPOKEN_CHARS).collect();"; + for repo in [ + "core/continuum-core/src/modules/voice_reply_speaker.rs", + "core/continuum-core/src/airc/relay.rs", + "core/continuum-genome/src/genome/teach/progress.rs", + "core/continuum-core/src/experience/lived.rs", + "core/continuum-core/src/recipe/loader.rs", + "core/continuum-core/src/positron/chat.rs", + "core/continuum-core/src/rag/engine.rs", + "core/continuum-core/src/persona/unified.rs", + "core/continuum-core/src/cognition/recall.rs", + ] { + assert_eq!(found(&SelfSized, repo, cut), 1, "{repo}"); + } + assert_eq!(found(&SelfSized, "core/continuum-engine/src/inference/lane_args.rs", cut), 0, "engine argv is not her text"); +} diff --git a/core/source-hygiene/src/budget_discipline/writes.rs b/core/source-hygiene/src/budget_discipline/writes.rs new file mode 100644 index 0000000000..d314c555c2 --- /dev/null +++ b/core/source-hygiene/src/budget_discipline/writes.rs @@ -0,0 +1,29 @@ +//! `writes_outside_a_class`: a file written to a path its writer chose. Every directory the +//! substrate fills is a class with a claim; the class owner resolves the continuum home, +//! hands out the path and turns its grant into retention. A writer that picks its own path, +//! rotation count or age is how 460 GB filled the M5 (2026-07-13) and how ~15 writers grow +//! without bound today (inventory on canary 365f70fe4). + +use super::{is_vendored, owned_by}; +use crate::{sites, SourceFile, SourceRule, Violation}; + +/// The owners of persistent bytes: the ORM (stores) and the disk classes. +const OWNERS: &[&str] = &["core/continuum-kernel/src/orm/", "core/continuum-kernel/src/system_resources/disk_reporters"]; + +/// The ways Rust code creates or appends to a file. +const WRITES: &[&str] = &["fs::write(", "File::create(", "OpenOptions::new()"]; + +pub struct WritesOutsideAClass; + +impl SourceRule for WritesOutsideAClass { + fn name(&self) -> &'static str { + "writes_outside_a_class" + } + + fn check(&self, file: &SourceFile) -> Vec { + if is_vendored(file) || owned_by(file, OWNERS) { + return Vec::new(); + } + sites(file, self.name(), |code| WRITES.iter().find(|w| code.contains(**w)).map(|w| format!("writes with `{w}`"))) + } +} diff --git a/core/source-hygiene/src/cognition_names_persona.rs b/core/source-hygiene/src/cognition_names_persona.rs index bbdc0c12a7..b43c5f5cca 100644 --- a/core/source-hygiene/src/cognition_names_persona.rs +++ b/core/source-hygiene/src/cognition_names_persona.rs @@ -10,7 +10,7 @@ //! Per line, so a pure move cannot change the count; only removing a coupling lowers it. //! Measured on canary a51bc55bd (2026-10-24): 108 lines in 34 files. The cut lands at 0. -use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; +use super::{lexer::split_code_and_comment, SourceFile, SourceRule, Violation}; pub struct CognitionNamesPersona; diff --git a/core/source-hygiene/src/context_codec.rs b/core/source-hygiene/src/context_codec.rs index da1e6153a0..ce49ab17cb 100644 --- a/core/source-hygiene/src/context_codec.rs +++ b/core/source-hygiene/src/context_codec.rs @@ -16,15 +16,9 @@ //! - `collapse_outside_the_view`: collapsing what she sees anywhere but a view start. Working //! memory bounds RAM by handle; the view decides what she reads. //! - `hand_churn_labels`: ordering sources by a label (`churn_of`) instead of measured motion. -//! - `prompt_self_sizing`: anything that decides how much content enters her prompt outside the -//! ONE flexbox allocation per turn (Joel, 2026-10-28: "We called this flexbox budgeting"; -//! "Others shrink. She still has all of the context. Requires adherence"). A source delivers -//! levels (whole, summary, pointer); the allocation's claims decide which she sees. Measured -//! at ~40 sites on 2026-10-28, including a second `flex_allocate` over the served window in -//! `compose_for_turn` (FLOW-IMPLEMENTATION-PLAN §2d). When it reaches 0 the sizing methods go -//! private and this ratchet is deleted. +//! - sizing what she sees outside the one allocation is `budget_discipline::SelfSized`'s class. -use super::{SourceFile, SourceRule, Violation}; +use super::{sites, SourceFile, SourceRule, Violation}; /// The prompt assembly, where every message must come from the view or the tail's renderer. const PROMPT_ASSEMBLY: &str = "cognition/llm_deliberation_faculty/prompt/"; @@ -32,45 +26,6 @@ const PROMPT_ASSEMBLY: &str = "cognition/llm_deliberation_faculty/prompt/"; struct PromptMessagesOutsideTheView; struct CollapseOutsideTheView; struct HandChurnLabels; -struct PromptSelfSizing; - -/// The one allocation's owners: the prompt assembly runs it; `context_budget.rs` and the -/// allocator module define what it uses. -const ALLOCATION_OWNERS: [&str; 3] = [PROMPT_ASSEMBLY, "cognition/context_budget.rs", "cognition/rag_budget/"]; - -/// Calls that size prompt content on their own: the `ContextBudget` entry points and fraction -/// methods, the fixed share splits, and a second run of the flexbox. -const SELF_SIZING: [&str; 22] = [ - "ContextBudget::live(", - "ContextBudget::live_or_floor(", - "ContextBudget::from_window(", - "ContextBudget::from_window_for(", - "ContextBudget::from_window_unbounded(", - ".recall_tokens(", - ".grounding_tokens(", - ".tool_surface_tokens(", - ".latest_action_chars(", - ".dispatch_result_chars(", - ".render_slice_chars(", - ".catalog_summary_chars(", - ".echoed_arg_chars(", - ".trail_head_chars(", - ".recent_results_chars(", - ".receipt_archive_chars(", - ".default_response_tokens(", - "_SHARE_DENOM", - "budget_claim(", - "FlexboxRagBudgetAdapter::new(", - "adapter.allocate(", - "flex_allocate(", -]; - -fn sites(file: &SourceFile, rule: &'static str, hit: impl Fn(&str) -> bool) -> Vec { - file.production_lines() - .filter(|(_, l)| hit(crate::split_code_and_comment(l).0)) - .map(|(n, l)| Violation { rule, file: file.rel.clone(), line: n, source: l.trim().to_string() }) - .collect() -} impl SourceRule for PromptMessagesOutsideTheView { fn name(&self) -> &'static str { @@ -81,7 +36,9 @@ impl SourceRule for PromptMessagesOutsideTheView { if !file.rel.starts_with(PROMPT_ASSEMBLY) { return Vec::new(); } - sites(file, self.name(), |code| code.contains("ChatMessage::text(") || code.contains("ChatMessage::tool_results(")) + sites(file, self.name(), |code| { + (code.contains("ChatMessage::text(") || code.contains("ChatMessage::tool_results(")).then(|| "a message pushed by hand".to_owned()) + }) } } @@ -92,7 +49,7 @@ impl SourceRule for CollapseOutsideTheView { fn check(&self, file: &SourceFile) -> Vec { sites(file, self.name(), |code| { - !code.contains("fn ") && (code.contains(".collapse_over(") || code.contains("collapse_results_over_cap()")) + (code.contains(".collapse_over(") || code.contains("collapse_results_over_cap()")).then(|| "a collapse outside the view".to_owned()) }) } } @@ -103,20 +60,7 @@ impl SourceRule for HandChurnLabels { } fn check(&self, file: &SourceFile) -> Vec { - sites(file, self.name(), |code| code.contains("churn_of(") && !code.contains("fn churn_of(")) - } -} - -impl SourceRule for PromptSelfSizing { - fn name(&self) -> &'static str { - "prompt_self_sizing" - } - - fn check(&self, file: &SourceFile) -> Vec { - if ALLOCATION_OWNERS.iter().any(|owner| file.rel.starts_with(owner)) || !file.rel.starts_with("cognition/") && !file.rel.starts_with("persona/") { - return Vec::new(); - } - sites(file, self.name(), |code| !code.contains("fn ") && SELF_SIZING.iter().any(|call| code.contains(call))) + sites(file, self.name(), |code| code.contains("churn_of(").then(|| "an order by label".to_owned())) } } @@ -160,13 +104,6 @@ mod tests { hold(&HandChurnLabels, "The view orders a start by measured motion (continuum_context::motion)."); } - // what this catches: content sized outside the one flexbox allocation (Aiko turned over every act - // while ~40 sites sized for 159k and the prompt fit 48k, M5 2026-10-28). It may only fall. - #[test] - fn prompt_self_sizing_never_increases() { - hold(&PromptSelfSizing, "Deliver levels (whole, summary, pointer) and make the content a claim in the one allocation in prompt/view.rs; never size it at the source."); - } - // what this catches: the predicates that make the rules useful rather than noise. #[test] fn each_rule_catches_its_shape_and_spares_its_definition() { @@ -177,10 +114,6 @@ mod tests { assert_eq!(count(&CollapseOutsideTheView, "cognition/wm.rs", "self.collapse_results_over_cap();"), 1); assert_eq!(count(&CollapseOutsideTheView, "cognition/wm.rs", "pub fn collapse_over(&mut self, cap: usize) -> Collapsed {"), 0); assert_eq!(count(&HandChurnLabels, "cognition/a.rs", "churn_of(&block.faculty) < PromptChurn::Claims"), 1); - assert_eq!(count(&PromptSelfSizing, "cognition/recall_faculty.rs", "ContextBudget::from_window(context_window).recall_tokens()"), 1); - assert_eq!(count(&PromptSelfSizing, "persona/unified.rs", "let plan = adapter.allocate(&claims, budget);"), 1); - assert_eq!(count(&PromptSelfSizing, "cognition/llm_deliberation_faculty/prompt/view.rs", "let plan = flex_allocate(window, &claims);"), 0); - assert_eq!(count(&PromptSelfSizing, "cognition/context_budget.rs", "pub fn recall_tokens(&self) -> usize {"), 0); assert_eq!(count(&HandChurnLabels, "cognition/a.rs", "pub(super) fn churn_of(faculty: &str) -> PromptChurn {"), 0); } } diff --git a/core/source-hygiene/src/continuum_home.rs b/core/source-hygiene/src/continuum_home.rs index 9ae6b8f958..cea3859cdf 100644 --- a/core/source-hygiene/src/continuum_home.rs +++ b/core/source-hygiene/src/continuum_home.rs @@ -25,7 +25,7 @@ pub struct ContinuumHomeResolvedOnce; /// The code of a line, strings intact: the scanner's one string-aware split, so a `//` /// inside `"http://…"` is never read as a comment (Astra on #5196). fn code(line: &str) -> &str { - super::split_code_and_comment(line).0 + super::lexer::split_code_and_comment(line).0 } /// Whether the code at `i` joins `.continuum` onto a path by hand, including a `.join(` diff --git a/core/source-hygiene/src/crate_wiring.rs b/core/source-hygiene/src/crate_wiring.rs index 994161cd7a..622e31bd39 100644 --- a/core/source-hygiene/src/crate_wiring.rs +++ b/core/source-hygiene/src/crate_wiring.rs @@ -50,7 +50,7 @@ pub fn policy_gaps(repo: &Path, members: &[Member], policy: &Policy) -> Vec Vec bool { - crate::collect_files(src).iter().any(|file| file.raw.contains("#[test]") || file.raw.contains("#[tokio::test")) +/// Whether the crate at `core/` declares any test in its `src/`. +pub fn has_tests(repo: &Path, dir: &str) -> bool { + crate::collect_files(repo, &format!("core/{dir}/src")).iter().any(|file| file.raw.contains("#[test]") || file.raw.contains("#[tokio::test")) } /// The quoted strings of `"key":[...]` in the selector's `crate-sets` JSON line. diff --git a/core/source-hygiene/src/derived_bounds.rs b/core/source-hygiene/src/derived_bounds.rs deleted file mode 100644 index e9db136cf2..0000000000 --- a/core/source-hygiene/src/derived_bounds.rs +++ /dev/null @@ -1,424 +0,0 @@ -//! **A clip is DERIVED from a measurement, or it is a NAMED FLOOR that says so.** -//! -//! # The class -//! -//! Four defects of one shape surfaced in a single night (2026-09-19/20), each a static -//! number standing in for a measurement the substrate already takes: -//! -//! | The constant | What it cost | -//! |---|---| -//! | a 768-token output-allowance floor (#4194) | turns ENDED INSIDE the reasoning channel — the mind never reached its answer | -//! | the KV cache type defaulting to `f16` | halved the usable context on two of three boxes | -//! | a flat 10 s KV-page wedge bound, sized from the M5's 0.1 s (#4287) | cut off legitimate page saves on the 5090 | -//! | `PREFILL_TARGET_SECONDS × CONSERVATIVE_PREFILL_TOKENS_PER_S` | a flat 15,000-token conversation fill on every machine; the 500 t/s half was 5–20× what any box in the fleet prefills, so the clip failed its own 30 s purpose everywhere WHILE taking 27% of a 67,072-token lane away from its holder | -//! -//! Joel's standing instruction, the design constraint for this whole module: *static -//! clips and fallbacks silently destroy the system and then we do forensics.* Every one -//! of the four compiled, had passing tests, and was invisible until someone measured. -//! -//! # Why this guard and not the one that already exists -//! -//! `cognition::context_budget`'s de-hardcode guard is a WALL over constants whose NAME -//! says window/context/token/prompt/chars, exempted line-by-line with -//! `context-budget-exempt:`. It is load-bearing and stays. It did not catch this class -//! for two reasons, and this rule is exactly those two reasons: -//! -//! 1. **It cannot see a PRODUCT.** Both halves of `30 × 500` were individually exempted, -//! in good faith, each with a true sentence about itself — and their product was a -//! bound nothing had ever measured. [`ConstantProduct`] below is that shape: a -//! constant multiplied by a constant is a bound with no measurement in it. -//! 2. **Its vocabulary stops at size.** Time and RATE are the units this class actually -//! hides in — `_SECONDS`, `_SECS`, `_MS`, `_PER_S`, `_TPS` — and `_MS` is explicitly -//! excluded there as "categorically not a size bound". True, and beside the point: a -//! seconds constant times a measured rate is fine, a seconds constant standing in FOR -//! a rate is the defect. -//! -//! # What it asks -//! -//! A bound on a live path is either derived from something the substrate measures, or it -//! carries a `derived-or-floor:` justification naming why a constant is the right answer -//! THERE — a floor that only ever raises a budget, a protocol's own stated requirement, a -//! physical unit, a product latency intent. The marker may sit on the same line or in the -//! contiguous comment block directly above the declaration, because a reason worth -//! writing rarely fits after a semicolon. -//! -//! # A ratchet, not a wall -//! -//! There are 160-odd of these in tree and most are fine. A guard that demanded all of -//! them today would fail forever and be `#[ignore]`d inside a week — the documented fate -//! of every rule that lives in prose. So: **the count may never rise.** Every new bound -//! arrives derived or justified, and every old one anybody touches is a chance to lower -//! the count the ratchet holds. - -use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; - -/// The marker a constant spends to say it is deliberately a constant. -pub const JUSTIFICATION_MARKER: &str = "derived-or-floor:"; - -/// A justification has to say something. Same bar, and the same reasoning, as the unwrap -/// ratchet's [`super::unwrap_justification`]: a marker with nothing after it is the SHAPE -/// of a reason, which is worse than no marker at all because it silences the guard. -// derived-or-floor: a FLOOR on the length of a COMMENT a human types — it bounds prose, never a token, a second or a rate, and there is nothing here to measure -// context-budget-exempt: this bounds the length of a COMMENT, not a window, prompt or -// token budget — the de-hardcode guard matches it on the `CHARS` suffix alone, which is -// that guard erring toward noise on purpose (same exemption its sibling in -// `unwrap_justification` spends, for the same reason). -const MIN_REASON_CHARS: usize = 16; - -/// The trees a live cognition / serving turn actually runs through. Violations are raised -/// only here: `audio_constants.rs` and the video renderer are full of constants that are -/// PHYSICS (a sample rate, a frame budget), and flagging them would bury the findings -/// that matter under noise — the way a guard earns being deleted. -const LIVE_PATHS: &[&str] = &[ - "cognition/", - "inference/", - "persona/", - "governor/", - "paging/", - "runtime/", - "capacity/", - "system_resources/", -]; - -/// Name fragments that say a constant IS a bound, whatever its units. -const BOUND_WORDS: &[&str] = &[ - "CAP", - "BOUND", - "LIMIT", - "MAX", - "MIN", - "FLOOR", - "CEILING", - "BUDGET", - "TIMEOUT", - "DEADLINE", - "THRESHOLD", - "TARGET", - "QUOTA", - "RESERVE", - "ALLOWANCE", - "INTERVAL", - "CADENCE", -]; - -/// Units the substrate MEASURES — tokens, seconds, milliseconds, tokens-per-second. A -/// constant in one of these units is standing where a measurement could stand. -const MEASURED_UNITS: &[&str] = &["_PER_S", "_TPS", "_SECONDS", "_SECS", "_MS", "_TOKENS", "TOKENS_"]; - -/// Numeric types a bound can wear. A `&str`, a `bool` or a `Duration` named `..._MAX` is -/// not a quantity this rule can reason about. -const NUMERIC_TYPES: &[&str] = &[ - "u8", "u16", "u32", "usize", "u64", "i32", "i64", "f32", "f64", -]; - -pub struct DerivedBounds; - -impl DerivedBounds { - /// Is `token` a SCREAMING_SNAKE constant name? At least one underscore, so a type - /// (`Duration`) or a single-letter generic is never mistaken for one. - fn is_constant(token: &str) -> bool { - token.len() >= 3 - && token.contains('_') - && token.starts_with(|c: char| c.is_ascii_uppercase()) - && token - .chars() - .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') - } - - /// `CONST_A * CONST_B` on this line — a bound assembled from constants alone, with - /// no measurement anywhere in it. Returns the two names. - /// - /// A constant times a LITERAL (`MIN_SERVE_CTX * 8`) is deliberately NOT this shape: - /// it is a derivation from a named bound, which the de-hardcode guard already blesses - /// and which keeps one owner for the number. - fn constant_product<'a>(code: &'a str) -> Option<(&'a str, &'a str)> { - let bytes = code.as_bytes(); - for (i, c) in code.char_indices() { - if c != '*' { - continue; - } - // `**`, `*/`, `/*` are not multiplication; nor is `*mut` / `*const`, whose - // keywords are lowercase and so can never be constant names. - if bytes.get(i + 1).is_some_and(|b| *b == b'*' || *b == b'/') { - continue; - } - if i > 0 && (bytes[i - 1] == b'*' || bytes[i - 1] == b'/') { - continue; - } - let left = Self::trailing_identifier(&code[..i]); - let right = Self::leading_identifier(&code[i + 1..]); - if let (Some(l), Some(r)) = (left, right) { - if Self::is_constant(l) && Self::is_constant(r) { - return Some((l, r)); - } - } - } - None - } - - fn trailing_identifier<'a>(before: &'a str) -> Option<&'a str> { - let t = before.trim_end(); - let start = t - .char_indices() - .rev() - .take_while(|(_, c)| c.is_alphanumeric() || *c == '_') - .last() - .map(|(i, _)| i)?; - Some(&t[start..]) - } - - fn leading_identifier<'a>(after: &'a str) -> Option<&'a str> { - let t = after.trim_start(); - let end = t - .char_indices() - .take_while(|(_, c)| c.is_alphanumeric() || *c == '_') - .last() - .map(|(i, c)| i + c.len_utf8())?; - Some(&t[..end]) - } - - /// `(name, type, value)` if this line declares a numeric constant. - fn const_declaration<'a>(code: &'a str) -> Option<(&'a str, &'a str, &'a str)> { - let trimmed = code.trim_start(); - // Visibility does not change whether a declaration is a numeric constant. - // Restricted visibility includes pub(in crate::owner), not only crate/super. - let declaration = if let Some(restricted) = trimmed.strip_prefix("pub(") { - restricted.split_once(')')?.1.trim_start() - } else if let Some(public) = trimmed.strip_prefix("pub ") { - public.trim_start() - } else { - trimmed - }; - let rest = declaration.strip_prefix("const ")?; - let (name, tail) = rest.split_once(':')?; - let (ty, value) = tail.split_once('=')?; - let ty = ty.trim(); - if !NUMERIC_TYPES.contains(&ty) { - return None; - } - Some((name.trim(), ty, value.trim().trim_end_matches(';').trim())) - } - - /// Does this constant's NAME say it is a bound, or that it carries a unit the - /// substrate measures? - fn names_a_bound(name: &str) -> bool { - BOUND_WORDS.iter().any(|w| name.contains(w)) - || MEASURED_UNITS.iter().any(|u| name.contains(u)) - } - - /// A value the compiler reads as a fresh guess: a bare decimal or float literal. An - /// expression over another named bound is a derivation and passes. - fn is_bare_literal(value: &str) -> bool { - !value.is_empty() - && value.starts_with(|c: char| c.is_ascii_digit()) - && value - .chars() - .all(|c| c.is_ascii_digit() || c == '_' || c == '.') - } - - /// Does the marker appear with a real reason after it — on this line, or in the - /// contiguous comment block directly above it? - /// - /// The block-above form exists because a `const` carries a doc comment, not a - /// trailing one; the same allowance the de-hardcode guard makes, for the same reason. - fn justified(lines: &[&str], index: usize) -> bool { - let reason_on = |text: &str| { - text.split_once(JUSTIFICATION_MARKER) - .is_some_and(|(_, why)| why.trim().chars().count() >= MIN_REASON_CHARS) - }; - if let Some(comment) = split_code_and_comment(lines[index]).1 { - if reason_on(comment) { - return true; - } - } - lines[..index] - .iter() - .rev() - .take_while(|l| { - let t = l.trim_start(); - t.starts_with("//") || t.is_empty() - }) - .any(|l| reason_on(l)) - } -} - -impl SourceRule for DerivedBounds { - fn name(&self) -> &'static str { - "derived-or-justified-bound" - } - - fn check(&self, file: &SourceFile) -> Vec { - // Vendored upstream ports carry the upstream model's own numbers; they are not - // ours to restyle. - if file.rel.contains("vendored/") { - return Vec::new(); - } - let lines: Vec<&str> = file.raw.lines().collect(); - let live = LIVE_PATHS.iter().any(|p| file.rel.starts_with(p)); - let mut out = Vec::new(); - for (line_no, line) in file.production_lines() { - let (code, _) = split_code_and_comment(line); - if Self::justified(&lines, line_no - 1) { - continue; - } - // A constant times a constant is the shape wherever it appears — it needs no - // live-path test, because it IS the defect this guard was written for. - if let Some((l, r)) = Self::constant_product(code) { - out.push(Violation { - rule: "derived-or-justified-bound", - file: file.rel.clone(), - line: line_no, - source: format!("{l} * {r} — a bound with no measurement in it"), - }); - continue; - } - if !live { - continue; - } - if let Some((name, ty, value)) = Self::const_declaration(code) { - if Self::names_a_bound(name) && Self::is_bare_literal(value) { - out.push(Violation { - rule: "derived-or-justified-bound", - file: file.rel.clone(), - line: line_no, - source: format!("const {name}: {ty} = {value}"), - }); - } - } - } - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::scan; - - /// What this catches: a new bound landing on a live path as a constant, with nothing - /// measured behind it and no line saying why a constant is right there. - /// - /// A RATCHET, not a wall — see the module header. If this fails because you added - /// one: derive it from what the substrate already measures - /// (`inference::prefill_rate`, `inference::decode_knee`, `cognition::working_set`, - /// `ContextBudget`), or write `derived-or-floor: ` and say what makes a constant - /// correct THERE. If it fails because you derived one that used to be a constant, - /// the ratchet then holds the lower count. - #[test] - fn underived_unjustified_bounds_never_increase() { - let violations = scan(&[&DerivedBounds]); - let count = violations.len(); - crate::ratchet::hold("underived_bounds", count, || { - format!( - "underived, unjustified bounds rose to {count}.\n\ - \n\ - THE CLASS: a constant standing in for a measurement the substrate already \ - takes. A 768-token output floor ended turns INSIDE the reasoning channel \ - (#4194); a KV cache type defaulting to f16 halved the context on two of \ - three boxes; a 10 s page-wedge bound sized from the M5's 0.1 s cut off \ - legitimate saves on the 5090 (#4287); and `PREFILL_TARGET_SECONDS × \ - CONSERVATIVE_PREFILL_TOKENS_PER_S` clipped every machine's conversation to \ - a flat 15,000 tokens with a 500 t/s assumption no box in the fleet has ever \ - met. Each compiled, each passed its tests, each was found by forensics.\n\ - \n\ - THE FIX: derive it. The measurements exist — `inference::prefill_rate` \ - (prefill t/s, with the fresh → stale → conservative ladder), \ - `inference::decode_knee` (decode t/s), `cognition::working_set` (her \ - measured need), `ContextBudget` (fractions of the SERVED window). If a \ - constant genuinely is right there — a floor that only ever raises a budget, \ - a protocol's stated requirement, a physical unit, a product latency intent \ - — say so on the line or in the comment block above it:\n\ - \x20 // {JUSTIFICATION_MARKER} a FLOOR — \n\ - \n\ - This scan cannot tell new from old. To find yours: diff against your base \ - and look for added `const` lines on cognition/inference/persona/governor/\ - paging/runtime/capacity/system_resources paths, or a `CONST * CONST` \ - product anywhere.\n\ - First {} of {count} in tree order (NOT necessarily new):\n{}", - violations.len().min(15), - violations - .iter() - .take(15) - .map(|v| format!(" {}:{} {}", v.file, v.line, v.source)) - .collect::>() - .join("\n") - ) - }); - } - - /// What this catches: the guard going blind to the exact line it was written for. - /// - /// `cognition/llm_deliberation_faculty.rs` gated a test-only helper `#[cfg(test)]` - /// INSIDE an `impl`, above the clip. A production split that cut at the first - /// `#[cfg(test)]` anywhere reported nothing below it; the shared split cuts at column - /// zero, where a test mod lives. - #[test] - fn a_mid_file_cfg_test_helper_does_not_blind_the_scan() { - let raw = "impl Faculty {\n #[cfg(test)]\n fn helper() {}\n}\n\ - let cap = TARGET_SECONDS * CONSERVATIVE_TOKENS_PER_S;\n\ - #[cfg(test)]\nmod tests {}\n"; - let file = SourceFile { - rel: "cognition/llm_deliberation_faculty.rs".into(), - production: crate::production_half(raw), - raw: raw.into(), - }; - let found = DerivedBounds.check(&file); - assert_eq!(found.len(), 1, "the clip below an indented #[cfg(test)] must still be seen"); - assert!(found[0].source.contains("TARGET_SECONDS * CONSERVATIVE_TOKENS_PER_S")); - assert_eq!(found[0].line, 5); - assert!(!file.production.contains("mod tests"), "the column-zero test mod ends production"); - } - - /// What this catches: the two predicates that decide whether this rule is useful or - /// noise. A rule that flagged `MIN_SERVE_CTX * 8` would punish the one derivation - /// shape the codebase wants; a rule that a bare `// derived-or-floor:` satisfied - /// would report zero forever while the substrate filled up with guesses. - #[test] - fn a_named_derivation_passes_and_a_token_marker_does_not() { - let mk = |raw: &str| SourceFile { - rel: "cognition/x.rs".into(), - production: raw.into(), - raw: raw.into(), - }; - // A constant times a LITERAL is a derivation from a named bound. - assert!(DerivedBounds.check(&mk("const A: u32 = MIN_SERVE_CTX * 8;")).is_empty()); - // A constant times a CONSTANT is not. - assert_eq!(DerivedBounds.check(&mk("let c = A_SECONDS * B_TOKENS_PER_S;")).len(), 1); - // A live-path bound with a bare literal and nothing said about it. - assert_eq!(DerivedBounds.check(&mk("const FILL_CAP_TOKENS: usize = 15_000;")).len(), 1); - // Regression for #5227: restricting visibility must not hide the same bound. - for visibility in ["pub", "pub(crate)", "pub(super)", "pub(self)", "pub(in crate::owner)"] { - let raw = format!("{visibility} const FILL_CAP_TOKENS: usize = 15_000;"); - assert_eq!(DerivedBounds.check(&mk(&raw)).len(), 1, "{visibility}"); - } - // The same, derived from a measurement or another named bound: fine. - assert!(DerivedBounds - .check(&mk("const FILL_CAP_TOKENS: usize = BOOTSTRAP_WORKING_SET as usize;")) - .is_empty()); - // A marker with nothing after it is the shape of a reason, not a reason. - assert_eq!( - DerivedBounds - .check(&mk("const FILL_CAP_TOKENS: usize = 15_000; // derived-or-floor: ok")) - .len(), - 1 - ); - // A real reason, same line or in the block above. - assert!(DerivedBounds - .check(&mk( - "const FILL_CAP_TOKENS: usize = 15_000; // derived-or-floor: a FLOOR, it only ever raises a budget" - )) - .is_empty()); - assert!(DerivedBounds - .check(&mk( - "// derived-or-floor: the protocol's own stated maximum, not ours to choose\nconst FRAME_MAX_TOKENS: usize = 15_000;" - )) - .is_empty()); - // Off a live path, a bare bound constant is not this rule's business. - let elsewhere = SourceFile { - rel: "audio_constants.rs".into(), - production: "const SILENCE_THRESHOLD_MS: u64 = 704;".into(), - raw: "const SILENCE_THRESHOLD_MS: u64 = 704;".into(), - }; - assert!(DerivedBounds.check(&elsewhere).is_empty()); - } -} diff --git a/core/source-hygiene/src/dev_only_deps.rs b/core/source-hygiene/src/dev_only_deps.rs index a605fd63ff..2989ec6fd0 100644 --- a/core/source-hygiene/src/dev_only_deps.rs +++ b/core/source-hygiene/src/dev_only_deps.rs @@ -18,7 +18,7 @@ use std::collections::BTreeSet; use std::path::Path; -use crate::{collect_files, split_code_and_comment, SourceFile, Violation}; +use crate::{lexer::split_code_and_comment, collect_files, SourceFile, Violation}; /// The crates a manifest declares, by the name code uses for them (`-` becomes `_`). #[derive(Debug, Default, PartialEq, Eq)] @@ -232,7 +232,7 @@ fn test_regions(file: &SourceFile) -> (Vec, Vec) { } else { let mut item = lines[head..].to_vec(); item[0] = code; - head + crate::gated_item_end(&item, 0) + head + crate::lexer::gated_item_end(&item, 0) }; test_only[i..=end].iter_mut().for_each(|t| *t = true); i = end + 1; @@ -289,7 +289,7 @@ pub fn workspace_violations(repo: &Path) -> (usize, Vec) { }; scanned += 1; let name = entry.file_name().to_string_lossy().into_owned(); - out.extend(violations_in(&name, &DeclaredCrates::parse(&manifest), &collect_files(&dir.join("src")))); + out.extend(violations_in(&name, &DeclaredCrates::parse(&manifest), &collect_files(repo, &format!("{group}/{name}/src")))); } } (scanned, out) diff --git a/core/source-hygiene/src/head_cuts.rs b/core/source-hygiene/src/head_cuts.rs deleted file mode 100644 index a63f1eba69..0000000000 --- a/core/source-hygiene/src/head_cuts.rs +++ /dev/null @@ -1,171 +0,0 @@ -//! **Text bound for her prompt never loses its newest end, and never shrinks by a literal.** -//! -//! # The class -//! -//! A cut that keeps the START of text drops what happened last: the latest message, the -//! result she just got, the outcome at the end of a log. She then acts on a world where -//! time and causality never moved forward, and loops or hangs (Joel, 2026-10-20). And one -//! source that shrinks itself by its own number breaks the whole budget, because the -//! budget no longer accounts for what the prompt holds. The sweep that day found ~30: -//! a per-message `.clamp(48, 256)` in room history, `first line at 140` and `800 chars` -//! on recalled acts, `chars().take(cap) + "…[truncated]"` on command results, a 12-card -//! board, `.min(1_500)` on her own work turns. -//! -//! # What it asks -//! -//! On the paths that render her prompt, text shrinks only through the one budget, oldest -//! first, collapsed to a handle she can expand (`Contribution::with_parts` + -//! `grounding_plan` + `expand_command`, or `tool_executor::spill`), keeping the newest end. -//! A cut that is NOT prompt text (a log label, a file name in a probe) says so with -//! `head-cut-ok: ` on its line or in the comment block above. -//! -//! # A ratchet -//! -//! The count may only fall; the ratchet holds the base tree's count. - -use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; - -/// The marker a cut spends to say it never reaches a prompt. -pub const JUSTIFICATION_MARKER: &str = "head-cut-ok:"; - -/// A reason has to say something (the same bar as `derived-or-floor:`). -// derived-or-floor: bounds the length of a comment a human types, never a token, a second or a rate -// context-budget-exempt: bounds a COMMENT's length, not a prompt; matched on the CHARS suffix alone -const MIN_REASON_CHARS: usize = 16; - -/// The trees that render what a mind reads. -const PROMPT_PATHS: &[&str] = &["cognition/", "persona/", "genome/", "rag/", "modules/", "airc/", "positron/", "experience/", "recipe/"]; - -/// Cuts that keep a head whatever bounds them. -const HEAD_KEEPERS: &[&str] = &[".chars().take(", "head_to_tokens(", "truncate_chars(", ".lines().next()"]; - -/// Shrinking calls that take a literal size: a ceiling no budget decided. -const LITERAL_CEILINGS: &[&str] = &[".take(", ".truncate(", "[.."]; - -/// A literal `.min(N)` / `.clamp(_, N)` is a size ceiling only beside a size word; without -/// one it is arithmetic (a backoff exponent, a percentage), which this rule must not flag. -const SIZE_WORDS: &[&str] = &["cap", "char", "token", "len", "budget", "share", "limit", "max"]; - -pub struct HeadCuts; - -impl HeadCuts { - /// `call` followed (after spaces) by a decimal digit: a size written into the code. - fn literal_after(code: &str, call: &str) -> bool { - code.match_indices(call).any(|(i, _)| { - code[i + call.len()..].trim_start().starts_with(|c: char| c.is_ascii_digit()) - }) - } - - /// `.clamp(a, N)` with a literal upper bound. - fn literal_clamp_ceiling(code: &str) -> bool { - code.match_indices(".clamp(").any(|(i, _)| { - let args = &code[i + ".clamp(".len()..]; - let Some(close) = args.find(')') else { return false }; - let Some((_, upper)) = args[..close].rsplit_once(',') else { return false }; - upper.trim_start().starts_with(|c: char| c.is_ascii_digit()) - }) - } - - fn cut(code: &str) -> Option<&'static str> { - if let Some(k) = HEAD_KEEPERS.iter().find(|k| code.contains(**k)) { - return Some(k); - } - if let Some(c) = LITERAL_CEILINGS.iter().find(|c| Self::literal_after(code, c)) { - return Some(c); - } - let lower = code.to_ascii_lowercase(); - if !SIZE_WORDS.iter().any(|w| lower.contains(w)) { - return None; - } - if Self::literal_after(code, ".min(") { - return Some(".min(N)"); - } - Self::literal_clamp_ceiling(code).then_some(".clamp(_, N)") - } - - /// The marker on this line or in the contiguous comment block above it. - fn justified(lines: &[&str], idx: usize) -> bool { - let says = |l: &str| { - l.find(JUSTIFICATION_MARKER) - .is_some_and(|at| l[at + JUSTIFICATION_MARKER.len()..].trim().chars().count() >= MIN_REASON_CHARS) - }; - if lines.get(idx).is_some_and(|l| says(l)) { - return true; - } - lines[..idx] - .iter() - .rev() - .take_while(|l| l.trim_start().starts_with("//")) - .any(|l| says(l)) - } -} - -impl SourceRule for HeadCuts { - fn name(&self) -> &'static str { - "head-cut" - } - - fn check(&self, file: &SourceFile) -> Vec { - if !PROMPT_PATHS.iter().any(|p| file.rel.starts_with(p)) { - return Vec::new(); - } - let lines: Vec<&str> = file.raw.lines().collect(); - file.production_lines() - .filter_map(|(line_no, line)| { - let (code, _) = split_code_and_comment(line); - let cut = Self::cut(code)?; - (!Self::justified(&lines, line_no - 1)).then(|| Violation { - rule: "head-cut", - file: file.rel.clone(), - line: line_no, - source: format!("{cut} {}", code.trim()), - }) - }) - .collect() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::scan; - - /// What this catches: a new cut on a prompt path that keeps the head of text or - /// shrinks it by a literal, the shape that hides her newest message or result. - #[test] - fn head_cuts_on_prompt_paths_never_increase() { - let violations = scan(&[&HeadCuts]); - let count = violations.len(); - crate::ratchet::hold("head_cuts", count, || { - format!( - "head cuts on prompt paths rose to {count}.\n\ - A cut that keeps the start drops the newest end, and she acts as if time never \ - moved. Shrink through the one budget, oldest first, to a handle she can expand \ - (Contribution::with_parts + grounding_plan, or tool_executor::spill). If this \ - text never reaches a prompt: `// {JUSTIFICATION_MARKER} `.\n\ - First {} of {count} (not necessarily new):\n{}", - count.min(20), - violations.iter().take(20).map(|v| format!(" {}:{} {}", v.file, v.line, v.source)).collect::>().join("\n") - ) - }); - } - - /// What this catches: the predicates that make the rule useful rather than noise. A - /// budget-derived bound with no head-keeping call is fine; a literal ceiling, a head - /// keeper and a literal clamp are each caught; a real reason silences one; a bare - /// marker does not. - #[test] - fn literals_and_head_keepers_are_caught_and_a_reason_silences_one() { - let check = |rel: &str, src: &str| HeadCuts.check(&SourceFile::for_test(rel, src)).len(); - assert_eq!(check("persona/a.rs", "let n = items.len().min(share);"), 0); - assert_eq!(check("persona/a.rs", "items.truncate(5);"), 1); - assert_eq!(check("persona/a.rs", "let s: String = body.chars().take(cap).collect();"), 1); - assert_eq!(check("persona/a.rs", "let cap = (budget / 8).clamp(48, 256);"), 1); - assert_eq!(check("persona/a.rs", "let head = &s[..197];"), 1); - assert_eq!(check("persona/a.rs", "let keep = self.budget().trail_head_chars().min(1_500);"), 1); - assert_eq!(check("airc/a.rs", "let mult = 1u32 << failed_attempts.min(10);"), 0, "arithmetic, not a size"); - assert_eq!(check("audio/a.rs", "items.truncate(5);"), 0, "not a prompt path"); - assert_eq!(check("persona/a.rs", "// head-cut-ok: a probe label, never prompt text\nlabel.truncate(40);"), 0); - assert_eq!(check("persona/a.rs", "label.truncate(40); // head-cut-ok:"), 1, "a bare marker is not a reason"); - } -} diff --git a/core/source-hygiene/src/lexer.rs b/core/source-hygiene/src/lexer.rs new file mode 100644 index 0000000000..6606755fce --- /dev/null +++ b/core/source-hygiene/src/lexer.rs @@ -0,0 +1,643 @@ +//! The lexer every rule shares: which lines of a file are production code, where a line's +//! code ends and its comment begins, and how a line moves brace depth. One owner, so two +//! rules never disagree about the same file. + +/// The PRODUCTION half of a source file (see [`crate::SourceFile::production`]): every line +/// not gated by a `#[cfg(test)]` that is CODE, not prose. Matching the raw string +/// would truncate at the first doc comment that merely MENTIONS test-gating, and module +/// headers in this crate do exactly that, including this one. Found by the guard's own +/// positive control: the naive form excluded nearly all of `source_hygiene/mod.rs` from +/// its own scan, silently. Match by nature, never by name. +/// +/// A file that IS a test module, moved out of its parent to shrink it, says so with the +/// inner `#![cfg(test)]` on its first code line: the whole file is test code. Without +/// this, every `mod tests;` split read as all-production and charged its unwraps and +/// spawns to the ratchets (card 0af5d5ec, 2026-10-18). +/// +/// A COLUMN-ZERO `#[cfg(test)]` gates one file-scope item: that item is test code and +/// nothing else is. An indented `#[cfg(test)]` (a test-only helper inside an `impl`) is +/// scanned as production, erring toward noise: cut there, `cognition/llm_deliberation_faculty.rs` +/// hid ~9,000 production lines from every ratchet (found 2026-10-20). +/// +/// Only the gated ITEM is test code, never the rest of the file. The first cut stopped +/// at the first column-zero `#[cfg(test)]`, which is the end of production only when the +/// test mod is the file's last item. A split that declares `#[cfg(test)] mod tests;` with +/// the other modules near the top (llamacpp_adapter.rs, line 93 of 934), or a gated test +/// const above the code (generate_response.rs, line 75 of 644), hid everything below it: +/// a split read as 10 unwraps removed when none were (found on #5225, 2026-10-20). +/// Lines of a gated item are blanked, not dropped, so line numbers stay true. +/// The attributes that gate an item OUT of a production build: unit tests, and the fixtures a +/// crate exports to its dependents' tests (`test-fixtures` is never enabled in a release +/// build). Code under either is test code to these scans; the kernel cut moved its fixtures +/// from the first spelling to the second so core's tests can reach them across the crate. +const TEST_GATES: &[&str] = &["#[cfg(test)]", "#[cfg(any(test, feature = \"test-fixtures\"))]"]; + +pub fn production_half(src: &str) -> String { + let lines: Vec<&str> = src.lines().collect(); + let mut out: Vec<&str> = Vec::with_capacity(lines.len()); + let mut gated = false; + let mut i = 0; + while i < lines.len() { + let code = split_code_and_comment(lines[i]).0; + if code.trim_start().starts_with("#![cfg(test)]") { + gated = true; + break; // the whole file from here is a test module moved out of its owner + } + let Some(gate) = TEST_GATES.iter().find(|gate| code.starts_with(**gate)) else { + out.push(lines[i]); + i += 1; + continue; + }; + // The gated item can begin on the attribute's own line. Keep the slice's + // line count intact so blanking still preserves source line numbers. + let mut item_lines = lines[i..].to_vec(); + item_lines[0] = &lines[i][gate.len()..]; + let end = i + gated_item_end(&item_lines, 0); + out.extend(std::iter::repeat_n("", end + 1 - i)); + gated = true; + i = end + 1; + } + if !gated { + return src.to_string(); + } + while out.last().is_some_and(|l| l.trim().is_empty()) { + out.pop(); + } + out.join("\n") +} + +/// Byte offset after a block comment's closing delimiter, given its body (after `/*`). +/// Rust block comments nest; punctuation inside every nesting level is trivia. +fn block_comment_end(bytes: &[u8]) -> Option { + let (mut depth, mut at) = (1usize, 0usize); + while at < bytes.len() { + if bytes[at..].starts_with(b"/*") { + depth += 1; + at += 2; + } else if bytes[at..].starts_with(b"*/") { + depth -= 1; + at += 2; + if depth == 0 { return Some(at); } + } else { + at += 1; + } + } + None +} + +/// Skip Rust whitespace and comments. Comments are trivia even +/// between `const` and `fn`; nested block comments are consumed as one comment. +fn skip_item_trivia(mut src: &str) -> &str { + loop { + src = src.trim_start(); + if let Some(comment) = src.strip_prefix("//") { + match comment.find('\n') { + Some(end) => src = &comment[end + 1..], + None => return "", + } + } else if let Some(comment) = src.strip_prefix("/*") { + let Some(end) = block_comment_end(comment.as_bytes()) else { return "" }; + src = &comment[end..]; + } else { + break; + } + } + src +} + +fn significant_word(src: &str) -> (Option<&str>, &str) { + let src = skip_item_trivia(src); + let end = src.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count(); + if end == 0 { (None, src) } else { (Some(&src[..end]), &src[end..]) } +} + +/// Index of the last line of the item starting at or after `from` (attributes, blank +/// lines and comments before it belong to it). The item ends on the line where its +/// braces close, or on its `;` at depth zero when it opens none (`mod tests;`, a +/// multi-line `static ... = ...;`). Read as one character stream, not line by line: a +/// test module's multi-line string fixtures (JSON, source snippets, raw strings) carry +/// braces that a per-line count read as the module's end, leaking the rest of the tests +/// into production. An item that never closes runs to the end of the file. +pub(crate) fn gated_item_end(lines: &[&str], from: usize) -> usize { + let last = lines.len().saturating_sub(1); + let Some(head) = (from..lines.len()).find(|&k| { + let code = split_code_and_comment(lines[k]).0.trim(); + !code.is_empty() && !code.starts_with("#[") + }) else { + return last; + }; + let text = lines[head..].join("\n"); + // Initializer blocks can be followed by operators, method calls, or more blocks. + // A static/const ends at its outer semicolon, never at an initializer's `}`. + let (mut keyword, mut rest) = significant_word(&text); + if keyword == Some("pub") { + rest = skip_item_trivia(rest); + if let Some(restricted) = rest.strip_prefix('(') { + rest = restricted; + loop { + rest = skip_item_trivia(rest); + match rest.chars().next() { + Some(')') => { + rest = &rest[1..]; + break; + } + Some(ch) => rest = &rest[ch.len_utf8()..], + None => return last, + } + } + } + (keyword, rest) = significant_word(rest); + } + let semicolon_terminated = match keyword { + Some("static") => true, + Some("const") => !matches!(significant_word(rest).0, Some("fn" | "unsafe" | "extern")), + _ => false, + }; + let b = text.as_bytes(); + let ident = |at: usize| b[at].is_ascii_alphanumeric() || b[at] == b'_'; + let (mut depth, mut line, mut i, mut opened) = (0usize, head, 0usize, false); + let (mut parentheses, mut brackets) = (0usize, 0usize); + while i < b.len() { + match b[i] { + b'\n' => line += 1, + b'/' if b.get(i + 1) == Some(&b'/') => { + while i + 1 < b.len() && b[i + 1] != b'\n' { + i += 1; + } + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let start = i + 2; + let Some(length) = block_comment_end(&b[start..]) else { return last }; + line += b[start..start + length].iter().filter(|&&c| c == b'\n').count(); + i = start + length - 1; + } + // A raw string, r"…" / r#"…"# / br#"…"#: no escapes, ends at `"` + the same hashes. + b'r' if (i == 0 || !ident(i - 1)) || (b[i - 1] == b'b' && (i < 2 || !ident(i - 2))) => { + let hashes = b[i + 1..].iter().take_while(|&&c| c == b'#').count(); + if b.get(i + 1 + hashes) == Some(&b'"') { + i += 2 + hashes; + while i < b.len() && !(b[i] == b'"' && b[i + 1..].iter().take(hashes).all(|&c| c == b'#') && b.len() - i > hashes) { + line += usize::from(b[i] == b'\n'); + i += 1; + } + i += hashes; + } + } + b'"' => { + i += 1; + while i < b.len() && b[i] != b'"' { + if b[i] == b'\\' { + // An escape, including the `\` + newline continuation: its newline still counts. + line += usize::from(b.get(i + 1) == Some(&b'\n')); + i += 2; + continue; + } + line += usize::from(b[i] == b'\n'); + i += 1; + } + } + // A char literal ('{', '\'', '\u{7d}') is skipped whole; a lifetime ('a, 'static) + // has no closing quote right after its first character and is left alone. + b'\'' => { + if b.get(i + 1) == Some(&b'\\') { + i += 2; + while i < b.len() && b[i] != b'\'' { + i += 1; + } + } else if b.get(i + 2) == Some(&b'\'') { + i += 2; + } + } + b'{' => { + depth += 1; + opened = true; + } + b'}' => { + depth = depth.saturating_sub(1); + if depth == 0 && parentheses == 0 && brackets == 0 + && opened && !semicolon_terminated + { + return line; + } + } + b'(' => parentheses += 1, + b')' => parentheses = parentheses.saturating_sub(1), + b'[' => brackets += 1, + b']' => brackets = brackets.saturating_sub(1), + b';' if depth == 0 && parentheses == 0 && brackets == 0 => return line, + _ => {} + } + i += 1; + } + last +} + +/// Split a source line into (code, same-line comment), respecting string literals so +/// a `//` inside `"http://…"` is not read as a comment. +/// +/// Shared because every rule that asks "is this line justified / is this a real +/// occurrence" needs exactly this, and getting it subtly different per rule is how +/// two scanners disagree about the same file. +pub fn split_code_and_comment(line: &str) -> (&str, Option<&str>) { + let bytes = line.as_bytes(); + let mut in_str = false; + let mut escaped = false; + let mut i = 0; + while i < bytes.len() { + let c = bytes[i]; + if !in_str { + if let Some(len) = char_literal_len(bytes, i) { + i += len; + continue; + } + } + if in_str { + if escaped { + escaped = false; + } else if c == b'\\' { + escaped = true; + } else if c == b'"' { + in_str = false; + } + } else if c == b'"' { + in_str = true; + } else if c == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' { + return (&line[..i], Some(&line[i + 2..])); + } + i += 1; + } + (line, None) +} + +/// The byte length of a char (or byte) literal starting at `i`, if one does: `'x'` (any +/// single byte, `'"'` and `'{'` included) or an escaped `'\x'` (`'\''`, `'\"'`). A lifetime +/// (`'a`) never has a closing `'` two bytes on, so it is never mistaken for one (Cormac, +/// review of #4678: `'"'` opened a string and hid every brace after it on the line). +fn char_literal_len(bytes: &[u8], i: usize) -> Option { + if bytes.get(i) != Some(&b'\'') { + return None; + } + if bytes.get(i + 2) == Some(&b'\'') && bytes.get(i + 1) != Some(&b'\\') { + return Some(3); + } + if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 3) == Some(&b'\'') { + return Some(4); + } + None +} + +/// The net brace depth change of a line of CODE (comments already split off), counting +/// only braces outside string literals and outside the `'{'` / `'}'` char literals, by +/// the same string tracking as [`split_code_and_comment`]. A brace in `"}"` is text, not +/// a block (Astra, review of #4678). Line-based like its sibling, so a string literal +/// spanning lines or a raw string with an unbalanced brace is outside its reach. +pub fn brace_delta(code: &str) -> i64 { + outside_literals(code) + .map(|(_, c)| match c { + b'{' => 1, + b'}' => -1, + _ => 0, + }) + .sum() +} + +/// The bytes of a line of CODE that lie outside string and char literals, with their offsets: +/// the one literal-aware walk this lexer's line readers share ([`brace_delta`], +/// [`without_signature`]), so a literal is skipped the same way by every rule. +fn outside_literals(code: &str) -> impl Iterator + '_ { + let bytes = code.as_bytes(); + let mut in_str = false; + let mut escaped = false; + let mut i = 0; + std::iter::from_fn(move || { + while i < bytes.len() { + let (at, c) = (i, bytes[i]); + if in_str { + if escaped { + escaped = false; + } else if c == b'\\' { + escaped = true; + } else if c == b'"' { + in_str = false; + } + i += 1; + continue; + } + if c == b'"' { + in_str = true; + i += 1; + continue; + } + if let Some(len) = raw_string_len(bytes, i) { + i += len; + continue; + } + if let Some(len) = char_literal_len(bytes, i) { + i += len; + continue; + } + i += 1; + return Some((at, c)); + } + None + }) +} + +/// The byte length of a raw string literal starting at `i`, if one does: `r"..."`, `r#"..."#` with +/// any number of `#`, and the byte forms `br"..."`, `br#"..."#`. Its body may hold `"` freely, so +/// only the closing quote followed by the same number of `#` ends it (Codex on #5609: +/// `write(path, r#"let source = "fn main() {}";"#)` hid the write). The prefix must start a token, +/// so an identifier ending in `r` or `br` is not one. A raw string left open on this line runs to +/// the line's end, the limit every line reader here shares. +fn raw_string_len(bytes: &[u8], i: usize) -> Option { + let starts_token = i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_'); + if !starts_token { + return None; + } + let mut at = i; + if bytes.get(at) == Some(&b'b') { + at += 1; + } + if bytes.get(at) != Some(&b'r') { + return None; + } + at += 1; + let hashes = bytes[at..].iter().take_while(|&&b| b == b'#').count(); + at += hashes; + if bytes.get(at) != Some(&b'"') { + return None; + } + at += 1; + while at < bytes.len() { + if bytes[at] == b'"' && bytes[at + 1..].iter().take(hashes).filter(|&&b| b == b'#').count() == hashes { + return Some(at + 1 + hashes - i); + } + at += 1; + } + Some(bytes.len() - i) +} + +/// `code` without a function signature it declares: what follows the body's opening brace, or +/// nothing when the line is only a signature. A declaration is `fn` at a word boundary followed by +/// whitespace, outside every literal: a `fn ` inside a string is text, so +/// `std::fs::write(path, "fn main() {}")` keeps its write visible (Codex on #5609). +pub fn without_signature(code: &str) -> &str { + let bytes = code.as_bytes(); + let starts_fn = |at: usize| { + bytes.get(at + 1) == Some(&b'n') + && bytes.get(at + 2).is_some_and(u8::is_ascii_whitespace) + && (at == 0 || !(bytes[at - 1].is_ascii_alphanumeric() || bytes[at - 1] == b'_')) + }; + let mut declared = false; + for (at, c) in outside_literals(code) { + if !declared { + declared = c == b'f' && starts_fn(at); + } else if c == b'{' { + return &code[at + 1..]; + } + } + if declared { "" } else { code } +} + +/// The numeric types a bound can wear. A `&str`, a `bool` or a `Duration` named `..._MAX` +/// is not a quantity a bound rule can reason about. +const NUMERIC_TYPES: &[&str] = &[ + "u8", "u16", "u32", "usize", "u64", "i32", "i64", "f32", "f64", +]; + +/// Is `token` a SCREAMING_SNAKE constant name? At least one underscore, so a type +/// (`Duration`) or a single-letter generic is never mistaken for one. +pub fn is_constant_name(token: &str) -> bool { + token.len() >= 3 + && token.contains('_') + && token.starts_with(|c: char| c.is_ascii_uppercase()) + && token + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') +} + +/// `CONST_A * CONST_B` on this line — a bound assembled from constants alone, with +/// no measurement anywhere in it. Returns the two names. +/// +/// A constant times a LITERAL (`MIN_SERVE_CTX * 8`) is deliberately NOT this shape: +/// it is a derivation from a named bound, which the de-hardcode guard already blesses +/// and which keeps one owner for the number. +pub fn constant_product<'a>(code: &'a str) -> Option<(&'a str, &'a str)> { + let bytes = code.as_bytes(); + for (i, c) in code.char_indices() { + if c != '*' { + continue; + } + // `**`, `*/`, `/*` are not multiplication; nor is `*mut` / `*const`, whose + // keywords are lowercase and so can never be constant names. + if bytes.get(i + 1).is_some_and(|b| *b == b'*' || *b == b'/') { + continue; + } + if i > 0 && (bytes[i - 1] == b'*' || bytes[i - 1] == b'/') { + continue; + } + let left = trailing_identifier(&code[..i]); + let right = leading_identifier(&code[i + 1..]); + if let (Some(l), Some(r)) = (left, right) { + if is_constant_name(l) && is_constant_name(r) { + return Some((l, r)); + } + } + } + None +} + +fn trailing_identifier<'a>(before: &'a str) -> Option<&'a str> { + let t = before.trim_end(); + let start = t + .char_indices() + .rev() + .take_while(|(_, c)| c.is_alphanumeric() || *c == '_') + .last() + .map(|(i, _)| i)?; + Some(&t[start..]) +} + +fn leading_identifier<'a>(after: &'a str) -> Option<&'a str> { + let t = after.trim_start(); + let end = t + .char_indices() + .take_while(|(_, c)| c.is_alphanumeric() || *c == '_') + .last() + .map(|(i, c)| i + c.len_utf8())?; + Some(&t[..end]) +} + +/// `(name, type, value)` if this line declares a numeric constant. +pub fn numeric_const<'a>(code: &'a str) -> Option<(&'a str, &'a str, &'a str)> { + let trimmed = code.trim_start(); + // Visibility does not change whether a declaration is a numeric constant. + // Restricted visibility includes pub(in crate::owner), not only crate/super. + let declaration = if let Some(restricted) = trimmed.strip_prefix("pub(") { + restricted.split_once(')')?.1.trim_start() + } else if let Some(public) = trimmed.strip_prefix("pub ") { + public.trim_start() + } else { + trimmed + }; + let rest = declaration.strip_prefix("const ")?; + let (name, tail) = rest.split_once(':')?; + let (ty, value) = tail.split_once('=')?; + let ty = ty.trim(); + if !NUMERIC_TYPES.contains(&ty) { + return None; + } + Some((name.trim(), ty, value.trim().trim_end_matches(';').trim())) +} + +/// A value the compiler reads as a fresh guess: a bare decimal or float literal. An +/// expression over another named bound is a derivation and passes. +pub fn is_bare_literal(value: &str) -> bool { + !value.is_empty() + && value.starts_with(|c: char| c.is_ascii_digit()) + && value + .chars() + .all(|c| c.is_ascii_digit() || c == '_' || c == '.') +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: a `fn ` inside a string literal read as a signature, so the code before + // the literal's brace was dropped and a real write escaped the writes ratchet (Codex on #5609). + #[test] + fn a_signature_is_declared_only_outside_literals() { + let raw = r##"std::fs::write(path, r#"let source = "fn main() {}";"#)?;"##; + assert_eq!(without_signature(raw), raw, "a fn inside a raw string with embedded quotes is text"); + let byte_raw = r##"let b = br#"fn x() { "}" }"#;"##; + assert_eq!(without_signature(byte_raw), byte_raw); + assert_eq!(brace_delta(byte_raw), 0, "braces inside a raw byte string are not blocks"); + assert_eq!(without_signature("let bar = barrier(fn_ptr);"), "let bar = barrier(fn_ptr);", "an identifier ending in r is not a raw string"); + let write = r#"std::fs::write(path, "fn main() {}")?;"#; + assert_eq!(without_signature(write), write, "a fn inside a string is text"); + assert_eq!(without_signature("fn cap(&self) -> usize { self.grant.take(8) }"), " self.grant.take(8) }"); + assert_eq!(without_signature("pub fn recall_tokens(&self) -> usize {"), ""); + assert_eq!(without_signature("let defn = x { y };"), "let defn = x { y };", "fn inside a word is no declaration"); + assert_eq!(without_signature(r#"fn label() -> &'static str { "{" }"#), r#" "{" }"#); + } + + // what this catches (Astra, review of #4678): a brace inside a string or char + // literal counted as a block, so `{ "}" }` read as closing the enclosing impl. + #[test] + fn braces_in_string_and_char_literals_are_not_blocks() { + assert_eq!(brace_delta(r#"fn label() -> &str { "}" }"#), 0); + assert_eq!(brace_delta(r#"let s = "{{";"#), 0); + assert_eq!(brace_delta(r#"let s = "a \" }";"#), 0, "an escaped quote does not end the string"); + assert_eq!(brace_delta("if c == '{' { open += 1;"), 1); + assert_eq!(brace_delta("impl Runner {"), 1); + assert_eq!(brace_delta("}"), -1); + // Cormac, review of #4678: a quote char or byte literal is not a string. + assert_eq!(brace_delta("if c == '\"' {"), 1); + assert_eq!(brace_delta("} else if c == b'\"' {"), 0); + assert_eq!(brace_delta(r"} else if c == b'\'' {"), 0, "an escaped quote char"); + assert_eq!(brace_delta("fn f<'a>(x: &'a str) {"), 1, "lifetimes are not char literals"); + // The same rule keeps the comment splitter right after a quote char literal. + assert_eq!(split_code_and_comment("if c == '\"' { // note").1, Some(" note")); + } + + /// What this catches: a `//` inside a string literal being read as the start of + /// a comment — which would let `let u = fetch("http://x").unwrap();` count as + /// "justified" because the URL's slashes look like a comment. Real shape: URLs + /// and file paths appear on plenty of unwrap lines in this crate. + #[test] + fn a_double_slash_inside_a_string_is_not_a_comment() { + let (code, comment) = split_code_and_comment(r#"let u = get("http://x").unwrap();"#); + assert_eq!(comment, None, "the URL's // must not read as a comment"); + assert!(code.contains("unwrap")); + + let (code, comment) = + split_code_and_comment(r#"let u = get("http://x").unwrap(); // JUSTIFIED: seeded"#); + assert_eq!(comment, Some(" JUSTIFIED: seeded")); + assert!(code.contains("unwrap")); + + // An escaped quote must not end the string early. + let (_, comment) = split_code_and_comment(r#"let s = "a\"// b";"#); + assert_eq!(comment, None); + } + + // what this catches (card 0af5d5ec): a test module moved to its own file, marked + // `#![cfg(test)]`, read as production, so its unwraps and spawns counted against the + // ratchets and every "split the monolith by moving its tests" looked like growth. + #[test] + fn a_file_marked_inner_cfg_test_has_no_production_half() { + let moved = "//! Tests for disk_eviction.\n#![cfg(test)]\nuse super::*;\nfn t() { x.unwrap(); }\n"; + assert_eq!(production_half(moved), "//! Tests for disk_eviction."); + let inline = "fn real() {}\n#[cfg(test)]\nmod tests { fn t() { x.unwrap(); } }\n"; + assert_eq!(production_half(inline), "fn real() {}"); + let prose = "//! Mentions #![cfg(test)] in prose only.\nfn real() {}\n"; + assert_eq!(production_half(prose), prose, "a mention in a comment is not the marker"); + } + + // what this catches: the first cut's blind spot. A `mod tests;` declared with the other + // modules near the top, or a gated test const above the code, hid every production line + // below it (llamacpp_adapter.rs on #5225: 10 unwraps read as removed when none were). + #[test] + fn only_the_gated_item_is_test_code_never_the_rest_of_the_file() { + let declared = "mod a;\n#[cfg(test)]\nmod tests;\nfn real() { x.unwrap(); }\n"; + assert_eq!(production_half(declared), "mod a;\n\n\nfn real() { x.unwrap(); }"); + let konst = "#[cfg(test)]\n#[allow(dead_code)]\nstatic LOCK: Lazy =\n Lazy::new(|| M::new());\nfn real() { y.unwrap(); }\n"; + assert!(production_half(konst).ends_with("fn real() { y.unwrap(); }")); + assert!(!production_half(konst).contains("LOCK")); + let mid = "#[cfg(test)]\nmod tests {\n fn t() { let s = \"}\"; let c = '}'; }\n}\nfn after() { z.unwrap(); }\n"; + let p = production_half(mid); + assert!(p.contains("fn after()") && !p.contains("fn t()"), "{p:?}"); + assert_eq!(p.lines().count(), 5, "line numbers stay true"); + let helper = "fn real() {}\n#[cfg(test)]\nfn helper() {\n q.unwrap();\n}\nfn more() {}\n"; + assert_eq!(production_half(helper), "fn real() {}\n\n\n\n\nfn more() {}"); + // Regression for #5227: a same-line test item must not consume its successor. + let inline = "#[cfg(test)] mod tests {}\nfn real() { x.unwrap(); }\n"; + assert_eq!(production_half(inline), "\nfn real() { x.unwrap(); }"); + let inline_decl = "#[cfg(test)] mod tests;\nfn real() { x.unwrap(); }\n"; + assert_eq!(production_half(inline_decl), "\nfn real() { x.unwrap(); }"); + // A comment's semicolon cannot make the closed test module swallow production. + let commented = "#[cfg(test)]\nmod tests {\n} // diagnostic; not syntax\nfn real() { x.unwrap(); }\n"; + assert_eq!(production_half(commented), "\n\n\nfn real() { x.unwrap(); }"); + // Real constructor closing syntax still belongs to the gated static. + let constructor = "#[cfg(test)]\nstatic X: LazyLock<()> = LazyLock::new(|| {\n});\nfn real() { x.unwrap(); }\n"; + assert_eq!(production_half(constructor), "\n\n\nfn real() { x.unwrap(); }"); + // Regression for the first proposed fix: initializer blocks do not end a static. + for initializer in [ + "{1} + { let y = 2;\n const EXTRA_LIMIT: usize = 9;\n y + EXTRA_LIMIT\n}", + "{1usize}.wrapping_add({ let y = 2;\n const EXTRA_LIMIT: usize = 9;\n y + EXTRA_LIMIT\n})", + "[ { let y = 2;\n const EXTRA_LIMIT: usize = 9;\n y + EXTRA_LIMIT\n} ][0]", + ] { + for declaration in [ + "static X", "const X", "pub(in crate::owner) const X", + "pub\nconst X", "pub /* comment */ (crate) const X", + "pub // visibility\n(in crate::owner) static X", + ] { + let raw = format!("#[cfg(test)]\n{declaration}: usize = {initializer};\nfn real() {{ x.unwrap(); }}\n"); + let projected = production_half(&raw); + assert!(!projected.contains("EXTRA_LIMIT"), "{projected}"); + assert_eq!(projected.lines().last(), Some("fn real() { x.unwrap(); }")); + assert_eq!(projected.lines().count(), raw.lines().count(), "line positions"); + } + } + // Const functions still end with their body, even when a comment has punctuation. + let konst_fn = "#[cfg(test)]\nconst fn helper() -> usize { 1 } // ;\nfn real() { x.unwrap(); }\n"; + assert_eq!(production_half(konst_fn), "\n\nfn real() { x.unwrap(); }"); + // Regression for proposed revision 4: nested comment delimiters are never code. + let nested = "#[cfg(test)]\nfn helper() { /* outer /* inner */ ( [ { ;\n tail ) ] } */ }\nfn production() { x.unwrap(); }\n"; + assert_eq!(production_half(nested), "\n\n\nfn production() { x.unwrap(); }"); + let open_delimiter = "#[cfg(test)]\nfn helper() { /* outer /* inner */ ( */ }\nfn production() { x.unwrap(); }\n"; + assert_eq!(production_half(open_delimiter), "\n\nfn production() { x.unwrap(); }"); + + // Regression for proposed revision 2: comments are whitespace between keywords. + for trivia in ["/* explanation */", "// explanation\n", "/* outer /* nested */ tail */"] { + let raw = format!("#[cfg(test)]\nconst {trivia} fn helper() -> usize {{ 1 }}\nfn production() {{ x.unwrap(); }}\n"); + let projected = production_half(&raw); + assert_eq!(projected.lines().last(), Some("fn production() { x.unwrap(); }")); + assert!(!projected.contains("helper")); + assert_eq!(projected.lines().count(), raw.lines().count()); + } + + + + } +} diff --git a/core/source-hygiene/src/lib.rs b/core/source-hygiene/src/lib.rs index b200790cc9..6dc43e2079 100644 --- a/core/source-hygiene/src/lib.rs +++ b/core/source-hygiene/src/lib.rs @@ -25,30 +25,34 @@ //! that is a follow-up, not a reason to hand-roll a fourth. pub mod boundary_serialization; +pub mod budget_discipline; pub mod cognition_names_persona; pub mod context_codec; pub mod continuum_home; pub mod crate_policy; pub mod crate_wiring; -pub mod derived_bounds; pub mod dev_only_deps; pub mod grab_bag; -pub mod head_cuts; pub mod file_size; pub mod identity_discipline; pub mod layer_discipline; +pub mod lexer; pub mod module_cycles; pub mod os_branches; pub mod production_reachability; pub mod ratchet; pub mod tenant_neutrality; +pub mod time_bounds; pub mod test_mod_singularity; pub mod subprocess_spawn; pub mod unwrap_justification; +pub mod vendor_pin; pub mod wall_clock; use std::path::{Path, PathBuf}; +use lexer::{production_half, split_code_and_comment, without_signature}; + /// One source file, pre-split so a rule never has to re-derive the split. pub struct SourceFile { /// Path relative to `src/`, forward-slashed — the form a rule's allow-list and @@ -67,9 +71,19 @@ pub struct SourceFile { /// fell back to `production` when the read failed — a fallback that silently /// swapped the shape and reintroduced the exact miscount it was written to fix.) pub raw: String, + /// Path from the root of the scanned checkout (`core/continuum-cognition/src/...`): + /// the file's identity in the repository, which `rel` is not (a module crate's `rel` + /// carries no crate name). A PR's changed files are matched on it. + pub repo: String, } impl SourceFile { + /// An in-memory file for a rule's own tests. + #[cfg(test)] + pub fn fixture(rel: &str, production: &str, raw: &str) -> Self { + Self { rel: rel.to_owned(), production: production.to_owned(), raw: raw.to_owned(), repo: format!("fixture/{rel}") } + } + /// The module a file's code belongs to, as the path that names it: `x` for `x.rs`, /// `x/mod.rs`, and for a test module moved out of it (`x/tests.rs`, /// `x/tests/mod.rs`, `x/tests/part_2.rs`, each marked `#![cfg(test)]`). A rule that @@ -114,11 +128,7 @@ impl SourceFile { /// unit tests, so predicate regressions are pinned without touching disk. #[cfg(test)] pub fn for_test(rel: &str, production: &str) -> Self { - Self { - rel: rel.to_string(), - production: production.to_string(), - raw: production.to_string(), - } + Self::fixture(rel, production, production) } } @@ -139,6 +149,20 @@ pub trait SourceRule { fn check(&self, file: &SourceFile) -> Vec; } +/// The production lines of `file` whose code (comments removed) `hit` names a finding for, as +/// violations of `rule`, located by repository path. A function's SIGNATURE is a definition, +/// not a use, so it is never a site; its body is code like any other, including a body on +/// the signature's own line (`fn cap(&self) -> usize { self.grant.take(8) }`, Codex on #5609). +pub fn sites(file: &SourceFile, rule: &'static str, hit: impl Fn(&str) -> Option) -> Vec { + file.production_lines() + .filter_map(|(line, text)| { + let code = without_signature(split_code_and_comment(text).0); + hit(code).map(|what| Violation { rule, file: file.repo.clone(), line, source: format!("{what}: {}", text.trim()) }) + }) + .collect() +} + + /// `src/` of this crate, resolved from the manifest so the scan is independent of /// the process's working directory (a test's cwd is not the crate root under every /// runner). @@ -169,6 +193,14 @@ fn audited_crate_root() -> PathBuf { .unwrap_or_else(|| PathBuf::from(AUDITED_CRATE)) } +/// The root of the checkout under audit (head, or the base tree a ratchet measures). +pub(crate) fn scanned_checkout() -> PathBuf { + let Some(checkout) = audited_crate_root().ancestors().nth(2).map(Path::to_path_buf) else { + panic!("{} has no checkout above core/: repository paths cannot be named", audited_crate_root().display()); + }; + checkout +} + /// The crate under audit. One name, one place — a second spelling of this is how a /// rule ends up scanning a directory that does not exist and reporting zero. pub(crate) const AUDITED_CRATE: &str = "continuum-core"; @@ -198,21 +230,19 @@ pub fn module_crates() -> Result, crate_policy::PolicyError> { /// relative to it, then each split crate's `src` with its name prefixed. A listed crate /// whose `src` is missing fails loudly rather than auditing nothing. pub fn audited_files() -> Result, crate_policy::PolicyError> { - let mut files = collect_files(&crate_src_root()); - let Some(core_dir) = audited_crate_root().parent().map(Path::to_path_buf) else { - panic!("{AUDITED_CRATE} has no parent directory: the split crates cannot be found"); - }; + let checkout = scanned_checkout(); + let mut files = collect_files(&checkout, &format!("core/{AUDITED_CRATE}/src")); for name in &split_crates()? { - let src = core_dir.join(name).join("src"); - assert!(src.is_dir(), "split crate {name} has no src at {}: the gates would audit nothing", src.display()); - files.extend(collect_files(&src).into_iter().map(|f| SourceFile { rel: format!("{name}/{}", f.rel), ..f })); + let dir = format!("core/{name}/src"); + assert!(checkout.join(&dir).is_dir(), "split crate {name} has no src at {dir}: the gates would audit nothing"); + files.extend(collect_files(&checkout, &dir).into_iter().map(|f| SourceFile { rel: format!("{name}/{}", f.rel), ..f })); } for name in &module_crates()? { // A tree from before the cut has no such crate: its modules are still in // continuum-core/src and were collected above, so nothing goes unaudited. - let src = core_dir.join(name).join("src"); - if src.is_dir() { - files.extend(collect_files(&src).into_iter().filter(|f| f.rel != "lib.rs")); + let dir = format!("core/{name}/src"); + if checkout.join(&dir).is_dir() { + files.extend(collect_files(&checkout, &dir).into_iter().filter(|f| f.rel != "lib.rs")); } } Ok(files) @@ -298,245 +328,18 @@ pub fn workspace_src_roots() -> Vec { roots } -/// The PRODUCTION half of a source file (see [`SourceFile::production`]): every line -/// not gated by a `#[cfg(test)]` that is CODE, not prose. Matching the raw string -/// would truncate at the first doc comment that merely MENTIONS test-gating, and module -/// headers in this crate do exactly that, including this one. Found by the guard's own -/// positive control: the naive form excluded nearly all of `source_hygiene/mod.rs` from -/// its own scan, silently. Match by nature, never by name. -/// -/// A file that IS a test module, moved out of its parent to shrink it, says so with the -/// inner `#![cfg(test)]` on its first code line: the whole file is test code. Without -/// this, every `mod tests;` split read as all-production and charged its unwraps and -/// spawns to the ratchets (card 0af5d5ec, 2026-10-18). -/// -/// A COLUMN-ZERO `#[cfg(test)]` gates one file-scope item: that item is test code and -/// nothing else is. An indented `#[cfg(test)]` (a test-only helper inside an `impl`) is -/// scanned as production, erring toward noise: cut there, `cognition/llm_deliberation_faculty.rs` -/// hid ~9,000 production lines from every ratchet (found 2026-10-20). -/// -/// Only the gated ITEM is test code, never the rest of the file. The first cut stopped -/// at the first column-zero `#[cfg(test)]`, which is the end of production only when the -/// test mod is the file's last item. A split that declares `#[cfg(test)] mod tests;` with -/// the other modules near the top (llamacpp_adapter.rs, line 93 of 934), or a gated test -/// const above the code (generate_response.rs, line 75 of 644), hid everything below it: -/// a split read as 10 unwraps removed when none were (found on #5225, 2026-10-20). -/// Lines of a gated item are blanked, not dropped, so line numbers stay true. -/// The attributes that gate an item OUT of a production build: unit tests, and the fixtures a -/// crate exports to its dependents' tests (`test-fixtures` is never enabled in a release -/// build). Code under either is test code to these scans; the kernel cut moved its fixtures -/// from the first spelling to the second so core's tests can reach them across the crate. -const TEST_GATES: &[&str] = &["#[cfg(test)]", "#[cfg(any(test, feature = \"test-fixtures\"))]"]; - -pub fn production_half(src: &str) -> String { - let lines: Vec<&str> = src.lines().collect(); - let mut out: Vec<&str> = Vec::with_capacity(lines.len()); - let mut gated = false; - let mut i = 0; - while i < lines.len() { - let code = split_code_and_comment(lines[i]).0; - if code.trim_start().starts_with("#![cfg(test)]") { - gated = true; - break; // the whole file from here is a test module moved out of its owner - } - let Some(gate) = TEST_GATES.iter().find(|gate| code.starts_with(**gate)) else { - out.push(lines[i]); - i += 1; - continue; - }; - // The gated item can begin on the attribute's own line. Keep the slice's - // line count intact so blanking still preserves source line numbers. - let mut item_lines = lines[i..].to_vec(); - item_lines[0] = &lines[i][gate.len()..]; - let end = i + gated_item_end(&item_lines, 0); - out.extend(std::iter::repeat_n("", end + 1 - i)); - gated = true; - i = end + 1; - } - if !gated { - return src.to_string(); - } - while out.last().is_some_and(|l| l.trim().is_empty()) { - out.pop(); - } - out.join("\n") -} - -/// Byte offset after a block comment's closing delimiter, given its body (after `/*`). -/// Rust block comments nest; punctuation inside every nesting level is trivia. -fn block_comment_end(bytes: &[u8]) -> Option { - let (mut depth, mut at) = (1usize, 0usize); - while at < bytes.len() { - if bytes[at..].starts_with(b"/*") { - depth += 1; - at += 2; - } else if bytes[at..].starts_with(b"*/") { - depth -= 1; - at += 2; - if depth == 0 { return Some(at); } - } else { - at += 1; - } - } - None -} - -/// Skip Rust whitespace and comments. Comments are trivia even -/// between `const` and `fn`; nested block comments are consumed as one comment. -fn skip_item_trivia(mut src: &str) -> &str { - loop { - src = src.trim_start(); - if let Some(comment) = src.strip_prefix("//") { - match comment.find('\n') { - Some(end) => src = &comment[end + 1..], - None => return "", - } - } else if let Some(comment) = src.strip_prefix("/*") { - let Some(end) = block_comment_end(comment.as_bytes()) else { return "" }; - src = &comment[end..]; - } else { - break; - } - } - src -} - -fn significant_word(src: &str) -> (Option<&str>, &str) { - let src = skip_item_trivia(src); - let end = src.bytes().take_while(|b| b.is_ascii_alphanumeric() || *b == b'_').count(); - if end == 0 { (None, src) } else { (Some(&src[..end]), &src[end..]) } -} - -/// Index of the last line of the item starting at or after `from` (attributes, blank -/// lines and comments before it belong to it). The item ends on the line where its -/// braces close, or on its `;` at depth zero when it opens none (`mod tests;`, a -/// multi-line `static ... = ...;`). Read as one character stream, not line by line: a -/// test module's multi-line string fixtures (JSON, source snippets, raw strings) carry -/// braces that a per-line count read as the module's end, leaking the rest of the tests -/// into production. An item that never closes runs to the end of the file. -pub(crate) fn gated_item_end(lines: &[&str], from: usize) -> usize { - let last = lines.len().saturating_sub(1); - let Some(head) = (from..lines.len()).find(|&k| { - let code = split_code_and_comment(lines[k]).0.trim(); - !code.is_empty() && !code.starts_with("#[") - }) else { - return last; - }; - let text = lines[head..].join("\n"); - // Initializer blocks can be followed by operators, method calls, or more blocks. - // A static/const ends at its outer semicolon, never at an initializer's `}`. - let (mut keyword, mut rest) = significant_word(&text); - if keyword == Some("pub") { - rest = skip_item_trivia(rest); - if let Some(restricted) = rest.strip_prefix('(') { - rest = restricted; - loop { - rest = skip_item_trivia(rest); - match rest.chars().next() { - Some(')') => { - rest = &rest[1..]; - break; - } - Some(ch) => rest = &rest[ch.len_utf8()..], - None => return last, - } - } - } - (keyword, rest) = significant_word(rest); - } - let semicolon_terminated = match keyword { - Some("static") => true, - Some("const") => !matches!(significant_word(rest).0, Some("fn" | "unsafe" | "extern")), - _ => false, - }; - let b = text.as_bytes(); - let ident = |at: usize| b[at].is_ascii_alphanumeric() || b[at] == b'_'; - let (mut depth, mut line, mut i, mut opened) = (0usize, head, 0usize, false); - let (mut parentheses, mut brackets) = (0usize, 0usize); - while i < b.len() { - match b[i] { - b'\n' => line += 1, - b'/' if b.get(i + 1) == Some(&b'/') => { - while i + 1 < b.len() && b[i + 1] != b'\n' { - i += 1; - } - } - b'/' if b.get(i + 1) == Some(&b'*') => { - let start = i + 2; - let Some(length) = block_comment_end(&b[start..]) else { return last }; - line += b[start..start + length].iter().filter(|&&c| c == b'\n').count(); - i = start + length - 1; - } - // A raw string, r"…" / r#"…"# / br#"…"#: no escapes, ends at `"` + the same hashes. - b'r' if (i == 0 || !ident(i - 1)) || (b[i - 1] == b'b' && (i < 2 || !ident(i - 2))) => { - let hashes = b[i + 1..].iter().take_while(|&&c| c == b'#').count(); - if b.get(i + 1 + hashes) == Some(&b'"') { - i += 2 + hashes; - while i < b.len() && !(b[i] == b'"' && b[i + 1..].iter().take(hashes).all(|&c| c == b'#') && b.len() - i > hashes) { - line += usize::from(b[i] == b'\n'); - i += 1; - } - i += hashes; - } - } - b'"' => { - i += 1; - while i < b.len() && b[i] != b'"' { - if b[i] == b'\\' { - // An escape, including the `\` + newline continuation: its newline still counts. - line += usize::from(b.get(i + 1) == Some(&b'\n')); - i += 2; - continue; - } - line += usize::from(b[i] == b'\n'); - i += 1; - } - } - // A char literal ('{', '\'', '\u{7d}') is skipped whole; a lifetime ('a, 'static) - // has no closing quote right after its first character and is left alone. - b'\'' => { - if b.get(i + 1) == Some(&b'\\') { - i += 2; - while i < b.len() && b[i] != b'\'' { - i += 1; - } - } else if b.get(i + 2) == Some(&b'\'') { - i += 2; - } - } - b'{' => { - depth += 1; - opened = true; - } - b'}' => { - depth = depth.saturating_sub(1); - if depth == 0 && parentheses == 0 && brackets == 0 - && opened && !semicolon_terminated - { - return line; - } - } - b'(' => parentheses += 1, - b')' => parentheses = parentheses.saturating_sub(1), - b'[' => brackets += 1, - b']' => brackets = brackets.saturating_sub(1), - b';' if depth == 0 && parentheses == 0 && brackets == 0 => return line, - _ => {} - } - i += 1; - } - last -} -/// Read every `.rs` file under `root`, pre-split into production and test halves. +/// Read every `.rs` file under `dir` (a directory relative to `checkout`, `core//src`), +/// pre-split into production and test halves; each file's repository path is `dir/`. /// /// Unreadable files are skipped rather than failing the scan: a hygiene guard must /// not turn a transient IO error into a red build that says nothing about hygiene. -pub fn collect_files(root: &Path) -> Vec { +pub fn collect_files(checkout: &Path, dir: &str) -> Vec { + let root = checkout.join(dir); let mut out = Vec::new(); - let mut stack = vec![root.to_path_buf()]; - while let Some(dir) = stack.pop() { - let Ok(entries) = std::fs::read_dir(&dir) else { + let mut stack = vec![root.clone()]; + while let Some(current) = stack.pop() { + let Ok(entries) = std::fs::read_dir(¤t) else { continue; }; for entry in entries.flatten() { @@ -551,24 +354,18 @@ pub fn collect_files(root: &Path) -> Vec { let Ok(src) = std::fs::read_to_string(&path) else { continue; }; - let rel = path - .strip_prefix(root) - .unwrap_or(&path) - .to_string_lossy() - .replace('\\', "/"); + let Ok(under_root) = path.strip_prefix(&root) else { + panic!("{} was found walking {} but is not under it", path.display(), root.display()); + }; + let rel = under_root.to_string_lossy().replace('\\', "/"); let production = production_half(&src); - out.push(SourceFile { - rel, - production, - raw: src, - }); + let repo = format!("{dir}/{rel}"); + out.push(SourceFile { rel, production, raw: src, repo }); } } out } - - /// Walk this crate's `src/` once and apply every per-file rule to every `.rs` file. pub fn scan(rules: &[&dyn SourceRule]) -> Vec { let files = match audited_files() { @@ -659,117 +456,8 @@ fn sort_violations(v: &mut [Violation]) { v.sort_by(|a, b| (a.file.as_str(), a.line).cmp(&(b.file.as_str(), b.line))); } -/// Split a source line into (code, same-line comment), respecting string literals so -/// a `//` inside `"http://…"` is not read as a comment. -/// -/// Shared because every rule that asks "is this line justified / is this a real -/// occurrence" needs exactly this, and getting it subtly different per rule is how -/// two scanners disagree about the same file. -pub fn split_code_and_comment(line: &str) -> (&str, Option<&str>) { - let bytes = line.as_bytes(); - let mut in_str = false; - let mut escaped = false; - let mut i = 0; - while i < bytes.len() { - let c = bytes[i]; - if !in_str { - if let Some(len) = char_literal_len(bytes, i) { - i += len; - continue; - } - } - if in_str { - if escaped { - escaped = false; - } else if c == b'\\' { - escaped = true; - } else if c == b'"' { - in_str = false; - } - } else if c == b'"' { - in_str = true; - } else if c == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' { - return (&line[..i], Some(&line[i + 2..])); - } - i += 1; - } - (line, None) -} - -/// The byte length of a char (or byte) literal starting at `i`, if one does: `'x'` (any -/// single byte, `'"'` and `'{'` included) or an escaped `'\x'` (`'\''`, `'\"'`). A lifetime -/// (`'a`) never has a closing `'` two bytes on, so it is never mistaken for one (Cormac, -/// review of #4678: `'"'` opened a string and hid every brace after it on the line). -fn char_literal_len(bytes: &[u8], i: usize) -> Option { - if bytes.get(i) != Some(&b'\'') { - return None; - } - if bytes.get(i + 2) == Some(&b'\'') && bytes.get(i + 1) != Some(&b'\\') { - return Some(3); - } - if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 3) == Some(&b'\'') { - return Some(4); - } - None -} - -/// The net brace depth change of a line of CODE (comments already split off), counting -/// only braces outside string literals and outside the `'{'` / `'}'` char literals, by -/// the same string tracking as [`split_code_and_comment`]. A brace in `"}"` is text, not -/// a block (Astra, review of #4678). Line-based like its sibling, so a string literal -/// spanning lines or a raw string with an unbalanced brace is outside its reach. -pub fn brace_delta(code: &str) -> i64 { - let bytes = code.as_bytes(); - let mut in_str = false; - let mut escaped = false; - let mut delta = 0i64; - let mut i = 0; - while i < bytes.len() { - let c = bytes[i]; - if in_str { - if escaped { - escaped = false; - } else if c == b'\\' { - escaped = true; - } else if c == b'"' { - in_str = false; - } - } else if c == b'"' { - in_str = true; - } else if let Some(len) = char_literal_len(bytes, i) { - i += len; - continue; - } else if c == b'{' { - delta += 1; - } else if c == b'}' { - delta -= 1; - } - i += 1; - } - delta -} - #[cfg(test)] mod tests { - // what this catches (Astra, review of #4678): a brace inside a string or char - // literal counted as a block, so `{ "}" }` read as closing the enclosing impl. - #[test] - fn braces_in_string_and_char_literals_are_not_blocks() { - assert_eq!(super::brace_delta(r#"fn label() -> &str { "}" }"#), 0); - assert_eq!(super::brace_delta(r#"let s = "{{";"#), 0); - assert_eq!(super::brace_delta(r#"let s = "a \" }";"#), 0, "an escaped quote does not end the string"); - assert_eq!(super::brace_delta("if c == '{' { open += 1;"), 1); - assert_eq!(super::brace_delta("impl Runner {"), 1); - assert_eq!(super::brace_delta("}"), -1); - // Cormac, review of #4678: a quote char or byte literal is not a string. - assert_eq!(super::brace_delta("if c == '\"' {"), 1); - assert_eq!(super::brace_delta("} else if c == b'\"' {"), 0); - assert_eq!(super::brace_delta(r"} else if c == b'\'' {"), 0, "an escaped quote char"); - assert_eq!(super::brace_delta("fn f<'a>(x: &'a str) {"), 1, "lifetimes are not char literals"); - // The same rule keeps the comment splitter right after a quote char literal. - assert_eq!(super::split_code_and_comment("if c == '\"' { // note").1, Some(" note")); - } - // what this catches: THE EXTRACTION'S OWN FAILURE MODE, and it is the quiet one. // These rules used to live inside the crate they audit, so `CARGO_MANIFEST_DIR` // and "the tree under audit" were the same directory and could not disagree. @@ -853,135 +541,4 @@ mod tests { } use super::*; - - /// What this catches: a `//` inside a string literal being read as the start of - /// a comment — which would let `let u = fetch("http://x").unwrap();` count as - /// "justified" because the URL's slashes look like a comment. Real shape: URLs - /// and file paths appear on plenty of unwrap lines in this crate. - #[test] - fn a_double_slash_inside_a_string_is_not_a_comment() { - let (code, comment) = split_code_and_comment(r#"let u = get("http://x").unwrap();"#); - assert_eq!(comment, None, "the URL's // must not read as a comment"); - assert!(code.contains("unwrap")); - - let (code, comment) = - split_code_and_comment(r#"let u = get("http://x").unwrap(); // JUSTIFIED: seeded"#); - assert_eq!(comment, Some(" JUSTIFIED: seeded")); - assert!(code.contains("unwrap")); - - // An escaped quote must not end the string early. - let (_, comment) = split_code_and_comment(r#"let s = "a\"// b";"#); - assert_eq!(comment, None); - } - - // what this catches (card 0af5d5ec): a test module moved to its own file, marked - // `#![cfg(test)]`, read as production, so its unwraps and spawns counted against the - // ratchets and every "split the monolith by moving its tests" looked like growth. - #[test] - fn a_file_marked_inner_cfg_test_has_no_production_half() { - let moved = "//! Tests for disk_eviction.\n#![cfg(test)]\nuse super::*;\nfn t() { x.unwrap(); }\n"; - assert_eq!(production_half(moved), "//! Tests for disk_eviction."); - let inline = "fn real() {}\n#[cfg(test)]\nmod tests { fn t() { x.unwrap(); } }\n"; - assert_eq!(production_half(inline), "fn real() {}"); - let prose = "//! Mentions #![cfg(test)] in prose only.\nfn real() {}\n"; - assert_eq!(production_half(prose), prose, "a mention in a comment is not the marker"); - } - - // what this catches: the first cut's blind spot. A `mod tests;` declared with the other - // modules near the top, or a gated test const above the code, hid every production line - // below it (llamacpp_adapter.rs on #5225: 10 unwraps read as removed when none were). - #[test] - fn only_the_gated_item_is_test_code_never_the_rest_of_the_file() { - let declared = "mod a;\n#[cfg(test)]\nmod tests;\nfn real() { x.unwrap(); }\n"; - assert_eq!(production_half(declared), "mod a;\n\n\nfn real() { x.unwrap(); }"); - let konst = "#[cfg(test)]\n#[allow(dead_code)]\nstatic LOCK: Lazy =\n Lazy::new(|| M::new());\nfn real() { y.unwrap(); }\n"; - assert!(production_half(konst).ends_with("fn real() { y.unwrap(); }")); - assert!(!production_half(konst).contains("LOCK")); - let mid = "#[cfg(test)]\nmod tests {\n fn t() { let s = \"}\"; let c = '}'; }\n}\nfn after() { z.unwrap(); }\n"; - let p = production_half(mid); - assert!(p.contains("fn after()") && !p.contains("fn t()"), "{p:?}"); - assert_eq!(p.lines().count(), 5, "line numbers stay true"); - let helper = "fn real() {}\n#[cfg(test)]\nfn helper() {\n q.unwrap();\n}\nfn more() {}\n"; - assert_eq!(production_half(helper), "fn real() {}\n\n\n\n\nfn more() {}"); - // Regression for #5227: a same-line test item must not consume its successor. - let inline = "#[cfg(test)] mod tests {}\nfn real() { x.unwrap(); }\n"; - assert_eq!(production_half(inline), "\nfn real() { x.unwrap(); }"); - let inline_decl = "#[cfg(test)] mod tests;\nfn real() { x.unwrap(); }\n"; - assert_eq!(production_half(inline_decl), "\nfn real() { x.unwrap(); }"); - // A comment's semicolon cannot make the closed test module swallow production. - let commented = "#[cfg(test)]\nmod tests {\n} // diagnostic; not syntax\nfn real() { x.unwrap(); }\n"; - assert_eq!(production_half(commented), "\n\n\nfn real() { x.unwrap(); }"); - // Real constructor closing syntax still belongs to the gated static. - let constructor = "#[cfg(test)]\nstatic X: LazyLock<()> = LazyLock::new(|| {\n});\nfn real() { x.unwrap(); }\n"; - assert_eq!(production_half(constructor), "\n\n\nfn real() { x.unwrap(); }"); - // Regression for the first proposed fix: initializer blocks do not end a static. - for initializer in [ - "{1} + { let y = 2;\n const EXTRA_LIMIT: usize = 9;\n y + EXTRA_LIMIT\n}", - "{1usize}.wrapping_add({ let y = 2;\n const EXTRA_LIMIT: usize = 9;\n y + EXTRA_LIMIT\n})", - "[ { let y = 2;\n const EXTRA_LIMIT: usize = 9;\n y + EXTRA_LIMIT\n} ][0]", - ] { - for declaration in [ - "static X", "const X", "pub(in crate::owner) const X", - "pub\nconst X", "pub /* comment */ (crate) const X", - "pub // visibility\n(in crate::owner) static X", - ] { - let raw = format!("#[cfg(test)]\n{declaration}: usize = {initializer};\nfn real() {{ x.unwrap(); }}\n"); - let projected = production_half(&raw); - assert!(!projected.contains("EXTRA_LIMIT"), "{projected}"); - assert_eq!(projected.lines().last(), Some("fn real() { x.unwrap(); }")); - assert_eq!(projected.lines().count(), raw.lines().count(), "line positions"); - } - } - // Const functions still end with their body, even when a comment has punctuation. - let konst_fn = "#[cfg(test)]\nconst fn helper() -> usize { 1 } // ;\nfn real() { x.unwrap(); }\n"; - assert_eq!(production_half(konst_fn), "\n\nfn real() { x.unwrap(); }"); - // Regression for proposed revision 4: nested comment delimiters are never code. - let nested = "#[cfg(test)]\nfn helper() { /* outer /* inner */ ( [ { ;\n tail ) ] } */ }\nfn production() { x.unwrap(); }\n"; - assert_eq!(production_half(nested), "\n\n\nfn production() { x.unwrap(); }"); - let open_delimiter = "#[cfg(test)]\nfn helper() { /* outer /* inner */ ( */ }\nfn production() { x.unwrap(); }\n"; - assert_eq!(production_half(open_delimiter), "\n\nfn production() { x.unwrap(); }"); - - // Regression for proposed revision 2: comments are whitespace between keywords. - for trivia in ["/* explanation */", "// explanation\n", "/* outer /* nested */ tail */"] { - let raw = format!("#[cfg(test)]\nconst {trivia} fn helper() -> usize {{ 1 }}\nfn production() {{ x.unwrap(); }}\n"); - let projected = production_half(&raw); - assert_eq!(projected.lines().last(), Some("fn production() { x.unwrap(); }")); - assert!(!projected.contains("helper")); - assert_eq!(projected.lines().count(), raw.lines().count()); - } - - - - } - - /// What this catches: the production/test split silently swallowing the whole - /// file (or none of it), which would make every rule vacuously green or wildly - /// noisy. The split is an approximation and this pins WHICH approximation. - #[test] - fn production_half_stops_at_the_first_cfg_test() { - let root = crate_src_root(); - assert!(root.join("lib.rs").is_file(), "src root resolved wrong"); - - struct Collect; - impl SourceRule for Collect { - fn name(&self) -> &'static str { - "collect" - } - fn check(&self, file: &SourceFile) -> Vec { - // This module's own tests live below a `#[cfg(test)]`, so the - // production half must NOT contain this very marker string. - if file.rel == "source_hygiene/mod.rs" && file.production.contains("mod tests") { - return vec![Violation { - rule: "collect", - file: file.rel.clone(), - line: 0, - source: "test mod leaked into the production half".into(), - }]; - } - Vec::new() - } - } - assert!(scan(&[&Collect]).is_empty()); - } } -pub mod vendor_pin; diff --git a/core/source-hygiene/src/os_branches.rs b/core/source-hygiene/src/os_branches.rs index b8eb64d7b5..ccbdb5451e 100644 --- a/core/source-hygiene/src/os_branches.rs +++ b/core/source-hygiene/src/os_branches.rs @@ -37,7 +37,7 @@ impl SourceRule for OsBranches { fn check(&self, file: &SourceFile) -> Vec { file.production_lines() .filter(|(_, l)| { - let code = crate::split_code_and_comment(l).0; + let code = crate::lexer::split_code_and_comment(l).0; branches_on_os(code) }) .map(|(n, l)| Violation { rule: self.name(), file: file.rel.clone(), line: n, source: l.trim().to_string() }) diff --git a/core/source-hygiene/src/production_reachability.rs b/core/source-hygiene/src/production_reachability.rs index 883959aa64..38cedccca4 100644 --- a/core/source-hygiene/src/production_reachability.rs +++ b/core/source-hygiene/src/production_reachability.rs @@ -58,7 +58,7 @@ //! against this crate; references are searched across every workspace root. See //! [`super::workspace_src_roots`]. -use super::{split_code_and_comment, CrateRule, SourceFile, Violation}; +use super::{lexer::split_code_and_comment, CrateRule, SourceFile, Violation}; use std::collections::HashMap; /// Constructor shapes that mark a type as machinery someone is meant to stand up. @@ -165,7 +165,7 @@ impl ProductionReachability { if own_impl_depth.is_some() && CONSTRUCTOR_SHAPES.iter().any(|s| code.contains(s)) { return true; } - let delta = crate::brace_delta(code); + let delta = crate::lexer::brace_delta(code); depth += delta; // `delta < 0` closes a multi-line impl; a one-line `impl X {}` (delta 0) opens // and closes on its own line and must not stay open over the rest of the file. @@ -301,11 +301,7 @@ mod tests { impl AgentContext {\n pub async fn bootstrap() -> Self { Self {} }\n}\n\ #[cfg(test)]\nmod tests {\n fn t() { let _ = AgentContext::bootstrap(); }\n}\n"; let production = own.split("#[cfg(test)]").next().unwrap_or(own); // the split marker is present by construction above - let file = SourceFile { - rel: "context/agent.rs".into(), - production: production.into(), - raw: own.into(), - }; + let file = SourceFile::fixture("context/agent.rs", production, own); let corpus = format!( "{own}\npub use agent::{{AgentContext, AgentMetadata}};\n/// `AgentContext` (Slice 4)\n" ); @@ -331,8 +327,8 @@ mod tests { #[cfg(test)]\nmod tests;\n"; let tests = "//! Tests for agent.\n#![cfg(test)]\nuse super::*;\nfn t() { let _ = AgentContext::bootstrap(); }\n"; let files = [ - SourceFile { rel: "context/agent.rs".into(), production: own.into(), raw: own.into() }, - SourceFile { rel: "context/agent/tests.rs".into(), production: String::new(), raw: tests.into() }, + SourceFile::fixture("context/agent.rs", own, own), + SourceFile::fixture("context/agent/tests.rs", "", tests), ]; assert_eq!(files[1].owning_module(), "context/agent"); let corpus = format!("{own}\n{tests}"); @@ -345,38 +341,31 @@ mod tests { /// the wrong question — and flagging every wire DTO would bury the real findings. #[test] fn a_plain_data_carrier_is_not_machinery() { - let dto = SourceFile { - rel: "wire.rs".into(), - production: "pub struct Payload {\n pub id: String,\n}\n".into(), - raw: "pub struct Payload {\n pub id: String,\n}\n".into(), - }; + let dto_src = "pub struct Payload {\n pub id: String,\n}\n"; + let dto = SourceFile::fixture("wire.rs", dto_src, dto_src); assert!(!ProductionReachability::is_machinery(&dto, "Payload")); - let machine = SourceFile { - rel: "thing.rs".into(), - production: "pub struct Runner {}\nimpl Runner {\n pub fn new() -> Self { Self {} }\n}\n" - .into(), - raw: "pub struct Runner {}\nimpl Runner {\n pub fn new() -> Self { Self {} }\n}\n".into(), - }; + let machine_src = "pub struct Runner {}\nimpl Runner {\n pub fn new() -> Self { Self {} }\n}\n"; + let machine = SourceFile::fixture("thing.rs", machine_src, machine_src); assert!(ProductionReachability::is_machinery(&machine, "Runner")); // what this catches (review of #4672): a constructor on ANOTHER type in the file // made every pub type there read as machinery. let neighbour = "pub enum Outcome { A }\nimpl Outcome {\n pub fn ok(&self) -> bool { true }\n}\nstruct Scratch;\nimpl Scratch {\n fn new() -> Self { Scratch }\n}\n"; - let mixed = SourceFile { rel: "mixed.rs".into(), production: neighbour.into(), raw: neighbour.into() }; + let mixed = SourceFile::fixture("mixed.rs", neighbour, neighbour); assert!(!ProductionReachability::is_machinery(&mixed, "Outcome")); assert!(ProductionReachability::is_machinery(&mixed, "Scratch")); // what this also catches (Astra, review of #4678): a "}" inside a string closed // the impl early, so the constructor after it was missed. let stringy = "pub struct Runner {}\nimpl Runner {\n fn label() -> &'static str { \"}\" }\n pub fn new() -> Self { Runner {} }\n}\n"; - let quoted = SourceFile { rel: "stringy.rs".into(), production: stringy.into(), raw: stringy.into() }; + let quoted = SourceFile::fixture("stringy.rs", stringy, stringy); assert!(ProductionReachability::is_machinery("ed, "Runner")); // what this also catches (Cormac, review of #4678): a one-line empty impl stayed // open, so a later neighbour's constructor counted as this type's. let empty = "pub struct Marker;\nimpl Marker {}\nstruct Other;\nimpl Other {\n fn new() -> Self { Other }\n}\n"; - let one_line = SourceFile { rel: "empty.rs".into(), production: empty.into(), raw: empty.into() }; + let one_line = SourceFile::fixture("empty.rs", empty, empty); assert!(!ProductionReachability::is_machinery(&one_line, "Marker")); } } diff --git a/core/source-hygiene/src/ratchet.rs b/core/source-hygiene/src/ratchet.rs index 4052d5ddae..3fb574e48c 100644 --- a/core/source-hygiene/src/ratchet.rs +++ b/core/source-hygiene/src/ratchet.rs @@ -16,11 +16,14 @@ //! - `SOURCE_HYGIENE_RECORD=`: record every count as `name count` (both runs). //! - `SOURCE_HYGIENE_BASE=`: judge every count against the recorded base (the head run). -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io::Write; +use crate::Violation; + const RECORD: &str = "SOURCE_HYGIENE_RECORD"; const BASE: &str = "SOURCE_HYGIENE_BASE"; +const TOUCHED: &str = "SOURCE_HYGIENE_TOUCHED"; /// Hold the ratchet `name` at `count`. Record it, judge it against the base, or report it, /// by the environment the script sets. `advice` is rendered only on a failure: what to do @@ -46,6 +49,33 @@ pub fn hold(name: &str, count: usize, advice: impl FnOnce() -> String) { eprintln!("{name}: {before} -> {count}"); } +/// Judge that a change leaves none of `name`'s violations in a file it touched. The driver +/// lists the change's files (repository paths, one per line) in `SOURCE_HYGIENE_TOUCHED` for +/// the head run; unset, as in the base run or a plain `cargo test`, there is nothing to judge. +/// This is what moves a count to zero: a file is cleaned by whoever next changes it. +pub fn touched_clean(name: &str, violations: &[Violation], advice: impl FnOnce() -> String) { + let Ok(path) = std::env::var(TOUCHED) else { + return; + }; + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(e) => panic!("cannot read the touched-file list {path}: {e}"), + }; + let touched: BTreeSet<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + let dirty: Vec = violations + .iter() + .filter(|v| touched.contains(v.file.as_str())) + .map(|v| format!(" {}:{} {}", v.file, v.line, v.source)) + .collect(); + assert!( + dirty.is_empty(), + "{name}: {} site(s) remain in files this change touches; a touched file leaves with none. {}\n{}", + dirty.len(), + advice(), + dirty.join("\n") + ); +} + /// One line per count. A ratchet runs in its own test thread, and a single short append is /// one `write` on an `O_APPEND` file, so concurrent records do not interleave. fn record(path: &str, name: &str, count: usize) { diff --git a/core/source-hygiene/src/subprocess_spawn.rs b/core/source-hygiene/src/subprocess_spawn.rs index 0fecf32b20..7cc721137f 100644 --- a/core/source-hygiene/src/subprocess_spawn.rs +++ b/core/source-hygiene/src/subprocess_spawn.rs @@ -23,7 +23,7 @@ //! //! A real subprocess (llama-server, git, cargo, a benchmark's own test runner, the //! browser) is fine — through `bounded_command`, with a bound and a named outcome. -use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; +use super::{lexer::split_code_and_comment, SourceFile, SourceRule, Violation}; /// Programs that a library, module, or std already answers for. The replacement is /// the rule's message, so the site that trips it also says what to write instead. diff --git a/core/source-hygiene/src/tenant_neutrality.rs b/core/source-hygiene/src/tenant_neutrality.rs index e5512a337c..a1ffb658a3 100644 --- a/core/source-hygiene/src/tenant_neutrality.rs +++ b/core/source-hygiene/src/tenant_neutrality.rs @@ -14,7 +14,7 @@ //! URLs (the airc installer and the model-card attribution link), which name where //! the software comes from, not whose org is using it. -use super::{split_code_and_comment, SourceFile, SourceRule, Violation}; +use super::{lexer::split_code_and_comment, SourceFile, SourceRule, Violation}; /// The tenant identities that must never appear in production code. Lower-case; /// matched case-insensitively against CODE (string literals included — a URL is diff --git a/core/source-hygiene/src/test_mod_singularity.rs b/core/source-hygiene/src/test_mod_singularity.rs index 944641c3f9..93980730d8 100644 --- a/core/source-hygiene/src/test_mod_singularity.rs +++ b/core/source-hygiene/src/test_mod_singularity.rs @@ -94,11 +94,7 @@ mod tests { /// error direction makes the ratchet meaningless. #[test] fn only_gated_mods_count_and_the_first_is_free() { - let mk = |src: &str| SourceFile { - rel: "fake.rs".into(), - production: String::new(), - raw: src.into(), - }; + let mk = |src: &str| SourceFile::fixture("fake.rs", "", src); let rule = TestModSingularity; assert_eq!(rule.check(&mk("#[cfg(test)]\nmod tests {}")).len(), 0, "one mod is sanctioned"); assert_eq!( diff --git a/core/source-hygiene/src/time_bounds.rs b/core/source-hygiene/src/time_bounds.rs new file mode 100644 index 0000000000..d258c3c007 --- /dev/null +++ b/core/source-hygiene/src/time_bounds.rs @@ -0,0 +1,185 @@ +//! **A duration or a rate is DERIVED from a measurement, or it is a NAMED FLOOR that says so.** +//! +//! # The class +//! +//! A static number standing in for a time or a rate the substrate already measures. The +//! defects that made this rule (2026-09-19/20): +//! +//! | The constant | What it cost | +//! |---|---| +//! | a flat 10 s KV-page wedge bound, sized from the M5's 0.1 s (#4287) | cut off legitimate page saves on the 5090 | +//! | `PREFILL_TARGET_SECONDS × CONSERVATIVE_PREFILL_TOKENS_PER_S` | a 500 t/s assumption no box in the fleet met, clipping every conversation to 15,000 tokens | +//! +//! Sizes (tokens, bytes, counts, shares) are `budget_discipline::SelfSized`'s class: they are +//! granted by the one allocation and allow no exemption. Durations have no owner to take +//! their value from yet (a cadence ladder and measured deadlines), so this rule still +//! accepts a `derived-or-floor: ` justification and only holds its count; when the time +//! owner exists, the marker goes the way of the size exemptions. +//! +//! # A ratchet +//! +//! The count may never rise; every touched duration is a chance to lower it. + +use super::budget_discipline::is_duration_name; +use super::{lexer::split_code_and_comment, SourceFile, SourceRule, Violation}; + +/// The marker a constant spends to say it is deliberately a constant. +pub const JUSTIFICATION_MARKER: &str = "derived-or-floor:"; + +/// A justification has to say something. Same bar, and the same reasoning, as the unwrap +/// ratchet's [`super::unwrap_justification`]: a marker with nothing after it is the SHAPE +/// of a reason, which is worse than no marker at all because it silences the guard. +// derived-or-floor: a FLOOR on the length of a COMMENT a human types — it bounds prose, never a token, a second or a rate, and there is nothing here to measure +// context-budget-exempt: this bounds the length of a COMMENT, not a window, prompt or +// token budget — the de-hardcode guard matches it on the `CHARS` suffix alone, which is +// that guard erring toward noise on purpose (same exemption its sibling in +// `unwrap_justification` spends, for the same reason). +const MIN_REASON_CHARS: usize = 16; + +/// The trees a live cognition / serving turn actually runs through. Violations are raised +/// only here: `audio_constants.rs` and the video renderer are full of constants that are +/// PHYSICS (a sample rate, a frame budget), and flagging them would bury the findings +/// that matter under noise — the way a guard earns being deleted. +const LIVE_PATHS: &[&str] = &[ + "cognition/", + "inference/", + "persona/", + "governor/", + "paging/", + "runtime/", + "capacity/", + "system_resources/", +]; + + +pub struct TimeBounds; + +impl TimeBounds { + /// Does the marker appear with a real reason after it — on this line, or in the + /// contiguous comment block directly above it? + /// + /// The block-above form exists because a `const` carries a doc comment, not a + /// trailing one; the same allowance the de-hardcode guard makes, for the same reason. + fn justified(lines: &[&str], index: usize) -> bool { + let reason_on = |text: &str| { + text.split_once(JUSTIFICATION_MARKER) + .is_some_and(|(_, why)| why.trim().chars().count() >= MIN_REASON_CHARS) + }; + if let Some(comment) = split_code_and_comment(lines[index]).1 { + if reason_on(comment) { + return true; + } + } + lines[..index] + .iter() + .rev() + .take_while(|l| { + let t = l.trim_start(); + t.starts_with("//") || t.is_empty() + }) + .any(|l| reason_on(l)) + } +} + +impl SourceRule for TimeBounds { + fn name(&self) -> &'static str { + "underived_duration" + } + + fn check(&self, file: &SourceFile) -> Vec { + // Vendored upstream ports carry the upstream model's own numbers; they are not + // ours to restyle. + if file.rel.contains("vendored/") { + return Vec::new(); + } + let lines: Vec<&str> = file.raw.lines().collect(); + let live = LIVE_PATHS.iter().any(|p| file.rel.starts_with(p)); + let mut out = Vec::new(); + for (line_no, line) in file.production_lines() { + let (code, _) = split_code_and_comment(line); + if Self::justified(&lines, line_no - 1) { + continue; + } + // A constant times a constant is the shape wherever it appears — it needs no + // live-path test, because it IS the defect this guard was written for. + if let Some((l, r)) = crate::lexer::constant_product(code).filter(|(l, r)| is_duration_name(l) || is_duration_name(r)) { + out.push(Violation { + rule: "underived_duration", + file: file.rel.clone(), + line: line_no, + source: format!("{l} * {r} — a bound with no measurement in it"), + }); + continue; + } + if !live { + continue; + } + if let Some((name, ty, value)) = crate::lexer::numeric_const(code) { + if is_duration_name(name) && crate::lexer::is_bare_literal(value) { + out.push(Violation { + rule: "underived_duration", + file: file.rel.clone(), + line: line_no, + source: format!("const {name}: {ty} = {value}"), + }); + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scan; + + /// What this catches: a new duration or rate landing as a constant with nothing measured + /// behind it and no line saying why a constant is right there. + #[test] + fn underived_durations_never_increase() { + let violations = scan(&[&TimeBounds]); + let count = violations.len(); + crate::ratchet::hold("underived_durations", count, || { + format!( + "underived, unjustified durations rose to {count}. Derive it from what the substrate \ + measures (`inference::prefill_rate`, `inference::decode_knee`), or say on the line or \ + in the block above why a constant is right there:\n // {JUSTIFICATION_MARKER} \n\ + First {} of {count} (not necessarily new):\n{}", + count.min(15), + violations.iter().take(15).map(|v| format!(" {}:{} {}", v.file, v.line, v.source)).collect::>().join("\n") + ) + }); + } + + /// What this catches: the guard going blind below a test-only helper gated inside an + /// `impl` (a production split that cut at the first `#[cfg(test)]` reported nothing below). + #[test] + fn a_mid_file_cfg_test_helper_does_not_blind_the_scan() { + let raw = "impl Faculty {\n #[cfg(test)]\n fn helper() {}\n}\n\ + let cap = TARGET_SECONDS * CONSERVATIVE_TOKENS_PER_S;\n\ + #[cfg(test)]\nmod tests {}\n"; + let file = SourceFile::fixture("cognition/llm_deliberation_faculty.rs", &crate::lexer::production_half(raw), raw); + let found = TimeBounds.check(&file); + assert_eq!(found.len(), 1, "the product below an indented #[cfg(test)] must still be seen"); + assert_eq!(found[0].line, 5); + } + + /// What this catches: the predicates that make the rule useful rather than noise: a + /// duration product and a bare duration are found, a derivation and a real reason pass, + /// and a size is not this rule's class. + #[test] + fn a_duration_is_found_a_reason_passes_and_a_size_is_not_its_class() { + let count = |rel: &str, raw: &str| TimeBounds.check(&SourceFile::fixture(rel, raw, raw)).len(); + assert_eq!(count("cognition/x.rs", "let c = A_SECONDS * B_TOKENS_PER_S;"), 1); + assert_eq!(count("cognition/x.rs", "const PAGE_WEDGE_TIMEOUT_MS: u64 = 10_000;"), 1); + for visibility in ["pub", "pub(crate)", "pub(super)", "pub(in crate::owner)"] { + assert_eq!(count("cognition/x.rs", &format!("{visibility} const PAGE_WEDGE_TIMEOUT_MS: u64 = 10_000;")), 1, "{visibility}"); + } + assert_eq!(count("cognition/x.rs", "const PAGE_WEDGE_TIMEOUT_MS: u64 = MEASURED_P99_MS * 4;"), 0, "a derivation"); + assert_eq!(count("cognition/x.rs", "const PAGE_WEDGE_TIMEOUT_MS: u64 = 10_000; // derived-or-floor: ok"), 1, "a marker with no reason"); + assert_eq!(count("cognition/x.rs", "// derived-or-floor: the protocol's own stated deadline, not ours\nconst ACK_DEADLINE_MS: u64 = 500;"), 0); + assert_eq!(count("cognition/x.rs", "const FILL_CAP_TOKENS: usize = 15_000;"), 0, "a size is SelfSized's class"); + assert_eq!(count("audio_constants.rs", "const SILENCE_THRESHOLD_MS: u64 = 704;"), 0, "off a live path"); + } +} diff --git a/core/source-hygiene/src/unwrap_justification.rs b/core/source-hygiene/src/unwrap_justification.rs index d44002b5d0..6cedeebb61 100644 --- a/core/source-hygiene/src/unwrap_justification.rs +++ b/core/source-hygiene/src/unwrap_justification.rs @@ -30,9 +30,9 @@ //! //! A same-line `//` comment with real content (see [`MIN_JUSTIFICATION_CHARS`]) — //! not `// ok`, not `// fixme`. String-literal-aware, so a `//` inside a URL is not -//! mistaken for a comment (see [`super::split_code_and_comment`]). +//! mistaken for a comment (see [`super::lexer::split_code_and_comment`]). -use super::{split_code_and_comment, SourceRule, SourceFile, Violation}; +use super::{lexer::split_code_and_comment, SourceRule, SourceFile, Violation}; /// A justification has to say something. `// ok` and `// safe` are not reasons; they /// are the shape of a reason, which is worse than nothing because it silences the @@ -133,11 +133,7 @@ mod tests { #[test] fn a_token_comment_does_not_count_as_a_justification() { let rule = UnwrapJustification; - let mk = |src: &str| SourceFile { - rel: "fake.rs".into(), - production: src.into(), - raw: src.into(), - }; + let mk = |src: &str| SourceFile::fixture("fake.rs", src, src); assert_eq!(rule.check(&mk("let x = o.unwrap(); // ok")).len(), 1, "`// ok` is not a reason"); assert_eq!(rule.check(&mk("let x = o.unwrap();")).len(), 1, "no comment at all"); diff --git a/core/source-hygiene/src/wall_clock.rs b/core/source-hygiene/src/wall_clock.rs index ac092b6600..fef74ffa84 100644 --- a/core/source-hygiene/src/wall_clock.rs +++ b/core/source-hygiene/src/wall_clock.rs @@ -99,9 +99,8 @@ mod tests { fn the_wall_clock_is_read_only_by_epoch_ms() { // The crate's integration tests too: four of them kept their own clocks after the // library moved onto EpochMs, because the scan covered src/ only. - let tests_root = crate::crate_src_root().parent().expect("src has a parent").join("tests"); let mut violations = scan(&[&WallClockReadOnlyByEpochMs]); - for file in crate::collect_files(&tests_root) { + for file in crate::collect_files(&crate::scanned_checkout(), &format!("core/{}/tests", crate::AUDITED_CRATE)) { violations.extend(WallClockReadOnlyByEpochMs.check(&file).into_iter().map(|v| Violation { file: format!("tests/{}", v.file), ..v diff --git a/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md b/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md index 404aa3a07e..67b99bd7bc 100644 --- a/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md +++ b/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md @@ -263,7 +263,7 @@ The owner of this contract is [FOCUS-CONTRACT.md](FOCUS-CONTRACT.md); this secti the sources sized for 159k, and Aiko turned over every act. **The change, shipped as one:** -1. The `prompt_self_sizing` ratchet first (~40). It counts `ContextBudget::live|live_or_floor|from_window*`, +1. The `self_sized` ratchet first (`budget_discipline`, ONE-BUDGET.md slice 0; it absorbed `prompt_self_sizing`). It counts `ContextBudget::live|live_or_floor|from_window*`, the fraction methods, `_SHARE_DENOM`, and any `flex_allocate`/`FlexboxRagBudgetAdapter` outside the one allocation. 2. Migrate by prompt mass: conversation (one allocation, `compose_for_turn` delivers items), results, diff --git a/docs/architecture/FOCUS-CONTRACT.md b/docs/architecture/FOCUS-CONTRACT.md index 529f97f2db..71685719e0 100644 --- a/docs/architecture/FOCUS-CONTRACT.md +++ b/docs/architecture/FOCUS-CONTRACT.md @@ -99,7 +99,7 @@ Do not implement permanent lane reduction from a stale training-demand record. | Boundary | Coordinating owner | Deliverable | |---|---|---| -| Single allocation and sources; Positron/RAG semantics | Fable | Source migration, private sizing APIs and `prompt_self_sizing` ratchet at zero | +| Single allocation and sources; Positron/RAG semantics | Fable | Source migration, private sizing APIs and `self_sized` ratchet at zero | | Serving, inference and grid | Codex | Wants/grants consumer audit, capacity and handoff conformance, Windows running receipts | | Lived capture, Dreaming and genes | Cormac | Capture-after-allocation invariant, durable demand/recovery review and learning receipts | | Modality/provider integrations | Relevant existing module owners, coordinated by Fable | Same levels/cost/retrieval contract; no independent prompt budget | diff --git a/docs/architecture/PERSONA-COGNITION-PIPELINE.md b/docs/architecture/PERSONA-COGNITION-PIPELINE.md index 67c2d29fb9..955f329e9f 100644 --- a/docs/architecture/PERSONA-COGNITION-PIPELINE.md +++ b/docs/architecture/PERSONA-COGNITION-PIPELINE.md @@ -185,7 +185,7 @@ still exists and still has files in it, which reads as "working". `expand_command`, or `tool_executor::spill`), keeping the newest interaction whole and the full result reachable through its handle. One source that shrinks itself by its own number breaks the budget for every other source. Guarded by - `source-hygiene::head_cuts`; a cut that never reaches a prompt says `head-cut-ok: `. + `source-hygiene` `self_sized` (ONE-BUDGET.md); there is no exemption comment. - **DO NOT** silently substitute defaults when something fails. Surface typed errors. The operator decides policy. ([[no-fallbacks-ever]]) ---