Merge branch 't3/transactional-mcp-writes': every write through the tools is one transaction, exactly once (P15 T1, D-88, D-89)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 10:40:34 -07:00
commit 38647e2143
61 files changed
+5801 -339

No files matched your search

+11 -4
View File
@@ -123,11 +123,11 @@ fn journal_history_traces_what_the_books_did() {
assert_eq!(next["lines"][0]["seq"].as_u64().unwrap(), after + 1);
// A bad subject is refused with the shapes; the journal is unchanged.
let before = books.journal();
let before = books.journal_raw();
let err =
answer_of(&w.call("books.journal_history", json!({"subject": "nonsense"}))).unwrap_err();
assert!(err.contains("entry:12"), "{err}");
assert_eq!(books.journal(), before);
assert_eq!(books.journal_raw(), before);
// It is a read: no head in the envelope.
assert!(all.get("head").is_none(), "{all}");
}
@@ -471,11 +471,18 @@ fn a_mutating_call_answers_with_the_head_and_a_refusal_names_its_remedy() {
.unwrap();
let head = added["head"]["seq"].as_u64().unwrap();
let start = answer_of(&w.call("books.start", json!({}))).unwrap();
// The head a write call answers is where its own lines end; its closing
// line (which holds this very answer) follows at once, and is the
// journal's head from then on (WB-format-8).
assert_eq!(
start["head"]["seq"],
json!(head),
"the head the call answered is the journal's"
json!(head + 1),
"the journal ends one line past the head the call answered: its closing line"
);
let journal = String::from_utf8(books.journal_raw()).unwrap();
let last: serde_json::Value = serde_json::from_str(journal.lines().last().unwrap()).unwrap();
assert_eq!(last["type"], "call.closed");
assert_eq!(last["payload"]["last_seq"], json!(head));
assert!(!added["next_steps"].as_array().unwrap().is_empty());
// A confirm with no preview is refused as stale_preview, naming the
// tool that previews.
+8 -4
View File
@@ -157,13 +157,17 @@ fn audit_is_deterministic() {
);
let run = first["run"].clone();
assert_eq!(run["at_current_head"], true);
let journal = books.journal();
let journal = books.journal_raw();
let again = audit(&mut w, "full", "2026-03-31");
assert_eq!(again["status"], "already_run");
assert_eq!(again["run"]["id"], run["id"]);
assert_eq!(again["run"]["findings_sha256"], run["findings_sha256"]);
assert_eq!(again["findings"], first["findings"]);
assert_eq!(books.journal(), journal, "asking again journals nothing");
assert_eq!(
books.journal_raw(),
journal,
"asking again journals nothing"
);
// The workpaper is the same twice, JSON and PDF.
let id = run["id"].clone();
let one = answer_of(&w.call("books.workpaper", json!({"id": id}))).unwrap();
@@ -406,7 +410,7 @@ fn audits_wait_for_the_upgrade() {
))
.unwrap();
assert_eq!(preview["status"], "preview");
let journal = books.journal();
let journal = books.journal_raw();
for (tool, args) in [
(
"books.audit",
@@ -425,7 +429,7 @@ fn audits_wait_for_the_upgrade() {
let e = answer_of(&w.call(tool, args)).unwrap_err();
assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}");
}
assert_eq!(books.journal(), journal, "a refusal journals nothing");
assert_eq!(books.journal_raw(), journal, "a refusal journals nothing");
// The package is held up only by what it always was: an open draft.
let args = json!({"as_of": "2026-01-31", "cash_accounts": ["1000"],
"include_receipts": false, "include_tins": false});
+7 -1
View File
@@ -248,7 +248,13 @@ async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, String>
}
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
let args = args.as_object().cloned().unwrap_or_default();
let mut args = args.as_object().cloned().unwrap_or_default();
// The key every write call carries (D-88).
static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
args.entry("request_key").or_insert_with(|| {
let n = NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
json!(format!("backups-key-{}-{n}", std::process::id()))
});
let r = tokio::time::timeout(
Duration::from_secs(60),
c.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
+13 -7
View File
@@ -1103,7 +1103,8 @@ fn a_call_whose_answer_was_never_read_is_on_record_as_having_run() {
let mut raw = raw::Raw::connect(&home, A);
let body = json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {
"name": "books.draft_entry",
"arguments": {"date": "2026-03-01", "description": "unread"}}})
"arguments": {"date": "2026-03-01", "description": "unread",
"request_key": common::fresh_request_key()}}})
.to_string();
raw.start(
"POST",
@@ -1541,7 +1542,8 @@ fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() {
let mut raw = raw::Raw::connect(&home, A);
let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {
"name": "books.draft_entry",
"arguments": {"date": "2026-03-01", "description": "never finished"}}})
"arguments": {"date": "2026-03-01", "description": "never finished",
"request_key": common::fresh_request_key()}}})
.to_string();
raw.start_inside(
"POST",
@@ -1665,7 +1667,8 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() {
);
let mut raw = raw::Raw::connect(&home, A);
let body = json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {
"name": "books.attach_receipt", "arguments": {"upload_id": up}}})
"name": "books.attach_receipt",
"arguments": {"upload_id": up, "request_key": common::fresh_request_key()}}})
.to_string();
raw.start(
"POST",
@@ -2191,7 +2194,8 @@ fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() {
let mut raw_call = raw::Raw::connect(&home, B);
let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {
"name": "books.draft_entry",
"arguments": {"date": "2026-03-01", "description": "never finished"}}})
"arguments": {"date": "2026-03-01", "description": "never finished",
"request_key": common::fresh_request_key()}}})
.to_string();
raw_call.start_inside(
"POST",
@@ -2653,9 +2657,11 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back
#[cfg(unix)]
fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> raw::Raw {
let mut raw = raw::Raw::connect(home, A);
let body = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
"name": tool, "arguments": args}})
.to_string();
let body = common::with_request_key(
&json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
"name": tool, "arguments": args}})
.to_string(),
);
raw.start(
"POST",
"mcp",
@@ -0,0 +1,863 @@
//! Every write through the tools is one transaction that happens exactly
//! once (plan P15 2a, D-88; WB-format-8 to WB-format-12), through the real
//! server as an agent reaches it.
//!
//! The law: a repeat of a request key posts nothing and returns the first
//! answer, across a restart; the same key for another request is refused;
//! a write without a key is not run; a failed write leaves its key free
//! and the books as they were; a call is framed in the journal and the
//! import is one frame; every tool that can write asks for the key; a call
//! that wrote lines and then failed rolls back, is on the record, and
//! frees its key; a call that wrote nothing leaves no line at all; the
//! same key under two tokens is two calls; a repeat that arrives while its
//! original runs gets its answer; a crash after the closing line is on
//! disk and before SQLite committed leaves the call done, once.
use common::{Books, Wire, answer_of};
use serde_json::{Value, json};
mod common;
/// The journal's lines, parsed.
fn lines(books: &Books) -> Vec<Value> {
String::from_utf8(books.journal_raw())
.unwrap()
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect()
}
/// A `tools/call` with exactly these arguments, key or none.
fn call_exactly(w: &mut Wire, tool: &str, args: Value) -> Value {
let msg = json!({"jsonrpc": "2.0", "id": 4242, "method": "tools/call",
"params": {"name": tool, "arguments": args}});
w.send_exactly(&msg.to_string());
w.recv(common::TIMEOUT).expect("an answer")
}
fn draft(key: &str, what: &str) -> Value {
json!({"date": "2026-03-01", "description": what, "no_party_reason": "test",
"request_key": key})
}
#[test]
fn a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing() {
let books = Books::new("calls-repeat");
let mut w = books.session("test");
let first = call_exactly(
&mut w,
"books.draft_entry",
draft("key-repeat-0001", "Rent"),
);
let first = answer_of(&first).unwrap();
let after_first = books.journal_raw();
// The answer was lost; the agent asks again, the same call, the same key.
let again = call_exactly(
&mut w,
"books.draft_entry",
draft("key-repeat-0001", "Rent"),
);
assert_eq!(answer_of(&again).unwrap(), first);
assert_eq!(books.journal_raw(), after_first, "a repeat writes nothing");
let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap();
assert_eq!(
drafts["drafts"].as_array().map(Vec::len),
Some(1),
"{drafts}"
);
// Across a restart: the key is in the journal.
books.restart();
let mut w = books.session("test");
let later = call_exactly(
&mut w,
"books.draft_entry",
draft("key-repeat-0001", "Rent"),
);
assert_eq!(answer_of(&later).unwrap(), first);
assert_eq!(books.journal_raw(), after_first, "nor after a restart");
}
#[test]
fn the_same_key_for_another_request_is_refused_in_words() {
let books = Books::new("calls-misuse");
let mut w = books.session("test");
answer_of(&call_exactly(
&mut w,
"books.draft_entry",
draft("key-misuse-0001", "Rent"),
))
.unwrap();
let before = books.journal_raw();
let refused = call_exactly(
&mut w,
"books.draft_entry",
draft("key-misuse-0001", "Something else"),
);
let why = answer_of(&refused).unwrap_err();
assert!(why.contains("already used"), "{why}");
assert!(why.contains("nothing was changed"), "{why}");
assert_eq!(books.journal_raw(), before);
}
#[test]
fn a_write_without_a_usable_key_is_not_run() {
let books = Books::new("calls-nokey");
let mut w = books.session("test");
let before = books.journal_raw();
let mut bare = draft("x", "No key");
bare.as_object_mut().unwrap().remove("request_key");
for (what, args) in [
("no key", bare),
("a short key", draft("short", "No key")),
("a key that isn't text", {
let mut a = draft("x", "No key");
a["request_key"] = json!(12345678);
a
}),
] {
let r = call_exactly(&mut w, "books.draft_entry", args);
let why = answer_of(&r).unwrap_err();
assert!(why.contains("request_key"), "{what}: {why}");
assert!(why.contains("not run"), "{what}: {why}");
}
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
// A read needs none, and a preview (a confirmed tool, not confirmed)
// writes nothing and needs none.
answer_of(&call_exactly(&mut w, "books.chart", json!({}))).unwrap();
let r = call_exactly(&mut w, "books.post_entry", json!({"entry_id": 1}));
let text = serde_json::to_string(&r).unwrap();
assert!(!text.contains("request_key"), "{text}");
}
#[test]
fn a_failed_write_leaves_the_books_and_its_key_as_they_were() {
let books = Books::new("calls-failed");
let mut w = books.session("test");
let before = books.journal_raw();
let mut bad = draft("key-failed-0001", "Bad date");
bad["date"] = json!("not a date");
let failed = call_exactly(&mut w, "books.draft_entry", bad);
assert!(answer_of(&failed).is_err(), "{failed}");
assert_eq!(
books.journal_raw(),
before,
"a call that wrote nothing leaves no line"
);
// Nothing happened under the key, so the corrected call may use it.
let fixed = call_exactly(
&mut w,
"books.draft_entry",
draft("key-failed-0001", "Good date"),
);
answer_of(&fixed).unwrap();
}
#[test]
fn a_call_is_one_frame_in_the_journal_closed_with_its_answer() {
let books = Books::new("calls-frame");
let mut w = books.session("test");
let before = lines(&books).len();
let out = call_exactly(
&mut w,
"books.draft_entry",
draft("key-frame-00001", "Framed"),
);
let answer = answer_of(&out).unwrap();
let all = lines(&books);
let call = &all[before..];
assert_eq!(call.first().unwrap()["type"], "call.begun", "{call:?}");
let closed = call.last().unwrap();
assert_eq!(closed["type"], "call.closed");
let p = &closed["payload"];
assert_eq!(p["outcome"], "ok");
assert_eq!(p["tool"], "books.draft_entry");
assert_eq!(p["key"], "key-frame-00001");
assert_eq!(p["first_seq"], call.first().unwrap()["seq"]);
assert_eq!(
p["last_seq"].as_u64().unwrap() + 1,
closed["seq"].as_u64().unwrap()
);
// The answer kept is the answer given.
let kept: Value = serde_json::from_str(p["answer"].as_str().unwrap()).unwrap();
assert_eq!(kept["structuredContent"], answer);
}
#[test]
fn the_import_is_one_transaction() {
let books = Books::new("calls-import");
let mut w = books.session("test");
for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] {
answer_of(&w.call(
"books.add_account",
json!({"code": code, "name": name, "account_type": kind}),
))
.unwrap();
}
let csv = b"Date,Description,Amount\n2026-01-02,Paper,-12.50\n2026-01-03,Pens,-3.25\n2026-01-04,Ink,-40.00\n";
let up = w.upload(csv, "bank.csv", "text/csv", "import");
let before = lines(&books).len();
let args = json!({"upload_id": up, "bank_account_code": "1000",
"default_offset_code": "6000", "request_key": "key-import-0001"});
let out = answer_of(&call_exactly(&mut w, "books.import_bank_csv", args.clone())).unwrap();
assert_eq!(out["count"], 3, "{out}");
let all = lines(&books);
let call = &all[before..];
assert_eq!(call.first().unwrap()["type"], "call.begun");
assert_eq!(call.last().unwrap()["type"], "call.closed");
// Every row of the file is inside the one frame.
let inside = call.iter().filter(|l| l["type"] == "entry.created").count();
assert_eq!(inside, 3);
assert_eq!(
all.iter().filter(|l| l["type"] == "call.begun").count(),
all.iter()
.filter(|l| l["type"] == "call.closed" && l["payload"]["first_seq"].is_u64())
.count(),
"every frame that began closed"
);
// The answer lost: the repeat gives the first answer, imports nothing.
let journal = books.journal_raw();
let again = answer_of(&call_exactly(&mut w, "books.import_bank_csv", args)).unwrap();
assert_eq!(again, out);
assert_eq!(books.journal_raw(), journal);
// A file the books refuse whole writes none of it.
let bad = b"Date,Description,Amount\n2026-02-02,Ok row,-1.00\nnot a date,Bad row,-2.00\n";
let up = w.upload(bad, "bad.csv", "text/csv", "import");
let before = books.journal_raw();
let refused = call_exactly(
&mut w,
"books.import_bank_csv",
json!({"upload_id": up, "bank_account_code": "1000",
"default_offset_code": "6000", "request_key": "key-import-0002"}),
);
assert!(answer_of(&refused).is_err(), "{refused}");
assert_eq!(books.journal_raw(), before, "all or nothing");
}
#[test]
fn every_tool_that_can_write_asks_for_a_key_and_no_other_does() {
let books = Books::new("calls-schema");
let mut w = books.session("test");
let listed = w.rpc("tools/list", json!({}));
let tools = listed["result"]["tools"].as_array().unwrap();
let (mut asking, mut reading) = (0, 0);
for t in tools {
let name = t["name"].as_str().unwrap();
// Three tools only read what is sealed (and may answer with a TIN):
// annotated as writes, they are reads and take no key.
let read_only = t["annotations"]["readOnlyHint"] == json!(true)
|| [
"books.vendor_1099",
"books.get_w9",
"books.export_cpa_package",
]
.contains(&name);
let required = t["inputSchema"]["required"]
.as_array()
.is_some_and(|r| r.contains(&json!("request_key")));
let property = t["inputSchema"]["properties"].get("request_key").is_some();
if read_only {
assert!(!required && !property, "{name} reads and asks for a key");
reading += 1;
} else {
assert!(required && property, "{name} can write and asks for no key");
asking += 1;
}
}
assert!(
asking > 50 && reading > 20,
"{asking} write, {reading} read"
);
}
/// The books' SQLite projection file.
fn projection(books: &Books) -> std::path::PathBuf {
std::fs::read_dir(books.dir())
.unwrap()
.flatten()
.map(|e| e.path())
.find(|p| p.extension().is_some_and(|e| e == "db"))
.expect("the projection file")
}
/// A `books.add_account` request.
fn account(key: &str) -> Value {
json!({"code": "1000", "name": "Bank", "account_type": "asset", "request_key": key})
}
/// The raw journal's line types, in order.
fn types(books: &Books) -> Vec<String> {
lines(books)
.iter()
.map(|l| l["type"].as_str().unwrap().to_string())
.collect()
}
/// A call that gets as far as writing lines and then fails: its savepoint
/// rolls back, the live books are rebuilt without its lines, a `failed`
/// closing line is on the record, its key is free, and what takes its ids
/// next is a fact of the books (plan P15 2a, SCENARIO 2).
///
/// The failure is the projection refusing the account's line: a
/// trigger put in the books' SQLite file from outside, as a full disk or a
/// corrupt page would.
#[test]
fn a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were() {
let books = Books::new("calls-failed-lines");
let mut w = books.session("test");
let before = types(&books);
let db = rusqlite::Connection::open(projection(&books)).unwrap();
db.execute_batch(
"CREATE TRIGGER wb_test_refuses BEFORE INSERT ON accounts \
BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;",
)
.unwrap();
let failed = call_exactly(&mut w, "books.add_account", account("key-lines-fail-1"));
assert!(answer_of(&failed).is_err(), "{failed}");
let added: Vec<_> = types(&books)[before.len()..].to_vec();
assert_eq!(
added.first().map(String::as_str),
Some("call.begun"),
"{added:?}"
);
assert_eq!(added.last().map(String::as_str), Some("call.closed"));
assert!(
added.len() >= 3,
"it wrote a line before failing: {added:?}"
);
let all = lines(&books);
let closed = &all.last().unwrap()["payload"];
assert_eq!(closed["outcome"], "failed");
assert!(closed["error"].as_str().is_some_and(|e| !e.is_empty()));
assert!(closed.get("answer").is_none());
// The live books are as they were: no such account, though a line was
// written.
db.execute_batch("DROP TRIGGER wb_test_refuses").unwrap();
drop(db);
let banks = |w: &mut common::Wire| {
let chart = answer_of(&w.call("books.chart", json!({}))).unwrap();
chart.to_string().matches("\"Bank\"").count()
};
assert_eq!(banks(&mut w), 0);
// The key is free: the same request now succeeds, takes the id the dead
// call had, and is the only account.
let fixed = answer_of(&call_exactly(
&mut w,
"books.add_account",
account("key-lines-fail-1"),
))
.unwrap();
assert_eq!(
fixed["account_id"], 1,
"the dead call's account id is handed out again: {fixed}"
);
assert_eq!(banks(&mut w), 1);
// History lists every line and says of the dead ones that they did not
// count; none of the counted lines is a dead one.
let history = answer_of(&w.call("books.journal_history", json!({"limit": 200}))).unwrap();
let said: Vec<&str> = history["lines"]
.as_array()
.unwrap()
.iter()
.filter_map(|l| l["summary"].as_str())
.filter(|s| s.contains("not counted"))
.collect();
assert_eq!(said.len(), added.len() - 2, "{history}");
// A restart replays the same books: the dead lines build nothing.
books.restart();
let mut w = books.session("test");
assert_eq!(banks(&mut w), 1);
answer_of(&w.call("books.verify", json!({}))).unwrap();
}
/// A call that wrote no line leaves none (WB-format-9): its answer is kept
/// for the life of the server, so a repeat within the session is answered;
/// after a restart the repeat simply runs again.
#[test]
fn a_call_that_wrote_nothing_leaves_no_line_and_is_answered_again_only_within_the_session() {
let books = Books::new("calls-nothing");
let mut w = books.session("test");
let before = books.journal_raw();
let args = json!({"request_key": "key-nothing-0001", "sha256": "ab".repeat(32),
"size": 5, "mime_type": "text/csv", "file_name": "x.csv",
"purpose": "import"});
let first = answer_of(&call_exactly(&mut w, "books.begin_upload", args.clone())).unwrap();
assert_eq!(books.journal_raw(), before, "no frame, no line");
let again = answer_of(&call_exactly(&mut w, "books.begin_upload", args.clone())).unwrap();
assert_eq!(again, first, "the same answer within the session");
assert_eq!(books.journal_raw(), before);
books.restart();
let mut w = books.session("test");
let after = answer_of(&call_exactly(&mut w, "books.begin_upload", args)).unwrap();
assert_ne!(after, first, "after a restart it simply runs again");
assert_eq!(books.journal_raw(), before, "and still writes nothing");
}
/// The same request key under two tokens is two calls: a key belongs to
/// the token that made it.
#[test]
fn the_same_key_under_two_tokens_is_two_calls() {
let books = Books::new("calls-two-tokens");
let mut one = books.session("test");
let second = books
.home
.token_with(&books.id, "second", &["read", "write", "post", "admin"]);
let mut two = common::Wire::with_token(&books.home, &books.id, Some(second));
two.initialize("test");
let a = answer_of(&call_exactly(
&mut one,
"books.draft_entry",
draft("key-tokens-0001", "Same"),
))
.unwrap();
let b = answer_of(&call_exactly(
&mut two,
"books.draft_entry",
draft("key-tokens-0001", "Same"),
))
.unwrap();
assert_ne!(a["entry_id"], b["entry_id"], "one draft per token: {a} {b}");
let drafts = answer_of(&one.call("books.list_drafts", json!({}))).unwrap();
assert_eq!(
drafts["drafts"].as_array().map(Vec::len),
Some(2),
"{drafts}"
);
// And each token's repeat finds its own.
let a2 = answer_of(&call_exactly(
&mut one,
"books.draft_entry",
draft("key-tokens-0001", "Same"),
))
.unwrap();
assert_eq!(a2, a);
}
/// A repeat that arrives while its original is still running waits for it
/// (writes take turns) and then gets its answer: the original's effects
/// are made once. Eight identical requests sent at the same moment make
/// one draft and are answered alike.
#[test]
fn a_repeat_arriving_while_its_original_runs_gets_its_answer_and_changes_nothing() {
let books = Books::new("calls-concurrent");
let before = lines(&books).len();
let barrier = std::sync::Barrier::new(8);
let (home, id) = (&books.home, books.id.clone());
let answers: Vec<Value> = std::thread::scope(|scope| {
let runs: Vec<_> = (0..8)
.map(|n| {
let (barrier, id) = (&barrier, &id);
scope.spawn(move || {
let mut w = common::Wire::new(home, id);
w.initialize(&format!("racer-{n}"));
barrier.wait();
call_exactly(
&mut w,
"books.draft_entry",
draft("key-concurrent-1", "Raced"),
)
})
})
.collect();
runs.into_iter().map(|r| r.join().unwrap()).collect()
});
let answers: Vec<Value> = answers.iter().map(|a| answer_of(a).unwrap()).collect();
assert!(answers.windows(2).all(|p| p[0] == p[1]), "{answers:?}");
let all = lines(&books);
assert_eq!(
all[before..]
.iter()
.filter(|l| l["type"] == "entry.created")
.count(),
1,
"one draft"
);
assert_eq!(
all[before..]
.iter()
.filter(|l| l["type"] == "call.begun")
.count(),
1,
"one frame"
);
}
/// A call whose answer is too long for the books to keep (above 4 KiB):
/// its closing line keeps the answer's hash and length, and a repeat, even
/// one that arrived while the original ran, is told in words that it was
/// done, with the lines it wrote; nothing is done twice.
#[test]
fn a_repeat_of_a_call_whose_answer_was_too_long_is_told_it_was_done() {
let books = Books::new("calls-long-answer");
let mut w = books.session("test");
for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] {
answer_of(&w.call(
"books.add_account",
json!({"code": code, "name": name, "account_type": kind}),
))
.unwrap();
}
let rows = 300;
let mut csv = String::from("Date,Description,Amount\n");
for n in 0..rows {
csv.push_str(&format!("2026-01-02,Row {n},-1.{:02}\n", n % 100));
}
let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import");
let args = json!({"upload_id": up, "bank_account_code": "1000",
"default_offset_code": "6000", "request_key": "key-long-answer1"});
let before = lines(&books).len();
let (home, id) = (&books.home, books.id.clone());
let (first, second) = std::thread::scope(|scope| {
let original = scope.spawn(|| {
let mut w = common::Wire::new(home, &id);
w.initialize("original");
call_exactly(&mut w, "books.import_bank_csv", args.clone())
});
std::thread::sleep(std::time::Duration::from_millis(30));
let repeat = scope.spawn(|| {
let mut w = common::Wire::new(home, &id);
w.initialize("repeat");
call_exactly(&mut w, "books.import_bank_csv", args.clone())
});
(original.join().unwrap(), repeat.join().unwrap())
});
// One of the two ran; the other was told, in words, that it was done.
let (ran, told) = match (answer_of(&first), answer_of(&second)) {
(Ok(a), Err(why)) | (Err(why), Ok(a)) => (a, why),
other => panic!("one runs and one is told: {other:?}"),
};
assert_eq!(ran["count"], rows, "{ran}");
assert!(told.contains("was done"), "{told}");
assert!(told.contains("nothing more was changed"), "{told}");
assert!(told.contains("journal lines"), "{told}");
let all = lines(&books);
assert_eq!(
all[before..]
.iter()
.filter(|l| l["type"] == "entry.created")
.count(),
rows,
"the file was imported once"
);
let closed = all.last().unwrap();
assert_eq!(closed["type"], "call.closed");
assert!(
closed["payload"].get("answer").is_none(),
"no answer kept whole"
);
assert_eq!(
closed["payload"]["answer_sha256"].as_str().map(str::len),
Some(64)
);
assert!(closed["payload"]["answer_bytes"].as_u64().unwrap() > 4096);
// Across a restart the same words.
books.restart();
let mut w = books.session("test");
let again = call_exactly(&mut w, "books.import_bank_csv", args);
assert!(answer_of(&again).unwrap_err().contains("was done"));
assert_eq!(lines(&books).len(), all.len());
}
/// A crash after the closing line is on disk and before SQLite committed:
/// the books are rebuilt from the journal, the call is done, and a repeat
/// of its key answers the first answer and changes nothing.
#[test]
fn a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once() {
let books = Books::new("calls-sqlite-behind");
let mut w = books.session("test");
answer_of(&call_exactly(
&mut w,
"books.draft_entry",
draft("key-crash-prior1", "Earlier"),
))
.unwrap();
drop(w);
// The projection as it was before the call.
books.stop();
let db = projection(&books);
let old = std::fs::read(&db).unwrap();
let side: Vec<_> = ["-wal", "-shm"]
.iter()
.map(|x| std::path::PathBuf::from(format!("{}{x}", db.display())))
.collect();
assert!(
side.iter().all(|p| !p.exists()),
"a stopped server leaves no -wal or -shm"
);
books.start();
let mut w = books.session("test");
let first = answer_of(&call_exactly(
&mut w,
"books.draft_entry",
draft("key-crash-0001", "Done once"),
))
.unwrap();
drop(w);
let journal = books.journal_raw();
assert_eq!(
lines(&books).last().unwrap()["payload"]["outcome"],
"ok",
"the ok closing line is on disk"
);
// Power fails: the journal has it (it was fsynced first), SQLite does not.
books.stop();
std::fs::write(&db, old).unwrap();
books.start();
let mut w = books.session("test");
// The books are rebuilt from the journal: both drafts are there.
let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap();
assert_eq!(
drafts["drafts"].as_array().map(Vec::len),
Some(2),
"{drafts}"
);
// The repeat is answered with the first answer and does nothing.
let again = answer_of(&call_exactly(
&mut w,
"books.draft_entry",
draft("key-crash-0001", "Done once"),
))
.unwrap();
assert_eq!(again, first);
assert_eq!(books.journal_raw(), journal, "nothing more was written");
let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap();
assert_eq!(
drafts["drafts"].as_array().map(Vec::len),
Some(2),
"{drafts}"
);
answer_of(&w.call("books.verify", json!({}))).unwrap();
}
// ---- The tax-id vault is inside the transaction (BS-partner-2). Obviously
// fake values: a TIN is never written in a journal line, an error, or here
// beyond these two.
const OLD_TIN: &str = "123-45-6789";
const NEW_TIN: &str = "765-43-2109";
fn digits(tin: &str) -> String {
tin.replace('-', "")
}
/// Whether `text` holds either fake TIN, hyphenated or not.
fn holds_a_tin(text: &str) -> bool {
[OLD_TIN, NEW_TIN]
.iter()
.any(|t| text.contains(t) || text.contains(&digits(t)))
}
/// What the vault holds for the party, by the vault's own reader: the
/// TIN's last four, or None.
fn vaulted_last4(books: &Books, party: u64) -> Option<String> {
let book = books.dir();
let key = book.join("keys").join("legacy.key");
let vault = ledger_vault::Vault::open(&book.join("vault"), &key, false).ok()?;
vault.tin(party).unwrap().map(|t| t.last4().to_string())
}
fn staged_files(books: &Books) -> Vec<String> {
std::fs::read_dir(books.dir().join("vault"))
.map(|d| {
d.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.contains(".staged-") || n.contains(".purging-"))
.collect()
})
.unwrap_or_default()
}
fn set_tin(key: &str, tin: &str) -> Value {
json!({"party": "Mo", "tin": tin, "tin_type": "ssn", "request_key": key})
}
/// A set_tin that fails after it wrote the vault: the vault keeps the old
/// tax id whole and holds nothing of the new one, the journal holds
/// neither, and once the call can run again it is the new one that is kept.
#[test]
fn a_set_tin_that_fails_leaves_the_vault_as_it_was() {
let books = Books::new("calls-vault-fail");
let mut w = books.session("test");
let party = answer_of(&w.call(
"books.add_party",
json!({"name": "Mo", "roles": ["member"]}),
))
.unwrap()["party_id"]
.as_u64()
.unwrap();
answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-vault-first1", OLD_TIN),
))
.unwrap();
assert_eq!(vaulted_last4(&books, party).as_deref(), Some("6789"));
// The projection refuses the call's first line (its begin line).
let db = rusqlite::Connection::open(projection(&books)).unwrap();
db.execute_batch(
"CREATE TRIGGER wb_test_refuses BEFORE UPDATE ON meta \
BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;",
)
.unwrap();
let failed = call_exactly(
&mut w,
"books.set_tin",
set_tin("key-vault-fail01", NEW_TIN),
);
let why = answer_of(&failed).unwrap_err();
assert!(!holds_a_tin(&why), "an error never holds a tax id");
db.execute_batch("DROP TRIGGER wb_test_refuses").unwrap();
drop(db);
// The failure here is one that persists (the projection refuses every
// write, as a full disk would), so the books server stops: the call's
// failed closing line is on disk, and what it staged is settled by what
// the journal says at the next start.
books.restart();
let mut w = books.session("test");
let log = books.server_log();
assert!(log.contains("vault records unsettled"), "{log}");
assert!(!holds_a_tin(&log), "a log never holds a tax id");
// The journal's failed frame holds no tax id, and the old one is whole in
// the vault; nothing is left staged.
assert_eq!(
lines(&books)[lines(&books).len() - 1]["payload"]["outcome"],
"failed"
);
assert!(!holds_a_tin(
&String::from_utf8(books.journal_raw()).unwrap()
));
assert_eq!(vaulted_last4(&books, party).as_deref(), Some("6789"));
assert_eq!(staged_files(&books), Vec::<String>::new());
// The party still shows the old last four.
let shown = answer_of(&w.call("books.party", json!({"party": "Mo"}))).unwrap();
assert!(shown.to_string().contains("6789"), "{shown}");
assert!(!shown.to_string().contains("2109"), "{shown}");
// The key is free: the same request now succeeds and the vault holds the new one.
answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-vault-fail01", NEW_TIN),
))
.unwrap();
assert_eq!(vaulted_last4(&books, party).as_deref(), Some("2109"));
assert_eq!(staged_files(&books), Vec::<String>::new());
assert!(!holds_a_tin(
&String::from_utf8(books.journal_raw()).unwrap()
));
}
/// Two requests that differ only in a tax id are two requests: the same key
/// with another tax id is refused, never answered as a repeat, and nothing
/// of either is in the journal to test a guess against.
#[test]
fn a_key_reused_for_another_tax_id_is_refused_not_repeated() {
let books = Books::new("calls-vault-mask");
let mut w = books.session("test");
answer_of(&w.call(
"books.add_party",
json!({"name": "Mo", "roles": ["member"]}),
))
.unwrap();
let first = answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-mask-000001", OLD_TIN),
))
.unwrap();
// The same request again: the first answer, nothing more written.
let journal = books.journal_raw();
let again = answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-mask-000001", OLD_TIN),
))
.unwrap();
assert_eq!(again, first);
// Another tax id under the same key: refused in words.
let other = call_exactly(&mut w, "books.set_tin", set_tin("key-mask-000001", NEW_TIN));
let why = answer_of(&other).unwrap_err();
assert!(why.contains("already used"), "{why}");
assert!(!holds_a_tin(&why));
assert_eq!(books.journal_raw(), journal);
assert!(!holds_a_tin(&String::from_utf8(journal).unwrap()));
// And across a restart, with the digest keyed by the books' own secret.
books.restart();
let mut w = books.session("test");
let other = call_exactly(&mut w, "books.set_tin", set_tin("key-mask-000001", NEW_TIN));
assert!(answer_of(&other).unwrap_err().contains("already used"));
let same = answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-mask-000001", OLD_TIN),
))
.unwrap();
assert_eq!(same, first);
}
/// A crash after the closing line is on disk and before the staged vault
/// record was made final: the next start finishes what the journal says
/// was done (the new tax id is the party's), and drops what no committed
/// call staged.
#[test]
fn a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start() {
let books = Books::new("calls-vault-crash");
let mut w = books.session("test");
let party = answer_of(&w.call(
"books.add_party",
json!({"name": "Mo", "roles": ["member"]}),
))
.unwrap()["party_id"]
.as_u64()
.unwrap();
answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-vcrash-first", OLD_TIN),
))
.unwrap();
drop(w);
books.stop();
let record = books.dir().join("vault").join(format!("tin-{party}.bin"));
let old = std::fs::read(&record).unwrap();
books.start();
let mut w = books.session("test");
answer_of(&call_exactly(
&mut w,
"books.set_tin",
set_tin("key-vcrash-second", NEW_TIN),
))
.unwrap();
drop(w);
let closed = lines(&books)
.into_iter()
.rev()
.find(|l| l["type"] == "call.closed")
.unwrap();
assert_eq!(closed["payload"]["outcome"], "ok");
let tag = ledger_store::calls::call_tag(
closed["payload"]["token"].as_str().unwrap(),
closed["payload"]["key"].as_str().unwrap(),
);
books.stop();
let new = std::fs::read(&record).unwrap();
assert_ne!(old, new);
// As a crash would have left it: the closing line is on disk, the new
// record is still staged, the old one still final. And a record staged
// by a call the journal never closed.
std::fs::write(&record, &old).unwrap();
let staged = record.with_file_name(format!("tin-{party}.staged-{tag}"));
std::fs::write(&staged, &new).unwrap();
let stray = record.with_file_name(format!("tin-99.staged-{}", "0123456789abcdef"));
std::fs::write(&stray, &new).unwrap();
books.start();
assert_eq!(
vaulted_last4(&books, party).as_deref(),
Some("2109"),
"finished"
);
assert!(
!staged.exists() && !stray.exists(),
"{:?}",
staged_files(&books)
);
assert!(books.server_log().contains("vault records unsettled"));
}
+64 -3
View File
@@ -434,8 +434,18 @@ impl Wire {
}
/// Send `text` as one message's body, as it is (a test's own bytes,
/// malformed ones included).
/// malformed ones included), except that a tool call that carries no
/// `request_key` is given a fresh one (D-88: every write needs one; a
/// read ignores it), so a test of what a tool does needn't make one up.
/// [`Self::send_exactly`] sends the bytes untouched.
pub fn send_line(&mut self, text: &str) {
let text = with_request_key(text);
self.send_exactly(&text);
}
/// [`Self::send_line`] without the request key: these bytes only
/// (the tests of what a call without a key is told).
pub fn send_exactly(&mut self, text: &str) {
let parsed: Option<Value> = serde_json::from_str(text).ok();
let method = parsed
.as_ref()
@@ -761,8 +771,15 @@ impl Books {
self.home.book_dir(&self.id)
}
/// The books' journal, as it is on disk.
/// The books' journal as it is on disk, without the frames of tool
/// calls (`call.begun`, `call.closed`: D-88): what the books hold, so
/// a test that a call "journaled nothing" says so of the events.
pub fn journal(&self) -> Vec<u8> {
without_call_lines(&self.journal_raw())
}
/// The books' journal, byte for byte.
pub fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.dir().join("journal.jsonl")).unwrap_or_default()
}
@@ -1113,6 +1130,48 @@ pub async fn connect_at(run: &Path, book: &str, token: Option<String>) -> Result
.map_err(|e| e.to_string())
}
/// A journal's bytes without its call frames (`call.begun`, `call.closed`).
pub fn without_call_lines(journal: &[u8]) -> Vec<u8> {
journal
.split_inclusive(|&b| b == b'\n')
.filter(|l| {
let l = String::from_utf8_lossy(l);
!l.contains(r#""type":"call.begun""#) && !l.contains(r#""type":"call.closed""#)
})
.flatten()
.copied()
.collect()
}
/// A request key no other call in this process has used.
pub fn fresh_request_key() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
format!(
"test-key-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::SeqCst)
)
}
/// `message`, a JSON-RPC message as text: if it is a `tools/call` whose
/// arguments are an object with no `request_key`, with a fresh one added
/// (the key the books ask of every write, D-88); anything else as it is.
pub fn with_request_key(message: &str) -> String {
let Ok(mut v) = serde_json::from_str::<Value>(message) else {
return message.to_string();
};
let keyed = v.get("method") == Some(&json!("tools/call"))
&& v.pointer("/params/arguments")
.and_then(Value::as_object)
.is_some_and(|a| !a.contains_key("request_key"));
if !keyed {
return message.to_string();
}
v["params"]["arguments"]["request_key"] = json!(fresh_request_key());
v.to_string()
}
/// Call a tool: Ok(structured result) or Err(the error text).
/// Call a tool the way an agent confirms (plan P4, D-50): a call with
/// `confirmed: true` and no `preview` is made first without `confirmed`,
@@ -1131,7 +1190,9 @@ pub async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, Stri
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
use rmcp::model::CallToolRequestParams;
let args = args.as_object().cloned().unwrap_or_default();
let mut args = args.as_object().cloned().unwrap_or_default();
args.entry("request_key")
.or_insert_with(|| json!(fresh_request_key()));
// A client whose server went away may wait forever: a call that
// takes this long counts as refused.
let r = tokio::time::timeout(
+13 -13
View File
@@ -123,7 +123,7 @@ fn an_invoice_from_issue_to_paid() {
// The preview: nothing written, a DRAFT copy handed over, the number
// and due date the confirm will take.
let before = books.journal();
let before = books.journal_raw();
let preview = m.call("books.create_invoice", issue.clone());
assert!(
preview["preview"].is_string(),
@@ -155,8 +155,8 @@ fn an_invoice_from_issue_to_paid() {
let draft = m.handed(&preview["pdf"]);
assert!(draft.starts_with(b"%PDF"), "a PDF, not bytes inline");
assert!(draft.len() > 1_000, "the DRAFT copy is a page: {preview}");
assert_eq!(books.journal(), before, "a preview journals nothing");
assert!(books.journal().len() == before.len());
assert_eq!(books.journal_raw(), before, "a preview journals nothing");
assert!(books.journal_raw().len() == before.len());
// The confirm: the same number, the issued copy filed with the invoice.
let mut confirmed = issue.clone();
@@ -239,7 +239,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() {
"account": "6500"}],
});
let before = books.journal();
let before = books.journal_raw();
let mut preview = bill.clone();
preview["upload_id"] = json!(file);
let p = m.call("books.create_bill", preview.clone());
@@ -248,7 +248,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() {
assert_eq!(p["terms"], "2/10 net 30", "{p}");
assert_eq!(p["discount_by"], "2026-02-11", "{p}");
assert_eq!(p["max_discount"], "20.00", "2% of 1,000.00");
assert_eq!(books.journal(), before, "a preview journals nothing");
assert_eq!(books.journal_raw(), before, "a preview journals nothing");
let mut confirm = preview;
confirm["confirmed"] = json!(true);
@@ -321,13 +321,13 @@ fn duplicate_vendor_invoice_refused() {
m.call("books.create_bill", bill(&first_file, "2026-02-01"));
// The same number (however written) is the same vendor invoice.
let second_file = m.upload(b"second copy", "ch-1-again.pdf", "receipt");
let before = books.journal();
let before = books.journal_raw();
let refused = m
.try_call("books.create_bill", bill(&second_file, "2026-02-02"))
.unwrap_err();
assert!(refused.contains("CH-4471"), "{refused}");
assert!(refused.contains("duplicate_reason"), "{refused}");
assert_eq!(books.journal(), before, "a refusal journals nothing");
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
// The upload was given back, not used up (an upload is spent only by
// the call that files it).
let mut with_reason = bill(&second_file, "2026-02-02");
@@ -377,14 +377,14 @@ fn a_line_account_must_be_allowed() {
"lines": [{"description": "Work", "amount": "100.00", "account": account}],
"confirmed": true})
};
let before = books.journal();
let before = books.journal_raw();
// An invoice line may not post to the receivable control or a role
// account.
let why = m
.try_call("books.create_invoice", invoice("1200"))
.unwrap_err();
assert!(why.contains("1200"), "{why}");
assert_eq!(books.journal(), before, "a refusal journals nothing");
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
// Nor to an expense account.
let why = m
.try_call("books.create_invoice", invoice("6999"))
@@ -547,7 +547,7 @@ fn custom_terms_are_due_on_the_date_they_give() {
assert_eq!(bill["due_date"], "2026-11-20", "{bill}");
// Dated after the agreed day: refused.
let before = books.journal();
let before = books.journal_raw();
let late = m
.try_call(
"books.create_invoice",
@@ -555,7 +555,7 @@ fn custom_terms_are_due_on_the_date_they_give() {
)
.unwrap_err();
assert!(late.contains("due"), "{late}");
assert_eq!(books.journal(), before, "a refusal writes nothing");
assert_eq!(books.journal_raw(), before, "a refusal writes nothing");
}
/// A customer given by id and by name is the same record (the old
@@ -589,7 +589,7 @@ fn a_customer_by_id_and_by_name_is_one_record() {
// ambiguous, and is refused rather than guessed.
m.customer("Zeta");
m.customer("2");
let before = books.journal();
let before = books.journal_raw();
let why = m
.try_call(
"books.create_invoice",
@@ -598,7 +598,7 @@ fn a_customer_by_id_and_by_name_is_one_record() {
)
.unwrap_err();
assert!(why.contains("ambiguous"), "{why}");
assert_eq!(books.journal(), before, "a refusal journals nothing");
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
// Nothing at all names no customer.
let why = m
.try_call(
+8 -4
View File
@@ -349,13 +349,13 @@ fn a_package_the_build_refuses_journals_no_decision_even_with_a_reason() {
draft(&mut w, "2026-03-10", "Open", "40.00");
let mut args = json!({"as_of": "2026-03-31", "cash_accounts": ["1000"]});
args["allow_open_drafts"] = json!({"reason": "the CPA wants it before the receipt comes"});
let before = books.journal().len();
let before = books.journal_raw().len();
for _ in 0..2 {
let why = answer_of(&w.call("books.export_cpa_package", args.clone()))
.expect_err("the build refuses an unknown capital account");
assert!(why.contains("unknown capital account 3999"), "{why}");
assert_eq!(
books.journal().len(),
books.journal_raw().len(),
before,
"a decision was journaled for a package that was refused"
);
@@ -397,7 +397,7 @@ fn stale_preview_refused() {
json!({"entry_id": id, "account": "1000", "side": "credit", "amount": "1.00"}),
))
.unwrap();
let before = books.journal();
let before = books.journal_raw();
let r = w.call_raw(
"books.post_entry",
json!({"entry_id": id, "confirmed": true, "preview": digest}),
@@ -405,7 +405,11 @@ fn stale_preview_refused() {
let err = refusal(&r);
assert_eq!(err["code"], "stale_preview");
assert_eq!(err["remedy_tool"], "books.post_entry");
assert_eq!(books.journal(), before, "a stale confirm writes nothing");
assert_eq!(
books.journal_raw(),
before,
"a stale confirm writes nothing"
);
// An operation's preview moves with the journal's head: a post by
// another session in between forces a re-preview.
let other = draft(&mut w, "2026-03-02", "Other", "5.00");
+14 -10
View File
@@ -325,11 +325,11 @@ fn consolidation_never_removes_an_entrys_only_evidence() {
let (_root, fixture) = legacy_duplicates("dupes-only", true);
let books = Books::placed("p6-dupes-only", &fixture);
let mut w = books.session("evidence");
let before = books.journal();
let before = books.journal_raw();
let r = w.call("books.consolidate_duplicates", json!({"confirmed": true}));
let why = answer_of(&r).unwrap_err();
assert!(why.contains("receipt_required"), "{why}");
assert_eq!(books.journal(), before, "a refusal journals nothing");
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
}
/// Plan P6 step 4: the kept file takes every subject the duplicates had;
@@ -351,8 +351,8 @@ fn consolidation_links_the_kept_file_to_every_subject() {
assert_eq!(preview["status"], "preview");
assert_eq!(preview["groups"][0]["keep"], 1);
assert_eq!(preview["groups"][0]["withdraw"], json!([2]));
let before = books.journal();
assert_eq!(before, books.journal(), "a preview journals nothing");
let before = books.journal_raw();
assert_eq!(before, books.journal_raw(), "a preview journals nothing");
let r = w.call("books.consolidate_duplicates", json!({"confirmed": true}));
let out = answer_of(&r).unwrap();
assert_eq!(out["status"], "consolidated", "{out}");
@@ -413,7 +413,7 @@ fn the_backfill_reads_an_old_fixtures_files_once() {
// Attachment 1 is a PDF (one page with text), 2 a text file, 3 a
// Markdown document.
for id in 1..=2 {
let before = books.journal();
let before = books.journal_raw();
let r = w.call("books.get_receipt", json!({"attachment_id": id}));
let out = answer_of(&r).unwrap();
assert_eq!(out["text_status"], "not_extracted", "{out}");
@@ -425,7 +425,11 @@ fn the_backfill_reads_an_old_fixtures_files_once() {
ledger_mcp::admin::Response::Extracted { status, .. } => assert_eq!(status, "ok"),
other => panic!("{other:?}"),
}
assert_ne!(books.journal(), before, "the backfill journals a record");
assert_ne!(
books.journal_raw(),
before,
"the backfill journals a record"
);
}
// The PDF's text is readable now, and its pages render.
let r = w.call("books.get_receipt", json!({"attachment_id": 1}));
@@ -446,18 +450,18 @@ fn the_backfill_reads_an_old_fixtures_files_once() {
common::clean_env(&mut extract, books.home.dir.path());
extract.output().unwrap()
};
let before = books.journal();
let before = books.journal_raw();
let out = run();
assert!(out.status.success(), "{out:?}");
assert!(
String::from_utf8_lossy(&out.stdout).contains("Read attachment 3"),
"{out:?}"
);
assert_ne!(books.journal(), before, "the command journals a record");
let after = books.journal();
assert_ne!(books.journal_raw(), before, "the command journals a record");
let after = books.journal_raw();
let out = run();
assert!(out.status.success(), "{out:?}");
assert_eq!(books.journal(), after, "an extract journals once");
assert_eq!(books.journal_raw(), after, "an extract journals once");
books.start();
let mut w = books.session("evidence");
let r = w.call("books.verify", json!({}));
+123 -87
View File
@@ -309,6 +309,8 @@ impl Agent {
}
fn send(&mut self, message: Value) {
// A tool call carries the request key every write needs (D-88).
let message = common::with_request_key(&message.to_string());
let stdin = self.run.child.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
stdin.flush().unwrap();
@@ -483,12 +485,19 @@ fn format_upgrade_waits_for_consent() {
assert!(refused.contains("format_upgrade_pending"), "{refused}");
assert!(refused.contains("no tool can"), "{refused}");
assert_eq!(journal(&dir), before, "a refusal journals nothing");
// What needs nothing new is made.
a.call(
"books.add_account",
json!({"code": "6000", "name": "Supplies", "account_type": "expense"}),
)
.unwrap();
// Nothing is written, whatever it is (D-89): a write that needs
// nothing new is refused the same, with the same remedy; reads work.
let refused = a
.call(
"books.add_account",
json!({"code": "6000", "name": "Supplies", "account_type": "expense"}),
)
.unwrap_err();
assert!(refused.starts_with("format_upgrade_pending"), "{refused}");
assert!(refused.contains("nothing can be written"), "{refused}");
assert!(refused.contains("wanderbooks books upgrade"), "{refused}");
assert_eq!(journal(&dir), before, "a refusal journals nothing");
a.call("books.chart", json!({})).unwrap();
let tools = a.request("tools/list", json!({}), 30);
let names: Vec<&str> = tools["result"]["tools"]
.as_array()
@@ -614,11 +623,11 @@ fn format_upgrade_waits_for_consent() {
assert_eq!(format_lines(&dir), 1);
}
/// plan P4b S4.4 (R-A step 4, 8.0.6 item 3): on books that haven't
/// declared `documents_v2`, an invoice carrying a new field (terms) is
/// refused with the upgrade remedy and journals nothing, while one
/// carrying none posts as before; after the owner's go-ahead the same call
/// is made, and takes the first number.
/// plan P4b S4.4 (R-A step 4, 8.0.6 item 3), under D-89: on books that
/// haven't declared the journal's call transactions, no write is taken, an
/// invoice carrying a new field (terms) no more than any other, and it
/// journals nothing; after the owner's go-ahead the same call is made, and
/// takes the first number.
#[test]
fn documents_v2_refused_until_consent() {
let home = Home::new("documents-v2");
@@ -632,31 +641,25 @@ fn documents_v2_refused_until_consent() {
.unwrap();
assert!(out.status.success(), "{out:?}");
let mut a = Agent::start(&home, "acme");
let customer = a
.call("books.add_customer", json!({"name": "Harbor Coffee"}))
.unwrap()["id"]
.clone();
let line = json!([{"description": "Design", "amount": "500.00"}]);
let with_terms = json!({"customer": customer.to_string(), "date": "2026-02-10",
let with_terms = json!({"customer": "1", "date": "2026-02-10",
"terms": "Net 30", "lines": line, "confirmed": true});
let before = journal(&dir);
let refused = a
.call("books.create_invoice", with_terms.clone())
.unwrap_err();
assert!(refused.starts_with("format_upgrade_pending"), "{refused}");
assert!(refused.contains("documents_v2"), "{refused}");
// (An invoice's preview, which writes nothing, is made as ever; its
// post is the write that waits: it is asked for after the go-ahead.)
for (tool, args) in [
("books.add_customer", json!({"name": "Harbor Coffee"})),
(
"books.draft_entry",
json!({"date": "2026-02-10", "description": "Waiting",
"no_party_reason": "test"}),
),
] {
let refused = a.call(tool, args).unwrap_err();
assert!(refused.starts_with("format_upgrade_pending"), "{refused}");
assert!(refused.contains("nothing can be written"), "{refused}");
}
assert_eq!(journal(&dir), before, "a refusal journals nothing");
// A document carrying none of the new fields posts as before, and
// files its copy; it takes no number (an older version reads it).
let plain = a
.call(
"books.create_invoice",
json!({"customer": customer.to_string(), "date": "2026-02-10", "due_date": "2026-03-12",
"lines": line, "confirmed": true}),
)
.unwrap();
assert!(plain.get("number").is_none(), "{plain}");
assert_eq!(plain["total"], "500.00");
// The go-ahead.
let mut words = home.words("books");
@@ -664,6 +667,12 @@ fn documents_v2_refused_until_consent() {
let (code, shown) = home.at_terminal(&words, &[PASS]);
assert_eq!(code, 0, "{shown}");
assert_eq!(format_lines(&dir), 1, "the format moved once");
let customer = a
.call("books.add_customer", json!({"name": "Harbor Coffee"}))
.unwrap()["id"]
.clone();
let mut with_terms = with_terms;
with_terms["customer"] = json!(customer.to_string());
let made = a.call("books.create_invoice", with_terms).unwrap();
assert_eq!(made["number"], "INV-0001", "{made}");
assert_eq!(made["terms"], "Net 30", "{made}");
@@ -700,15 +709,17 @@ fn copy_private(from: &Path, to: &Path) {
/// ```text
/// INVARIANTS:
/// 1. Before consent: the books open and are served, waiting; P2's
/// database is never written; what P2 can read is written, and every
/// write P2 would refuse or misread is refused, journaling nothing
/// (a setting key, a tax category, a depreciation catch-up, a members
/// close counted from the count's start, an invoice's or bill's line
/// naming its project).
/// database is never written; they are read as ever and take no
/// write at all (D-89, WB-format-11: every write is one transaction,
/// and books written before that can't keep it), every one refused
/// with the upgrade remedy, journaling nothing.
/// 2. The consent backup holds the books exactly as they were, keys and
/// vault too; the upgrade is one line after P2's, byte for byte.
/// 3. After it: the same figures, and every refused write is made; the
/// books verify; P2's database is still byte for byte.
/// 3. After it: the same figures, and every write is made, those P2
/// would have refused or misread among them (a setting key, a tax
/// category, a depreciation catch-up, a members close counted from
/// the count's start, an invoice's or bill's line naming its
/// project); the books verify; P2's database is still byte for byte.
/// ```
#[test]
fn books_p2_served_cut_over_whole() {
@@ -729,11 +740,9 @@ fn books_p2_served_cut_over_whole() {
let mut a = Agent::start(&home, "acme");
let start = a.call("books.start", json!({})).unwrap();
assert_eq!(start["format_upgrade"]["format"], 2, "{start}");
let verified = a.call("books.verify", json!({})).unwrap();
assert_eq!(verified["status"], "ok", "{verified}");
assert_eq!(verified["events"], 470);
assert_eq!(verified["database"], ledger_store::db_file());
assert_eq!(verified["other_databases"], json!(["wanderbooks.db"]));
// (books.verify can rebuild the projection: a write, so it waits for
// the go-ahead like every other, and is asked after it, below.)
assert_eq!(journal(&dir).iter().filter(|b| **b == b'\n').count(), 470);
let figures = |a: &mut Agent| {
[
a.call("books.trial_balance", json!({"as_of": "2025-12-31"})),
@@ -747,7 +756,68 @@ fn books_p2_served_cut_over_whole() {
};
let before = figures(&mut a);
// INVARIANT 1: what P2 reads is written; the rest waits.
// INVARIANT 1 (D-89): the books take no write before the go-ahead,
// whatever the write, and journal nothing for the refusal.
let waiting = journal(&dir);
for (tool, args) in [
(
"books.add_account",
json!({"code": "6600", "name": "Travel", "account_type": "expense"}),
),
(
"books.create_period",
json!({"name": "2025-Q2", "start": "2025-04-01", "end": "2025-06-30"}),
),
("books.add_project", json!({"name": "Lighthouse"})),
("books.add_customer", json!({"name": "Ridgeway Co"})),
(
"books.draft_entry",
json!({"date": "2026-02-12", "description": "Waiting for the go-ahead",
"no_party_reason": "test"}),
),
(
"books.raise_item",
json!({"title": "Ask the CPA", "decided_by": "Avery Quill"}),
),
] {
let e = a.call(tool, args).unwrap_err();
assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}");
assert!(e.contains("nothing can be written"), "{tool}: {e}");
}
assert_eq!(journal(&dir), waiting, "a refusal journals nothing");
assert!(journal(&dir).starts_with(&p2_journal));
// The books are read as ever.
assert_eq!(figures(&mut a), before);
// INVARIANT 2: the go-ahead.
let mut words = home.words("books");
words.extend(["upgrade".into(), "acme".into()]);
let (code, shown) = home.at_terminal(&words, &[PASS]);
assert_eq!(code, 0, "{shown}");
let after = journal(&dir);
assert!(after.starts_with(&waiting));
assert_eq!(
format_lines(&dir),
2,
"P2's declaration, then the upgrade's"
);
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
assert_eq!(
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
waiting.as_slice(),
"the backup holds the books as they were"
);
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
let out = Command::new("git")
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
.args(["show", &format!("{}:{kept}", backup.trim())])
.output()
.unwrap();
assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}");
}
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
// INVARIANT 3: every write is taken now: first what P2 could read.
a.call(
"books.add_account",
json!({"code": "6600", "name": "Travel", "account_type": "expense"}),
@@ -822,7 +892,6 @@ fn books_p2_served_cut_over_whole() {
)
.unwrap()["id"]
.clone();
let waiting = journal(&dir);
let refused: Vec<(&str, Value)> = vec![
// A source correction (source_revisions, P5): an older version
// refuses the type.
@@ -921,53 +990,20 @@ fn books_p2_served_cut_over_whole() {
json!({"entry_id": 1, "method": {"reasoning_effort": "high"}}),
),
];
for (tool, args) in &refused {
let e = a.call(tool, args.clone()).unwrap_err();
assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}");
}
assert_eq!(journal(&dir), waiting, "a refusal journals nothing");
assert!(journal(&dir).starts_with(&p2_journal));
assert_eq!(
std::fs::read(dir.join(ledger_store::LEGACY_DB_FILE)).unwrap(),
p2_db,
"P2's database is never written"
);
// INVARIANT 2: the go-ahead.
let mut words = home.words("books");
words.extend(["upgrade".into(), "acme".into()]);
let (code, shown) = home.at_terminal(&words, &[PASS]);
assert_eq!(code, 0, "{shown}");
let after = journal(&dir);
assert!(after.starts_with(&waiting));
assert_eq!(
format_lines(&dir),
2,
"P2's declaration, then the upgrade's"
);
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
assert_eq!(
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
waiting.as_slice(),
"the backup holds the books as they were"
);
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
let out = Command::new("git")
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
.args(["show", &format!("{}:{kept}", backup.trim())])
.output()
.unwrap();
assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}");
}
// INVARIANT 3.
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
// The writes P2 would have refused or misread, made now.
for (tool, args) in refused {
a.call(tool, args.clone())
.unwrap_or_else(|e| panic!("{tool} after the upgrade: {e}"));
}
let verified = a.call("books.verify", json!({})).unwrap();
assert_eq!(verified["status"], "ok", "{verified}");
// It counts the lines there were when it ran, all of them: a call that
// wrote nothing leaves no closing line of its own.
let events = verified["events"].as_u64().unwrap();
let on_disk = journal(&dir).iter().filter(|b| **b == b'\n').count() as u64;
assert!(events > 470 && events == on_disk, "{events} of {on_disk}");
assert_eq!(verified["database"], ledger_store::db_file());
assert_eq!(verified["other_databases"], json!(["wanderbooks.db"]));
assert_eq!(
std::fs::read(dir.join(ledger_store::LEGACY_DB_FILE)).unwrap(),
p2_db,
+4 -2
View File
@@ -623,7 +623,8 @@ async fn raw_upload(http: &reqwest::Client, session: &str, bytes: &[u8], name: &
let begin = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {
"name": "books.begin_upload", "arguments": {
"sha256": ledger_store::journal::sha256_hex(bytes), "size": bytes.len(),
"mime_type": "application/pdf", "file_name": name, "purpose": "document"}}});
"mime_type": "application/pdf", "file_name": name, "purpose": "document",
"request_key": common::fresh_request_key()}}});
let r = http
.post("http://localhost/b/acme/mcp")
.header("content-type", "application/json")
@@ -681,7 +682,8 @@ async fn a_call_whose_client_hung_up_finishes_before_the_close() {
let upload = raw_upload(&http, &session, &bytes, "big.pdf").await;
let call = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {
"name": "books.file_document", "arguments": {
"category": "formation", "upload_id": upload}}});
"category": "formation", "upload_id": upload,
"request_key": common::fresh_request_key()}}});
let response = http
.post("http://localhost/b/acme/mcp")
.header("content-type", "application/json")
+56 -38
View File
@@ -787,7 +787,7 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() {
let handed_over = [w9_back, mcp.handed(&ws["csv"]), mcp.handed(&pkg["file"])];
// Given back, each is refused by its bytes, by every way a file is
// filed.
let journal = books.journal();
let journal = books.journal_raw();
for (n, bytes) in handed_over.iter().enumerate() {
// One upload, refused by each tool and so left for the next.
let up = mcp.upload(bytes, "receipt.pdf", "application/pdf", "receipt");
@@ -805,7 +805,20 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() {
);
}
}
assert_eq!(books.journal(), journal, "a refusal stored something");
// (Each upload begun is a call, with its closing line: those only.)
let calls_only = |j: Vec<u8>| -> Vec<String> {
String::from_utf8(j)
.unwrap()
.lines()
.filter(|l| !l.contains(r#""type":"call.closed""#))
.map(str::to_string)
.collect()
};
assert_eq!(
calls_only(books.journal()),
calls_only(journal),
"a refusal stored something"
);
// Without TINs, the 1099 worksheet is an ordinary file: it may be
// filed like any other.
let plain = mcp.call("books.vendor_1099", json!({"year": 2026, "csv": true}));
@@ -1765,7 +1778,8 @@ fn close_period_shows_each_members_running_split() {
fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
// Books P1 kept, which P2 moved to its journal format (format 2, none
// of the features since), left in a data root, with their members set
// as an agent sets them: books waiting for their format upgrade.
// as an agent sets them once they are upgraded: books waiting for
// their format upgrade, which (D-89) take no write until then.
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../ledger-store/tests/fixtures/old-books/x_member_closes");
let books = Books::placed("members-old", &fixture);
@@ -1775,13 +1789,6 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
.declare_journal_format(2, &[])
.unwrap();
books.start();
books.settle(
"[company]\ntax_form = \"1065\"\n\n\
[[company.members]]\nname = \"Ann\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\
distribution_account = \"3100\"\n\n\
[[company.members]]\nname = \"Bo\"\nshare = \"50%\"\ncapital_account = \"3001\"\n\n\
[books]\nreceipt_threshold = \"10000\"\n",
);
let mut mcp = Mcp::spawn(&books);
init(&mut mcp);
let rules = |mcp: &mut Mcp| -> Vec<Value> {
@@ -1805,6 +1812,32 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
let mut want: Vec<Value> = old.iter().map(|r| json!(r)).collect();
want.extend([Value::Null, json!("members_run"), json!("members_run")]);
assert_eq!(rules(&mut mcp), want);
// Read as ever; no write is taken (D-89), whatever it is.
let refused = mcp.call_err(
"books.draft_entry",
json!({"date": "2026-12-10", "description": "two cents"}),
);
assert!(refused.starts_with("format_upgrade_pending:"), "{refused}");
// The owner's go-ahead, as the app gives it (ledger-gui owner.rs, after
// the passphrase and a verified backup): the server stopped, the books
// moved to this version's format, and served again.
drop(mcp);
books.stop();
ledger_store::Store::open(&books.dir())
.unwrap()
.upgrade_format()
.unwrap()
.expect("old books wait for the upgrade");
books.start();
books.settle(
"[company]\ntax_form = \"1065\"\n\n\
[[company.members]]\nname = \"Ann\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\
distribution_account = \"3100\"\n\n\
[[company.members]]\nname = \"Bo\"\nshare = \"50%\"\ncapital_account = \"3001\"\n\n\
[books]\nreceipt_threshold = \"10000\"\n",
);
let mut mcp = Mcp::spawn(&books);
init(&mut mcp);
let e = mcp.call(
"books.draft_entry",
@@ -1844,29 +1877,6 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
preview["lines"],
json!(["Debit 4000 0.02", "Credit 3001 0.02"])
);
// Books an older version wrote: the close counted from its regime's
// start waits for the owner's go-ahead (D-39), which no tool gives.
let refused = mcp.call_err(
"books.close_period",
json!({"period_id": dec["period_id"], "confirmed": true}),
);
assert!(
refused.starts_with("format_upgrade_pending:") && refused.contains("members_cumulative"),
"{refused}"
);
// The owner's go-ahead, as the app gives it (ledger-gui owner.rs, after
// the passphrase and a verified backup): the server stopped, the books
// moved to this version's format, and served again.
drop(mcp);
books.stop();
ledger_store::Store::open(&books.dir())
.unwrap()
.upgrade_format()
.unwrap()
.expect("old books wait for the upgrade");
books.start();
let mut mcp = Mcp::spawn(&books);
init(&mut mcp);
let closed = mcp.call(
"books.close_period",
json!({"period_id": dec["period_id"], "confirmed": true}),
@@ -2988,9 +2998,11 @@ fn rename_account_end_to_end_defect_15() {
);
assert!(err.contains(says), "{name:?}: {err}");
}
// (The first verify is a call too: its own closing line is the one
// line the second counts more; the refusals wrote none.)
assert_eq!(
mcp.call("books.verify", json!({"blobs": false}))["events"],
json!(events),
json!(events + 1),
"refusals write nothing"
);
let out = mcp.call(
@@ -3009,8 +3021,10 @@ fn rename_account_end_to_end_defect_15() {
let after = mcp.call("books.verify", json!({"blobs": false}));
assert_eq!(after["status"], "ok");
// New books declare account_renamed (with the rest of this version's
// format) as they are created: the rename journals only itself.
assert_eq!(after["events"], json!(events + 1), "the rename");
// format) as they are created: the rename journals only itself, in
// its frame (begun, the rename, closed), after the two verifies'
// closing lines.
assert_eq!(after["events"], json!(events + 1 + 1 + 3), "the rename");
let chart = mcp.call("books.chart", json!({}));
let acct = chart["accounts"]
.as_array()
@@ -3300,7 +3314,7 @@ fn files_pass_only_by_handle_in_and_out() {
);
mcp.call("books.import_chart_csv", json!({"upload_id": chart}));
// In: an inline file is refused as unknown, storing nothing.
let journal = books.journal();
let journal = books.journal_raw();
for (name, args) in [
(
"books.attach_receipt",
@@ -3320,7 +3334,11 @@ fn files_pass_only_by_handle_in_and_out() {
"{name}: {resp}"
);
}
assert_eq!(books.journal(), journal, "an inline file stored something");
assert_eq!(
books.journal_raw(),
journal,
"an inline file stored something"
);
// A posted entry with its receipt, and an asset with its tag.
let receipt = b"%PDF-1.4 a receipt for the laptop";
let e = mcp.call(
+4 -1
View File
@@ -372,6 +372,8 @@ impl Agent {
}
fn send(&mut self, message: Value) {
// A tool call carries the request key every write needs (D-88).
let message = common::with_request_key(&message.to_string());
let stdin = self.run.child.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
stdin.flush().unwrap();
@@ -1383,7 +1385,8 @@ fn a_call_cancelled_at_once_is_never_made() {
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
"name": "books.add_account",
"arguments": {"code": format!("{}", 1000 + k), "name": format!("A{k}"),
"account_type": "asset"}}}),
"account_type": "asset",
"request_key": common::fresh_request_key()}}}),
json!({"jsonrpc": "2.0", "method": "notifications/cancelled",
"params": {"requestId": id}})
)
+31 -12
View File
@@ -71,7 +71,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf {
impl Mcp {
fn start(dir: &TestDir, toml: &Path) -> Self {
let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap()));
Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap()))
}
/// [`Mcp::start`] with these settings, or none (books that take no
/// write, D-89, can't be given any).
fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self {
let wire = dir.start(settings);
let mut mcp = Self {
books_dir: None,
wire,
@@ -101,7 +107,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -145,7 +158,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -175,7 +188,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -202,10 +215,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
@@ -300,6 +313,12 @@ fn books_in(name: &str, p2: bool) -> Mcp {
.unwrap();
}
let toml = books_toml(&dir, "Spec Co", "financing_accounts = [\"2100\"]\n");
if p2 {
// Books that take no write (D-89): no settings, no chart.
let mut m = Mcp::start_settings(&dir, None);
m.books_dir = Some(dir);
return m;
}
let mut m = Mcp::start(&dir, &toml);
m.accounts(CHART);
m.books_dir = Some(dir);
@@ -321,6 +340,7 @@ impl Mcp {
.unwrap()
.expect("P2's books wait for the upgrade");
let mut m = Mcp::start(&dir, &dir.join("wanderbooks.toml"));
m.accounts(CHART);
m.books_dir = Some(dir);
m
}
@@ -623,18 +643,17 @@ fn set_w9_asks_for_the_w9_flags_feature_before_its_first_line() {
let w9 = json!({"party": "Harbor Design LLC", "received_on": "2026-03-02",
"entity_type": "LLC (partnership)", "tin_last4": "4321", "kept_at": "CPA portal"});
let mut m = books_in("set-w9-feature", true);
let why = m.refuse("books.set_w9", w9.clone());
assert!(why.starts_with("format_upgrade_pending:"), "{why}");
assert!(why.contains("nothing can be written"), "{why}");
assert_eq!(m.count("party.w9_set"), 0, "nothing half done");
let mut m = m.upgraded();
m.add_party("Harbor Design LLC", &["contractor"]);
m.ok("books.add_vendor", json!({"name": "Harbor Design LLC"}));
let why = m.refuse("books.set_w9", w9.clone());
assert!(
why.starts_with("format_upgrade_pending:") && why.contains("vendor_1099_decisions"),
"{why}"
);
assert_eq!(m.count("party.w9_set"), 0, "nothing half done");
let mut fresh = books("set-w9-feature-new");
fresh.add_party("Harbor Design LLC", &["contractor"]);
fresh.ok("books.add_vendor", json!({"name": "Harbor Design LLC"}));
for mut m in [m.upgraded(), fresh] {
for mut m in [m, fresh] {
let before = m.journal_types().len();
m.ok("books.set_w9", w9.clone());
let added = m.journal_types()[before..].to_vec();
+13 -6
View File
@@ -106,7 +106,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -150,7 +157,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -180,7 +187,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -207,10 +214,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
@@ -1593,7 +1600,7 @@ fn a_disposal_inside_a_posted_month_takes_back_the_extra_days() {
fn run_depreciation_skips_a_month_that_rounds_to_nothing() {
let mut m = books("zero-month");
let (a, _) = m.register_ok(json!({"cost": "0.01", "useful_life_months": 3}));
let before = m.journal();
let before = m.journal_raw();
let r = m.ok("books.run_depreciation", json!({"period": "2026-01"}));
assert_eq!(r["runs"], json!([]));
let skipped = r["skipped"].as_array().unwrap();
@@ -1606,7 +1613,7 @@ fn run_depreciation_skips_a_month_that_rounds_to_nothing() {
.contains("rounds to nothing"),
"{r}"
);
assert_eq!(m.journal(), before, "nothing journaled");
assert_eq!(m.journal_raw(), before, "nothing journaled");
let r = m.ok("books.run_depreciation", json!({"period": "2026-02"}));
assert_eq!(canon(r["runs"][0]["amount"].as_str().unwrap()), "0.01");
}
+11 -4
View File
@@ -110,7 +110,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -156,7 +163,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -186,7 +193,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -213,10 +220,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
+25 -16
View File
@@ -224,7 +224,9 @@ impl Mcp {
mcp
}
fn journal(&self) -> Vec<u8> {
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -285,7 +287,7 @@ impl Mcp {
/// Call a tool and check invariants 1, 2, 3 and 7 on the outcome.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let files = self.read_only(name).then(|| self.data_files());
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
@@ -305,13 +307,13 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"invariant 2: refused {name} {args} changed the journal ({out:?})"
);
}
if let Some(files) = files {
assert!(
self.journal() == before,
self.journal_raw() == before,
"readOnlyHint: {name} {args} changed the journal"
);
assert_eq!(
@@ -1950,16 +1952,16 @@ fn inv4_post_and_reverse_preview_without_confirmed() {
json!({"entry_id": e, "confirmed": false}),
json!({"entry_id": e, "confirmed": null}),
] {
let before = m.journal();
let before = m.journal_raw();
let p = m.ok("books.post_entry", args.clone());
assert_eq!(p["status"], "preview", "{args}: {p}");
assert!(m.journal() == before, "post_entry preview {args} wrote");
assert!(m.journal_raw() == before, "post_entry preview {args} wrote");
assert_eq!(m.entry_status(e), "draft");
}
let before = m.journal();
let before = m.journal_raw();
let posted = m.post(e).ok("confirmed post");
assert_eq!(posted["status"], "posted");
assert!(m.journal() != before, "confirmed post wrote nothing");
assert!(m.journal_raw() != before, "confirmed post wrote nothing");
assert_eq!(m.entry_status(e), "posted");
let rev = json!({"entry_id": e, "date": "2026-04-02", "description": "undo"});
@@ -1968,17 +1970,20 @@ fn inv4_post_and_reverse_preview_without_confirmed() {
args.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
let before = m.journal();
let before = m.journal_raw();
let p = m.ok("books.reverse_entry", args.clone());
assert_eq!(p["status"], "preview", "{args}: {p}");
assert!(m.journal() == before, "reverse_entry preview {args} wrote");
assert!(
m.journal_raw() == before,
"reverse_entry preview {args} wrote"
);
}
let mut args = rev;
args["confirmed"] = json!(true);
let before = m.journal();
let before = m.journal_raw();
let r = m.ok("books.reverse_entry", args);
assert_eq!(r["status"], "posted", "{r}");
assert!(m.journal() != before);
assert!(m.journal_raw() != before);
let tb = m.ok("books.trial_balance", json!({"as_of": "2026-12-31"}));
assert_eq!(tb["balanced"], true);
}
@@ -1999,7 +2004,7 @@ fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() {
);
m.attach(Some(e), b"rent receipt");
m.post(e).ok("post");
let before = m.journal();
let before = m.journal_raw();
for confirmed in [None, Some(false), Some(true)] {
let mut args = json!({"entry_id": e, "date": "2026-05-09", "description": "early"});
if let Some(c) = confirmed {
@@ -2011,7 +2016,7 @@ fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() {
"{why}"
);
}
assert!(m.journal() == before, "a refused reversal wrote");
assert!(m.journal_raw() == before, "a refused reversal wrote");
let p = m.ok(
"books.reverse_entry",
json!({"entry_id": e, "date": "2026-05-10", "description": "same day"}),
@@ -2144,7 +2149,7 @@ fn inv5_bad_threshold_refused_when_set() {
let dir = test_dir("inv5-set");
let toml = books_toml(&dir, "25.00", "");
let mut m = Mcp::start(&dir, &toml);
let before = m.journal();
let before = m.journal_raw();
assert!(!before.is_empty(), "the books keep a journal");
for bad in ["-1", "abc", "-0.01", "", "1,000", "ten"] {
m.refuse(
@@ -2153,7 +2158,11 @@ fn inv5_bad_threshold_refused_when_set() {
"decided_by": "Test Owner"}),
);
}
assert_eq!(m.journal(), before, "a refused threshold journals nothing");
assert_eq!(
m.journal_raw(),
before,
"a refused threshold journals nothing"
);
let rule = m.ok("books.settings", json!({}))["receipt_rule"].clone();
assert!(rule.as_str().unwrap().contains("25.00"), "{rule}");
}
+15 -8
View File
@@ -107,7 +107,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -151,7 +158,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -181,7 +188,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -208,10 +215,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
@@ -1224,13 +1231,13 @@ fn require_refuses_until_tagged_or_marked_none() {
json!({}),
&[("6999", "debit", "5.00"), ("1000", "credit", "5.00")],
);
let before = m.journal();
let before = m.journal_raw();
let e = m.refuse(
"books.post_entry",
json!({"entry_id": id, "confirmed": true}),
);
assert!(e.contains("party_required"), "{e}");
assert_eq!(m.journal(), before, "refusal journals nothing");
assert_eq!(m.journal_raw(), before, "refusal journals nothing");
m.ok(
"books.set_entry_party",
json!({"entry_id": id, "party": bank.to_string()}),
@@ -1608,10 +1615,10 @@ fn under_require_engine_postings_name_their_counterparty() {
let sale = json!({"asset_id": sold, "date": "2026-06-30", "proceeds": "500.00",
"proceeds_account": "1000", "gain_loss_account": "7100",
"confirmed": true});
let before = m.journal();
let before = m.journal_raw();
let e = m.refuse("books.dispose_asset", sale.clone());
assert!(e.contains("party_required"), "{e}");
assert!(m.journal() == before, "refused, nothing journaled");
assert!(m.journal_raw() == before, "refused, nothing journaled");
let mut with_buyer = sale;
with_buyer["buyer"] = json!("Buyer Co");
let d = m.ok("books.dispose_asset", with_buyer);
+32 -11
View File
@@ -78,7 +78,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf {
impl Mcp {
fn start(dir: &TestDir, toml: &Path) -> Self {
let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap()));
Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap()))
}
/// [`Mcp::start`] with these settings, or none (books that take no
/// write, D-89, can't be given any).
fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self {
let wire = dir.start(settings);
let mut mcp = Self {
books_dir: None,
wire,
@@ -108,7 +114,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -152,7 +165,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -182,7 +195,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -209,10 +222,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
@@ -312,6 +325,12 @@ fn books_in(name: &str, p2: bool) -> Mcp {
[[company.members]]\nname = \"Tobin Harlow\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\
[[company.members]]\nname = \"Morgan Ellis\"\nshare = \"50%\"\ncapital_account = \"3001\"\n",
);
if p2 {
// Books that take no write (D-89): no settings, no chart.
let mut m = Mcp::start_settings(&dir, None);
m.books_dir = Some(dir);
return m;
}
let mut m = Mcp::start(&dir, &toml);
m.accounts(CHART);
m.add_party("Tobin Harlow", &["member"]);
@@ -336,6 +355,10 @@ impl Mcp {
.unwrap()
.expect("P2's books wait for the upgrade");
let mut m = Mcp::start(&dir, &dir.join("wanderbooks.toml"));
m.accounts(CHART);
m.add_party("Tobin Harlow", &["member"]);
m.add_party("Morgan Ellis", &["member"]);
m.add_party("Harbor Bank", &["financial_institution"]);
m.books_dir = Some(dir);
m
}
@@ -563,12 +586,12 @@ fn defect24_creditor_of_round_trips_and_a_card_fee_is_not_a_payment() {
"nothing declared on the way"
);
// The same list again changes nothing.
let journal = m.journal();
let journal = m.journal_raw();
m.ok(
"books.update_party",
json!({"party": "Harbor Bank", "creditor_of": ["2050"]}),
);
assert!(m.journal() == journal);
assert!(m.journal_raw() == journal);
assert_eq!(
part(&mut m, fee, "Harbor Bank"),
(
@@ -616,10 +639,8 @@ fn update_party_asks_for_the_creditor_feature_before_its_first_line() {
json!({"party": "Harbor Bank", "notes": "the card's issuer", "creditor_of": ["2050"]});
let mut m = books_in("feature-first", true);
let why = m.refuse("books.update_party", change.clone());
assert!(
why.starts_with("format_upgrade_pending:") && why.contains("party_creditors"),
"{why}"
);
assert!(why.starts_with("format_upgrade_pending:"), "{why}");
assert!(why.contains("nothing can be written"), "{why}");
assert_eq!(m.count("party.updated"), 0, "nothing half done");
for mut m in [m.upgraded(), books("feature-first-new")] {
let start = m.journal_types().len();
+37 -27
View File
@@ -77,7 +77,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf {
impl Mcp {
fn start(dir: &TestDir, toml: &Path) -> Self {
let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap()));
Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap()))
}
/// [`Mcp::start`] with these settings, or none (books that take no
/// write, D-89, can't be given any).
fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self {
let wire = dir.start(settings);
let mut mcp = Self {
books_dir: None,
wire,
@@ -107,7 +113,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -151,7 +164,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -181,7 +194,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -208,10 +221,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
@@ -253,6 +266,7 @@ fn books(name: &str) -> Mcp {
/// for their format upgrade.
fn books_in(name: &str, p2: bool) -> Mcp {
let dir = test_dir(name);
let toml = books_toml(&dir, "Spec Co", "");
if p2 {
ledger_store::Store::create_in_format(
&dir.books_data(),
@@ -263,8 +277,11 @@ fn books_in(name: &str, p2: bool) -> Mcp {
},
)
.unwrap();
// Books that take no write (D-89): no settings, no chart.
let mut m = Mcp::start_settings(&dir, None);
m.books_dir = Some(dir);
return m;
}
let toml = books_toml(&dir, "Spec Co", "");
let mut m = Mcp::start(&dir, &toml);
m.accounts(CHART);
m.books_dir = Some(dir);
@@ -503,7 +520,7 @@ fn update_project_with_nothing_new_journals_nothing() {
"books.add_project",
json!({"name": "Harbor", "kind": "client"}),
);
let before = m.journal();
let before = m.journal_raw();
m.ok(
"books.update_project",
json!({"project": "Harbor", "kind": "client"}),
@@ -512,7 +529,7 @@ fn update_project_with_nothing_new_journals_nothing() {
"books.update_project",
json!({"project": "harbor", "name": "Harbor"}),
);
assert_eq!(m.journal(), before);
assert_eq!(m.journal_raw(), before);
}
// ------------------------------------------------- figures
@@ -914,17 +931,16 @@ fn show_project_sends_its_target() {
);
}
/// Books an older version wrote take no write at all (D-89): not a
/// project, not a link to one, nothing, and the refusal journals nothing.
/// (The feature `projects` itself waiting is the store's:
/// `ledger-store` `tests/projects.rs`.)
#[test]
fn project_writes_wait_for_the_format_upgrade() {
let mut m = books_in("upgrade", true);
// A name alone: a plain class, accepted.
m.ok("books.add_project", json!({"name": "Harbor"}));
let a = match m.doc(b"%PDF c", json!([])) {
Out::Ok(v) => v["attachment_id"].as_u64().unwrap(),
o => panic!("{o:?}"),
};
let head = m.journal();
let head = m.journal_raw();
for (tool, args) in [
("books.add_project", json!({"name": "Harbor"})),
(
"books.add_project",
json!({"name": "Dock", "kind": "client"}),
@@ -935,7 +951,7 @@ fn project_writes_wait_for_the_format_upgrade() {
),
(
"books.link_attachment",
json!({"attachment_id": a, "subject": {"kind": "project", "id": "Harbor"}}),
json!({"attachment_id": 1, "subject": {"kind": "project", "id": "Harbor"}}),
),
(
"books.record_decision",
@@ -944,16 +960,10 @@ fn project_writes_wait_for_the_format_upgrade() {
),
] {
let why = m.refuse(tool, args);
assert!(
why.starts_with("format_upgrade_pending:") && why.contains("projects"),
"{tool}: {why}"
);
assert!(why.starts_with("format_upgrade_pending:"), "{tool}: {why}");
assert!(why.contains("nothing can be written"), "{tool}: {why}");
}
// Filing with a link to a project is refused before the file is filed.
let out = m.doc(b"%PDF d", json!([{"kind": "project", "id": "Harbor"}]));
assert!(out.refused());
assert!(out.err_text().contains("projects"), "{out:?}");
assert_eq!(m.journal(), head, "nothing journaled");
assert_eq!(m.journal_raw(), head, "nothing journaled");
}
#[test]
@@ -1474,7 +1484,7 @@ fn books_without_the_feature_refuse_a_tagged_document() {
);
let cedar = m.ok("books.add_customer", json!({"name": "Cedar"}))["id"].clone();
let v = m.ok("books.add_vendor", json!({"name": "Dana"}))["id"].clone();
let head = m.journal();
let head = m.journal_raw();
for (tool, key, party) in [
("books.create_invoice", "customer", &cedar),
("books.create_bill", "vendor", &v),
@@ -1490,7 +1500,7 @@ fn books_without_the_feature_refuse_a_tagged_document() {
"{tool}: {why}"
);
}
assert_eq!(m.journal(), head, "nothing journaled");
assert_eq!(m.journal_raw(), head, "nothing journaled");
m.ok(
"books.create_invoice",
json!({"customer": (cedar).to_string(), "date": "2026-03-02", "due_date": "2026-04-01", "lines": [
+15 -6
View File
@@ -115,7 +115,14 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88): the events.
fn journal(&self) -> Vec<u8> {
common::without_call_lines(&self.journal_raw())
}
/// The journal, byte for byte: what a check that a refusal or a
/// preview "journaled nothing" compares, so a stray frame line is seen.
fn journal_raw(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
}
@@ -161,7 +168,7 @@ impl Mcp {
/// Call a tool; a refusal must leave the journal unchanged, a success
/// must match the outputSchema.
fn tool(&mut self, name: &str, args: Value) -> Out {
let before = self.journal();
let before = self.journal_raw();
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
let out = if let Some(err) = resp.get("error") {
Out::RpcErr(err.clone())
@@ -191,7 +198,7 @@ impl Mcp {
};
if out.refused() {
assert!(
self.journal() == before,
self.journal_raw() == before,
"refused {name} {args} changed the journal ({out:?})"
);
}
@@ -218,10 +225,10 @@ impl Mcp {
/// `ok`, and the journal must not change (read-only tools).
fn read_only(&mut self, name: &str, args: Value) -> Value {
let before = self.journal();
let before = self.journal_raw();
let v = self.ok(name, args);
assert!(
self.journal() == before,
self.journal_raw() == before,
"read-only {name} changed the journal"
);
v
@@ -1021,7 +1028,7 @@ fn purge_deletes_the_vault_records_and_journals_why() {
json!({"party": "Nobody", "reason": "x", "confirmed": true}),
);
// A preview changes nothing.
let journal = m.journal();
let journal = m.journal_raw();
let p = m.ok(
"books.purge_tin",
json!({"party": "Acme Design", "reason": "retention over"}),
@@ -1030,7 +1037,7 @@ fn purge_deletes_the_vault_records_and_journals_why() {
assert_eq!(p["tin_in_vault"], true);
assert_eq!(p["w9_file_in_vault"], true);
assert_eq!(p["tin_last4"], "2846");
assert!(m.journal() == journal);
assert!(m.journal_raw() == journal);
assert!(m.vault().join(format!("tin-{acme}.bin")).exists());
// Without the key, confirmed: gone, and journaled.
std::fs::remove_file(m.key()).unwrap();
@@ -2097,6 +2104,8 @@ fn idempotent_tools_change_nothing_when_repeated() {
m.ok(name, args.clone());
let (journal, vault) = (m.journal(), vault_bytes(&m));
m.ok(name, args.clone());
// The events, not the frames: a repeat with a new key is a call of
// its own, and its frame is no change of the books.
let changed = m.journal() != journal || vault_bytes(&m) != vault;
*repeats_change.entry(name).or_default() |= changed;
}