diff --git a/crates/ledger-core/src/form1099.rs b/crates/ledger-core/src/form1099.rs index 6f17e822..055d1c9b 100644 --- a/crates/ledger-core/src/form1099.rs +++ b/crates/ledger-core/src/form1099.rs @@ -84,7 +84,7 @@ impl Form1099 { /// Why a vendor gets no 1099: the kind of payee no return is required /// for. Each has its authority ([`ExemptReason::citation`], -/// sources/irs-1099-payment-method.md); a decision adds the facts in +/// docs/spec/sources/irs-1099-payment-method.md); a decision adds the facts in /// words. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -430,8 +430,8 @@ pub fn check_new_decision(decisions: &[Dated1099], new: &Dated1099) -> Result-` the pinned bookspec has, a -/// `WB--` in `docs/spec/claims/`, a vendored or repo source -/// path that exists, or an external citation (a statute, an ASC -/// paragraph, an IRS publication, a standard). Declared decisions and -/// plan citations name their document the same way. A `BS-` or `WB-` id -/// that does not exist fails here, so a typo'd id cannot survive. -/// And no retired `rules.md` B-n citation remains outside `plan/` and -/// the two map files (`docs/spec/rules.md`, `docs/spec/claims/`). fn repo_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") } @@ -27,8 +42,27 @@ fn collect_rs(dir: &Path, out: &mut Vec) { } } -/// The ids in `text` that start with `prefix` (`BS-` or `WB-`), each cut -/// at the first character that cannot be in an id. +fn collect_all(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name == "target" || name == ".git" { + continue; + } + if path.is_dir() { + collect_all(&path, out); + } else { + out.push(path); + } + } +} + +/// The ids in `text` that start with `prefix`, each cut at the first +/// character that cannot be in an id. fn ids_in(text: &str, prefix: &str) -> Vec { let mut ids = Vec::new(); let mut rest = text; @@ -37,7 +71,6 @@ fn ids_in(text: &str, prefix: &str) -> Vec { .chars() .take_while(|c| c.is_ascii_alphanumeric() || *c == '-') .collect(); - // An id is prefix + area + '-' + number; keep only full shapes. let body = &tail[prefix.len()..]; if body .rsplit('-') @@ -69,51 +102,120 @@ const EXTERNAL: &[&str] = &[ "RFC ", ]; -fn source_line_ok( - line: &str, - root: &Path, - bs_ids: &BTreeSet, - wb_ids: &BTreeSet, - bad: &mut Vec, - at: &str, -) -> bool { - let Some(text) = line.split("SOURCE:").nth(1) else { - return true; +/// The number of source clauses checked must stay at or above this. +const CHECKED_FLOOR: usize = 300; +/// Clauses passing only through the declared or external free-text +/// branch. Edit this constant, on purpose, in the same commit that +/// changes the count. +const FREE_TEXT_COUNT: usize = 56; + +fn strip_comment(line: &str) -> Option { + let t = line.trim_start(); + t.strip_prefix("//!") + .or_else(|| t.strip_prefix("///")) + .or_else(|| t.strip_prefix("//")) + .map(|rest| rest.trim().to_string()) +} + +fn is_heading(content: &str) -> bool { + let Some((head, _)) = content.split_once(':') else { + return false; }; + !head.is_empty() + && head.len() <= 32 + && head.chars().filter(|c| c.is_ascii_uppercase()).count() >= 2 + && head + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || " _-/()".contains(c)) +} + +fn clean_token(token: &str) -> String { + token + .trim_start_matches(['`', '"', '\'', '(', '[', '{']) + .trim_end_matches(['`', '"', '\'', ')', ']', '}', ',', ';', ':', '.']) + .to_string() +} + +fn is_path_like(token: &str) -> bool { + [".md", ".rs", ".toml", ".json"] + .iter() + .any(|e| token.ends_with(e)) +} + +struct ClauseCtx<'a> { + root: &'a Path, + bs_ids: &'a BTreeSet, + wb_ids: &'a BTreeSet, + identifiers: &'a BTreeSet, + basenames: &'a BTreeSet, +} + +fn check_clause(clause: &str, ctx: &ClauseCtx<'_>, bad: &mut Vec, at: &str) -> bool { + // Returns true when the clause passes only through the free-text branch. + let Some(text) = clause.split("SOURCE:").nth(1) else { + return false; + }; + let mut errors: Vec = Vec::new(); let mut cited = false; for id in ids_in(text, "BS-") { cited = true; - if !bs_ids.contains(&id) { - bad.push(format!("{at}: unknown bookspec id {id}")); + if !ctx.bs_ids.contains(&id) { + errors.push(format!("unknown bookspec id {id}")); } } for id in ids_in(text, "WB-") { cited = true; - if !wb_ids.contains(&id) { - bad.push(format!("{at}: unknown product rule {id}")); + if !ctx.wb_ids.contains(&id) { + errors.push(format!("unknown product rule {id}")); } } - if cited { - return true; - } - // A repo path that exists (vendored sources, docs, the plan). - for token in text.split_whitespace() { - let token = token.trim_matches(|c| matches!(c, '`' | '"' | '\'' | ')' | ',' | ';' | '(')); - if token.contains('/') - && token - .rsplit('.') - .next() - .is_some_and(|e| ["md", "rs", "toml", "json"].contains(&e)) - && root.join(token).exists() - { - return true; + let mut has_path = false; + let mut has_ref = false; + for raw in text.split_whitespace() { + let token = clean_token(raw); + if token.contains("://") { + continue; } + if is_path_like(&token) { + let exists = if token.contains('/') { + ctx.root.join(&token).exists() + } else { + ctx.basenames.contains(&token) + }; + if exists { + has_path = true; + } else { + errors.push(format!("path {token} does not exist")); + } + } + if token.contains("::") { + let first = token.split("::").next().unwrap_or(""); + if first == "crate" || first.starts_with("ledger_") { + let last = token.rsplit("::").next().unwrap_or(""); + let ident: String = last + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if ctx.identifiers.contains(&ident) { + has_ref = true; + } else { + errors.push(format!("code reference {token} names nothing real")); + } + } + } + } + if !errors.is_empty() { + for e in errors { + bad.push(format!("{at}: {e}")); + } + return false; + } + if cited || has_path || has_ref { + return false; } if EXTERNAL.iter().any(|m| text.contains(m)) { return true; } - // Declared decisions, requirements, plan citations and named code - // contracts: each names the document or module that states it. let declared = text.contains("DECISION") || text.contains("CONVENTION") || text.contains("CHOICE") @@ -139,8 +241,7 @@ fn source_line_ok( return true; } bad.push(format!( - "{at}: SOURCE cites no rule or source that exists: {}", - line.trim() + "{at}: source clause cites no rule or source that exists" )); false } @@ -165,95 +266,215 @@ pub(crate) fn every_source_line_cites_an_existing_rule_or_source() { } assert!(!wb_ids.is_empty(), "the claims files hold product rules"); - let mut files = Vec::new(); - for crate_dir in std::fs::read_dir(root.join("crates")).expect("crates") { - let src = crate_dir.expect("a crate").path().join("src"); - if src.is_dir() { - collect_rs(&src, &mut files); + // Identifiers declared anywhere under crates/, and file basenames + // anywhere in the repo, for the path and code-reference checks. + let mut crate_files = Vec::new(); + collect_all(&root.join("crates"), &mut crate_files); + let mut identifiers = BTreeSet::new(); + for path in crate_files + .iter() + .filter(|p| p.extension().is_some_and(|e| e == "rs")) + { + let Ok(text) = std::fs::read_to_string(path) else { + continue; + }; + let words: Vec<&str> = text + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter(|w| !w.is_empty()) + .collect(); + for pair in words.windows(2) { + if matches!( + pair[0], + "fn" | "struct" | "enum" | "mod" | "const" | "type" | "trait" + ) { + identifiers.insert(pair[1].to_string()); + } } } + let mut all_files = Vec::new(); + collect_all(&root, &mut all_files); + let basenames: BTreeSet = all_files + .iter() + .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())) + .collect(); + + let mut files = Vec::new(); + for crate_dir in std::fs::read_dir(root.join("crates")).expect("crates") { + let base = crate_dir.expect("a crate").path(); + for sub in ["src", "tests"] { + let dir = base.join(sub); + if dir.is_dir() { + collect_rs(&dir, &mut files); + } + } + } + let fuzz_dir = root.join("fuzz"); + if fuzz_dir.is_dir() { + collect_rs(&fuzz_dir, &mut files); + } files.sort(); - assert!(!files.is_empty(), "crates/*/src holds sources"); + assert!(!files.is_empty(), "crates and fuzz hold sources"); let mut bad = Vec::new(); let mut checked = 0usize; + let mut free_text = 0usize; for path in &files { let text = std::fs::read_to_string(path).expect("a source file"); - for (i, line) in text.lines().enumerate() { - if !line.contains("SOURCE:") { + let lines: Vec<&str> = text.lines().collect(); + let mut i = 0usize; + while i < lines.len() { + let Some(content) = strip_comment(lines[i]) else { + i += 1; + continue; + }; + if !content.contains("SOURCE:") { + i += 1; continue; } checked += 1; let at = format!("{}:{}", path.display(), i + 1); - source_line_ok(line, &root, &bs_ids, &wb_ids, &mut bad, &at); + let mut clause = content.clone(); + let mut j = i + 1; + while j < lines.len() { + let Some(next) = strip_comment(lines[j]) else { + break; + }; + if next.is_empty() || is_heading(&next) || next.contains("SOURCE:") { + break; + } + clause.push(' '); + clause.push_str(&next); + j += 1; + } + let ctx = ClauseCtx { + root: &root, + bs_ids: &bs_ids, + wb_ids: &wb_ids, + identifiers: &identifiers, + basenames: &basenames, + }; + if check_clause(&clause, &ctx, &mut bad, &at) { + free_text += 1; + } + i = j.max(i + 1); } } - assert!(checked > 100, "SOURCE lines were found ({checked})"); + println!("source clauses checked: {checked}"); + println!("source clauses passing only through the free-text branch: {free_text}"); + assert!( + checked >= CHECKED_FLOOR, + "source clauses were found ({checked})" + ); + assert_eq!( + free_text, FREE_TEXT_COUNT, + "free-text source clauses changed on purpose only: edit FREE_TEXT_COUNT in the same commit" + ); assert!( bad.is_empty(), - "every SOURCE line cites a rule or source that exists:\n{}", + "every source clause cites a rule or source that exists:\n{}", bad.join("\n") ); } +fn retired_count(text: &str) -> usize { + let chars: Vec = text.chars().collect(); + let mut count = 0usize; + let mut i = 0usize; + while i < chars.len() { + if chars[i] == 'B' + && (i == 0 || !(chars[i - 1].is_alphanumeric() || chars[i - 1] == '_')) + && chars.get(i + 1) == Some(&'-') + { + let mut j = i + 2; + let mut value = 0usize; + let mut digits = 0usize; + while j < chars.len() && chars[j].is_ascii_digit() { + value = value * 10 + chars[j].to_digit(10).unwrap_or(0) as usize; + digits += 1; + j += 1; + } + if digits > 0 && (1..=45).contains(&value) { + count += 1; + } + i = j.max(i + 1); + } else { + i += 1; + } + } + count +} + #[test] pub(crate) fn no_retired_rule_reference_remains() { let root = repo_root(); - let mut files = Vec::new(); - for top in ["crates", "docs", "deploy", "scripts", ".github"] { - let dir = root.join(top); - if dir.is_dir() { - collect_text(&dir, &mut files); - } - } - for top in ["AGENTS.md", "README.md"] { - files.push(root.join(top)); - } - let map_a = root.join("docs/spec/rules.md"); - let claims = root.join("docs/spec/claims"); + // Deliberately kept occurrences: path and exact count. Any change + // in either direction edits this list, on purpose, in that commit. + let allow: &[(&str, usize)] = &[ + // Kept: user-visible evidence-source strings in program output. + ("crates/ledger-core/src/ledger.rs", 8), + // Kept: goldens are hand-verified expected output. + ( + "crates/ledger-store/tests/golden/draft_states_and_evidence_gate.json", + 2, + ), + // Kept: user-visible CPA package text in program output. + ("crates/ledger-package/src/package.rs", 1), + // Kept: user-visible tool description text in program output. + ("crates/ledger-mcp/src/tools/settlements.rs", 1), + // Kept: user-visible on-screen contribution note. + ("crates/ledger-gui/src/pages/projects.rs", 1), + ]; + let output = std::process::Command::new("git") + .args(["ls-files", "-z"]) + .current_dir(&root) + .output() + .expect("git ls-files"); + assert!(output.status.success(), "git ls-files succeeds"); + let listing = String::from_utf8_lossy(&output.stdout); let mut bad = Vec::new(); - for path in files { - if path == map_a || path.starts_with(&claims) { + let mut seen_allow: BTreeSet<&str> = BTreeSet::new(); + for rel in listing.split('\0').filter(|s| !s.is_empty()) { + if rel.starts_with("plan/") + || rel == "docs/spec/rules.md" + || rel.starts_with("docs/spec/claims/") + { continue; } + let path = root.join(rel); let Ok(text) = std::fs::read_to_string(&path) else { - continue; // binary + continue; }; - for (i, line) in text.lines().enumerate() { - if retired_ref(line) { - bad.push(format!("{}:{}: {}", path.display(), i + 1, line.trim())); + if text.contains('\0') { + continue; + } + // Whole-text scan: a reference wrapped across a newline and a + // comment prefix is still one occurrence of the number. + let count = retired_count(&text); + if count == 0 { + continue; + } + match allow.iter().find(|(p, _)| *p == rel) { + Some((_, expected)) => { + seen_allow.insert(rel); + if count != *expected { + bad.push(format!( + "{rel}: {count} kept occurrences, allow-list says {expected}" + )); + } } + None => bad.push(format!("{rel}: {count} retired rule reference(s)")), + } + } + for (p, _) in allow { + if !seen_allow.contains(p) { + bad.push(format!( + "{p}: allow-listed file has no kept occurrence left" + )); } } assert!( bad.is_empty(), - "no retired rule reference remains outside the map files:\n{}", + "no retired rule reference remains outside the map files and the allow-list:\n{}", bad.join("\n") ); } - -fn collect_text(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - collect_text(&path, out); - } else { - out.push(path); - } - } -} - -/// The retired form: filename, space, B- (the script that -/// performed the rewrite keeps the backticked form in its docs). -fn retired_ref(line: &str) -> bool { - let needle = ["rules.md ", "B-"].concat(); - line.find(&needle).is_some_and(|at| { - line[at + needle.len()..] - .chars() - .next() - .is_some_and(|c| c.is_ascii_digit()) - }) -} diff --git a/crates/ledger-core/tests/form1099.rs b/crates/ledger-core/tests/form1099.rs index c45db33b..27f1ef33 100644 --- a/crates/ledger-core/tests/form1099.rs +++ b/crates/ledger-core/tests/form1099.rs @@ -219,7 +219,7 @@ fn cash_paid_per_vendor_and_who_is_reportable() { #[test] fn years_and_thresholds() { let l = books(); - // SOURCE: BS-1099-1 (sources/irs-1099-thresholds.md; Pub. L. + // SOURCE: BS-1099-1 (docs/spec/sources/irs-1099-thresholds.md; Pub. L. // 119-21 §70433(f): payments made after December 31, 2025). assert_eq!(default_threshold(2025), Ok(dec("600"))); assert_eq!(default_threshold(2026), Ok(dec("2000"))); diff --git a/crates/ledger-core/tests/spec_bounds.rs b/crates/ledger-core/tests/spec_bounds.rs index 56b4574d..9bf2e97f 100644 --- a/crates/ledger-core/tests/spec_bounds.rs +++ b/crates/ledger-core/tests/spec_bounds.rs @@ -13,8 +13,10 @@ //! ledger unchanged; a replayed line an earlier version wrote past //! the same bound is accepted exactly as written. //! SOURCE: DECISION (P0 review round 3, 2026-10-16, S1; round 4, -//! 2026-10-17); kernel.rs MAX_LINE_AMOUNT (rules.md: a line over a -//! quadrillion is a mistake); calendar.rs (four-digit years). +//! 2026-10-17); `crates/ledger-core/src/kernel/entries.rs` +//! MAX_LINE_AMOUNT (BS-entry-4: a line over a +//! quadrillion is a mistake); `crates/ledger-core/src/calendar.rs` +//! (four-digit years). //! ``` use chrono::{Datelike, NaiveDate}; diff --git a/crates/ledger-gui/src/books.rs b/crates/ledger-gui/src/books.rs index 6ae5d547..911753d8 100644 --- a/crates/ledger-gui/src/books.rs +++ b/crates/ledger-gui/src/books.rs @@ -1505,8 +1505,8 @@ impl Books { /// /// ```text /// GOAL: the monthly close leaves every bank and card account - /// reconciled through last month's end (docs/parties-and- - /// attachments.md, Reconciliations: "an account with activity + /// reconciled through last month's end + /// (docs/parties-and-attachments.md, Reconciliations: "an account with activity /// not reconciled through last month's end"). /// SOURCE: that rule; CONVENTION (a bank or card statement closes /// monthly; AGENTS.md's monthly close reconciles the bank); diff --git a/crates/ledger-mcp/src/tools/instruments.rs b/crates/ledger-mcp/src/tools/instruments.rs index 0c870338..81085e66 100644 --- a/crates/ledger-mcp/src/tools/instruments.rs +++ b/crates/ledger-mcp/src/tools/instruments.rs @@ -8,7 +8,7 @@ //! GOAL: the agent records how each payment was made and why each vendor //! does or doesn't get a 1099, and the worksheet never guesses. //! SOURCE: BS-1099-1 (Treas. Reg. §1.6041-1(a)(1)(iv), -//! §1.6041-3; sources/irs-1099-payment-method.md); plan/served.md +//! §1.6041-3; docs/spec/sources/irs-1099-payment-method.md); plan/served.md //! 4.9; DECISION D-40 (owner, 2026-10-20). //! INVARIANTS: //! 1. A 1099 decision names who made it (decided_by; decided_on diff --git a/crates/ledger-mcp/src/tools/reconciliation.rs b/crates/ledger-mcp/src/tools/reconciliation.rs index efa24fc0..172c7140 100644 --- a/crates/ledger-mcp/src/tools/reconciliation.rs +++ b/crates/ledger-mcp/src/tools/reconciliation.rs @@ -100,8 +100,7 @@ impl BooksServer { /// ```text /// GOAL: a monthly reconciliation that leaves proof: which statement, /// which balance, which lines it cleared. - /// SOURCE: CONVENTION (bank reconciliation); docs/parties-and- - /// attachments.md "Reconciliations"; Store::complete_reconciliation. + /// SOURCE: CONVENTION (bank reconciliation); docs/parties-and-attachments.md "Reconciliations"; Store::complete_reconciliation. /// INVARIANTS: /// 1. Without confirmed=true nothing is recorded: the preview reports /// the difference, the cleared and uncleared lines, and the diff --git a/crates/ledger-package/src/tins.rs b/crates/ledger-package/src/tins.rs index 3c558d50..ec3fb04f 100644 --- a/crates/ledger-package/src/tins.rs +++ b/crates/ledger-package/src/tins.rs @@ -5,8 +5,7 @@ //! GOAL: a worksheet for the CPA carries a TIN only when the vault and the //! books agree on it, and says why when it can't. //! SOURCE: DECISION (owner, 2026-10-15): the vault holds every member's -//! and payee's full TIN for the CPA package; docs/parties-and- -//! attachments.md "The TIN vault". +//! and payee's full TIN for the CPA package; docs/parties-and-attachments.md "The TIN vault". //! INVARIANTS: //! 1. The party's TIN facts, when on file, have the vault TIN's type and //! last four, and the record's hash when they name one. diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 9e2f3f70..8ccc35d0 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -5186,8 +5186,8 @@ impl Store { /// /// ```text /// GOAL: rename an account, keeping the name it had in the journal. - /// SOURCE: BS-ledger-10; Rev. Proc. 98-25 (docs/spec/sources/ - /// irs-records.md): a report printed under the old name can + /// SOURCE: BS-ledger-10; Rev. Proc. 98-25 + /// (docs/spec/sources/irs-records.md): a report printed under the old name can /// be tied to the new one. /// INVARIANTS: /// 1. Only the account's name changes (Ledger::rename_account @@ -5967,8 +5967,8 @@ impl Store { /// ```text /// GOAL: a monthly close that leaves proof: which statement, which /// balance, which lines it cleared. - /// SOURCE: CONVENTION (bank reconciliation); docs/parties-and- - /// attachments.md "Reconciliations"; DECISION (owner, + /// SOURCE: CONVENTION (bank reconciliation); + /// docs/parties-and-attachments.md "Reconciliations"; DECISION (owner, /// 2026-10-15). /// INVARIANTS: /// 1. Recorded only when the difference is exactly zero diff --git a/crates/ledger-store/tests/bounds.rs b/crates/ledger-store/tests/bounds.rs index 3dcd79c2..7afa4b9c 100644 --- a/crates/ledger-store/tests/bounds.rs +++ b/crates/ledger-store/tests/bounds.rs @@ -9,8 +9,8 @@ //! run without end; no journal line an earlier version wrote is //! refused for a bound added after it. //! SOURCE: DECISION (P0 review round 3, 2026-10-16, S1; round 4, -//! 2026-10-17); ledger_core calendar.rs and kernel.rs -//! MAX_LINE_AMOUNT. +//! 2026-10-17); ledger_core `crates/ledger-core/src/calendar.rs` +//! and `crates/ledger-core/src/kernel/entries.rs` MAX_LINE_AMOUNT. //! ``` use chrono::NaiveDate;