config, mcp, gui: specs from sources, spec-blind suites, and the bugs they found
check / check (push) Canceled after 0s

ledger-config: parse gets a sourced spec. A fiscal year starts on the
first of a month (IRS Pub. 538); tax_classification is read by whole
words (Treas. Reg. 301.7701-3, Schedule C instructions; "business corp"
no longer reads as an S corp, "corporation or S corporation" is refused);
duplicate or blank members and shared capital accounts are refused; a
negative or non-grammatical receipt threshold is refused; codes trimmed.
tests/spec_config.rs (65 spec-blind tests, 14 properties), fuzz target
fuzz_config_parse (weekly). Mutation: 55 of 55 viable caught (from 25/38).

The receipt policy moves to ledger-config, with one loader
(effective_receipt_policy) and one decimal grammar, so the server and
the viewer enforce and show the same rule (the viewer had its own: only
expense-like debits, a silent $25 default, and no config.json).

ledger-mcp: a module spec (MCP 2025-06-18 tools, JSON-RPC 2.0, the
operating contract). Amounts in are exactly -?digits[.digits]; a number
that is one account's code and another's id (vendors, classes alike) is
refused, not guessed; the threshold is validated at startup. Fixed:
add_line with a bad class journaled the line before refusing;
profit_and_loss_by_class ignored `class`; aging buckets said "0". A wire
in front of rmcp answers malformed JSON with -32700 and invalid requests
with -32600 and their id (rmcp dropped the first, omitted the id).
tests/spec_mcp.rs (26 spec-blind tests: every tool's result against its
own outputSchema, a random-call state machine checking the journal is
untouched by every refusal, amount grammar, previews, the receipt policy).

ledger-gui: money, accounting, and dollars never round (they rounded to
cents, banker's style); export file names avoid Windows device names,
trailing dots and spaces, empty names, and 255-byte overflow; specs on
attention, history, fuzzy search, and axis ticks.

ledger-core: the lifetime profit_and_loss is renamed unclosed_earnings
(docs/testing.md #3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GWVo7x3UHw5kwCUaWxiejX
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-10-14 10:13:05 -06:00
1 parent 5b8910a1cd
commit 3f20df9700
42 files changed
+4636 -363

No files matched your search

+26 -2
View File
@@ -12,6 +12,30 @@ use ledger_core::reports::profit_and_loss_for_period;
use ledger_core::{AccountType, EntryStatus, PeriodStatus, vendor_1099_report};
use rust_decimal::Decimal;
/// Everything the books need, as items to show.
///
/// ```text
/// GOAL: tell the humans what's unfinished or wrong, and hand them the
/// prompt that gets the agent to fix it; never change the books.
/// SOURCE: DECISION (Stephen: the viewer is read-only; its "Needs
/// attention" list offers prompts, AGENTS.md); the conditions
/// below; docs/spec/sources/irs-1099-thresholds.md (W-9s).
/// INVARIANTS:
/// 1. Pure: reads `b`, writes nothing.
/// 2. One item per: draft entry (Todo); posted entry missing a receipt
/// (Problem; four or more are one combined item); recurring entry or
/// schedule due through today (Todo); period ended and still open
/// (Todo); fiscal-year account with activity and no tax category
/// (Info); legal rule known only through a past year (Todo); 1099
/// vendor without a W-9 (Problem); overdue bills, and overdue
/// invoices (Problem, one each, with the total); money owed to
/// owners (Info, per account with a balance); the database differing
/// from the journal or unreadable, and damaged or missing stored
/// files (Problem).
/// 3. Nothing else: books with none of those yield no items.
/// 4. Every item's prompt starts "In wanderbooks," or names
/// wanderbooks, and its amounts are the books' exact amounts.
/// ```
pub fn find(b: &Books) -> Vec<Attention> {
let mut out = Vec::new();
let today = b.today;
@@ -49,9 +73,9 @@ pub fn find(b: &Books) -> Vec<Attention> {
.collect();
out.push(Attention {
severity: Severity::Problem,
title: format!("{} without receipts", fmt::count(missing.len(), "expense", "expenses")),
title: format!("{} without receipts", fmt::count(missing.len(), "entry", "entries")),
detail: format!(
"{} of spending has no receipt attached ({}).",
"{} in entries with no receipt attached ({}).",
fmt::dollars(total),
b.receipt_rule()
),
+14 -21
View File
@@ -34,7 +34,7 @@ pub struct EntryInfo {
pub vendor: Option<String>,
pub reversal_of: Option<EntryId>,
pub reversed_by: Option<EntryId>,
/// Spending over the receipt threshold with no receipt.
/// Covered by the receipt policy (the server's rule) and has no receipt.
pub missing_receipt: bool,
/// Net effect on cash accounts: positive in, negative out, zero if the
/// entry doesn't touch cash.
@@ -162,11 +162,13 @@ impl Books {
let ledger = snap.ledger().clone();
let attachments = snap.attachments(None).map_err(|e| e.to_string())?;
let journal = snap.journal().to_vec();
let receipt_threshold = settings
.receipt_threshold
.as_deref()
.and_then(|t| t.parse().ok())
.unwrap_or(Decimal::new(25, 0));
// The server's own rule (config.json, else wanderbooks.toml), so
// the viewer flags exactly what the server would refuse.
let policy = ledger_config::effective_receipt_policy(
&snap.data_dir().join("config.json"),
&settings,
)?;
let receipt_threshold = policy.threshold();
let cash_accounts = cash_accounts(&ledger, &settings);
let codes = |cs: &[String]| -> Vec<AccountId> {
cs.iter()
@@ -238,23 +240,14 @@ impl Books {
.entry_vendor(id)
.and_then(|v| ledger.get_vendor(v))
.map(|v| v.name.clone());
// Receipts prove spending: hand-made entries (and recurring
// drafts) that debit an expense or buy an asset from outside.
// Invoices, payments, transfers, draws, closes, and schedules
// carry their own evidence.
let spends = e.lines().iter().any(|l| {
l.side == Side::Debit
&& ledger.chart().get(l.account).is_some_and(|a| {
a.account_type == AccountType::Expense
|| (a.account_type == AccountType::Asset
&& !cash_accounts.contains(&a.id)
&& !a.name.to_lowercase().contains("receivable"))
})
});
// The receipt policy covers what is posted by hand (journal
// entries and recurring drafts); invoices, payments, closes,
// depreciation, and schedules carry their own evidence, and a
// reversal leans on its original's.
let missing_receipt = matches!(origin, "Journal entry" | "Recurring")
&& spends
&& e.reversal_of().is_none()
&& rec.is_empty()
&& amount > receipt_threshold;
&& policy.receipt_required(&ledger, e);
let cash_effect: Decimal = e
.lines()
.iter()
+7
View File
@@ -15,6 +15,13 @@ fn f(d: Decimal) -> f64 {
d.try_into().unwrap_or(0.0)
}
/// ```text
/// INVARIANTS (finite lo <= hi, n >= 1):
/// 1. Evenly spaced by a step of 1, 2, 2.5, or 5 times a power of ten.
/// 2. The first tick is at or below lo and the last at or above hi, so
/// no data falls outside the gridlines.
/// 3. At most n + 2 ticks.
/// ```
/// "Nice" axis ticks covering [lo, hi].
fn ticks(lo: f64, hi: f64, n: usize) -> Vec<f64> {
let span = (hi - lo).max(1e-9);
+65 -1
View File
@@ -20,6 +20,23 @@ pub fn downloads_dir() -> PathBuf {
}
/// `name` made safe as a file name on every platform.
///
/// ```text
/// GOAL: a report title (company data) can never name a file outside the
/// downloads folder, or one a platform refuses.
/// SOURCE: docs/spec/sources/file-names.md (Microsoft's naming rules;
/// POSIX NAME_MAX).
/// INVARIANTS:
/// 1. The result is `<base>.<ext>`, `base` holding no reserved
/// character (< > : " / \ | ? *) and no control character: each is
/// replaced ('-' or a space).
/// 2. `base` is never empty, never "." or "..", never ends with a space
/// or a period, and is never a reserved device name (CON, NUL, COM1,
/// LPT¹, ... in any case, before its first period): such a base gets
/// a leading '_'.
/// 3. The whole name is at most 255 bytes of UTF-8, cut at a character
/// boundary.
/// ```
pub fn file_name(name: &str, ext: &str) -> String {
let clean: String = name
.chars()
@@ -29,7 +46,54 @@ pub fn file_name(name: &str, ext: &str) -> String {
c => c,
})
.collect();
format!("{}.{ext}", clean.trim())
let mut base = clean.trim().trim_end_matches(['.', ' ']).to_string();
if base.is_empty() {
base = "report".to_string();
}
let stem = base
.split('.')
.next()
.unwrap_or("")
.trim_end()
.to_uppercase();
let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| ["COM", "LPT"].iter().any(|p| {
stem.strip_prefix(p).is_some_and(|n| {
matches!(
n,
"1" | "2"
| "3"
| "4"
| "5"
| "6"
| "7"
| "8"
| "9"
| "\u{b9}"
| "\u{b2}"
| "\u{b3}"
)
})
});
if reserved {
base.insert(0, '_');
}
let limit = 255usize.saturating_sub(ext.len() + 1);
if base.len() > limit {
let mut cut = limit;
while !base.is_char_boundary(cut) {
cut -= 1;
}
base.truncate(cut);
// A cut can leave a trailing space or period: trim again.
while base.ends_with(['.', ' ']) {
base.pop();
}
if base.is_empty() {
base = "report".to_string();
}
}
format!("{base}.{ext}")
}
/// Write `bytes` to the downloads folder as `name.ext` (replacing a file
+49 -16
View File
@@ -1,36 +1,56 @@
//! Formatting money, dates, and counts. Amounts are exact decimals in and
//! exact strings out: nothing here rounds except `compact`, which says so.
//!
//! ```text
//! GOAL: show every amount exactly as the books hold it.
//! SOURCE: DECISION (the MCP contract: "money is exact or it is wrong");
//! CONVENTION (US accounting display: thousands commas,
//! negatives in parentheses or with a minus sign).
//! INVARIANTS:
//! 1. money, accounting, and dollars NEVER round: every decimal place
//! the amount has (at least two) is shown, thousands grouped by
//! commas in threes, so the text reads back to the same value.
//! 2. Zero (and negative zero) shows without a sign; a negative shows
//! U+2212 (money, dollars) or parentheses (accounting), never both
//! and never "-0".
//! 3. compact rounds (chart axes, tight tiles): $950, $1.2k, $25k,
//! $3.4M; it never shows a sign on what rounds to zero.
//! ```
use chrono::NaiveDate;
use rust_decimal::Decimal;
/// Thousands separators, two decimals, a true minus sign: `−1,234.56`.
/// Thousands separators, every decimal (at least two), a true minus sign:
/// `−1,234.56`.
pub fn money(d: Decimal) -> String {
let neg = d.is_sign_negative() && !d.is_zero();
let s = group(d.abs().round_dp(2));
if neg { format!("\u{2212}{s}") } else { s }
let s = group(d.abs());
if is_negative(d) {
format!("\u{2212}{s}")
} else {
s
}
}
/// Accounting style: negatives in parentheses, `(1,234.56)`.
pub fn accounting(d: Decimal) -> String {
if d.is_sign_negative() && !d.is_zero() {
format!("({})", group(d.abs().round_dp(2)))
} else {
group(d.round_dp(2))
}
let s = group(d.abs());
if is_negative(d) { format!("({s})") } else { s }
}
/// With the currency sign: `$1,234.56`, `−$12.00`.
pub fn dollars(d: Decimal) -> String {
let neg = d.is_sign_negative() && !d.is_zero();
let s = format!("${}", group(d.abs().round_dp(2)));
if neg { format!("\u{2212}{s}") } else { s }
let s = format!("${}", group(d.abs()));
if is_negative(d) {
format!("\u{2212}{s}")
} else {
s
}
}
/// Rounded for chart axes and tight tiles: `$1.2k`, `$3.4M`, `$950`.
pub fn compact(d: Decimal) -> String {
let f: f64 = d.try_into().unwrap_or(0.0);
let (neg, a) = (f < 0.0, f.abs());
let a = f.abs();
let s = if a >= 1_000_000.0 {
format!("${:.1}M", a / 1_000_000.0)
} else if a >= 10_000.0 {
@@ -40,11 +60,22 @@ pub fn compact(d: Decimal) -> String {
} else {
format!("${a:.0}")
};
if neg { format!("\u{2212}{s}") } else { s }
// No sign on what rounds to zero ("$0", not "−$0").
if f < 0.0 && s != "$0" {
format!("\u{2212}{s}")
} else {
s
}
}
fn is_negative(d: Decimal) -> bool {
d.is_sign_negative() && !d.is_zero()
}
/// A non-negative amount, every decimal it has (at least two), grouped.
fn group(d: Decimal) -> String {
let s = format!("{:.2}", d);
let places = d.normalize().scale().max(2) as usize;
let s = format!("{:.*}", places, d);
let (int, frac) = s.split_once('.').unwrap_or((&s, "00"));
let mut out = String::new();
for (i, c) in int.chars().enumerate() {
@@ -172,7 +203,9 @@ mod tests {
assert_eq!(money(dec("0")), "0.00");
assert_eq!(money(dec("-0.00")), "0.00");
assert_eq!(accounting(dec("-207.68")), "(207.68)");
assert_eq!(dollars(dec("999.999")), "$1,000.00");
assert_eq!(dollars(dec("999.999")), "$999.999");
assert_eq!(money(dec("0.125")), "0.125");
assert_eq!(compact(dec("-0.4")), "$0");
assert_eq!(compact(dec("1234")), "$1.2k");
assert_eq!(compact(dec("-25000")), "\u{2212}$25k");
assert_eq!(compact(dec("950.4")), "$950");
+11
View File
@@ -150,6 +150,17 @@ impl Section {
}
}
/// ```text
/// GOAL: back and forward behave like a web browser's.
/// SOURCE: CONVENTION (browser session history: going somewhere new
/// drops the forward list).
/// INVARIANTS:
/// 1. go(r) to a different route makes it current, pushes the old one
/// on back, and clears forward; go to the current route does nothing.
/// 2. back() then forward() returns to the same route (and vice versa);
/// either does nothing when its list is empty.
/// 3. can_back/can_forward say whether back/forward would move.
/// ```
/// Back/forward history.
pub struct Nav {
back: Vec<Route>,
+12
View File
@@ -148,6 +148,18 @@ impl Palette {
/// Subsequence match: every query character in order, rewarding
/// contiguous runs and word starts. None if no match.
/// Fuzzy match score, higher is better.
///
/// ```text
/// INVARIANTS:
/// 1. Matches (Some) exactly when the query's non-space characters,
/// lower-cased, appear in order in the lower-cased hay; the empty
/// query matches everything with score 0.
/// 2. A match's score is at least the number of non-space query
/// characters; consecutive matches and matches at a word start score
/// more, so a word-start prefix scores at least as high as any
/// other match of the same query.
/// ```
fn fuzzy(hay: &str, query: &str) -> Option<i32> {
if query.is_empty() {
return Some(0);