feat(mcp): every write call is one transaction with a request key (P15 T1, D-88, D-89)

Accounting reasoning: these are financial books reached over the internet,
where a request is retried. A write whose answer is lost and then sent again
must not post twice, a call half done must not be left looking done, and a
failed write must be on the record.

Every tool that can change the books (83 of the 140: three that only read
what is sealed and may answer with a TIN are reads) takes a required
`request_key`, added to its schema in tools/list and taken out of the
arguments before the tool runs, so no tool, preview digest or check changes.
A write without a usable key is refused in words. Write calls take turns,
and each runs as one transaction of the store: opened (or answered from the
books if its key committed: the same tool and arguments return the first
answer and write nothing; other arguments are refused as a misuse of the
key; the access log says `repeat`), then closed with its answer if it
answered ok, or rolled back and closed `failed` if it errored, failed or was
stopped by a close. Books an older version wrote take no write at all until
the owner's go-ahead (D-89): every write is refused with the upgrade remedy;
reads work as ever. `books.import_bank_csv` is one transaction like the rest.

The handbook, docs/mcp-interface.md, the claims (WB-format-8 to 12, and
WB-format-3 amended for D-89) and docs/parity.md say so. Tests that wrote to
old books through the tools now assert the refusal and write after the
upgrade; the shared wire helpers add a fresh key to every tool call (the
journal helpers leave the call frames out, as they left out nothing before),
so no other test changed. The store-level `_waits_for_<feature>` tests still
check each feature's own gate. No figure and no golden moved.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 09:43:52 -07:00
1 parent 2633109d55
commit e542319e63
25 files changed
+1084 -186

No files matched your search

+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
@@ -1083,7 +1083,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",
@@ -1521,7 +1522,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",
@@ -1645,7 +1647,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",
@@ -2171,7 +2174,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",
@@ -2623,9 +2627,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,265 @@
//! 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.
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"
);
}
+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(
+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: the call's own closing
// line comes after its answer.
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")
+49 -35
View File
@@ -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()
+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}})
)
+24 -9
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,8 +107,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
@@ -300,6 +309,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 +336,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 +639,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();
+4 -1
View File
@@ -106,8 +106,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
+4 -1
View File
@@ -110,8 +110,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
+4 -1
View File
@@ -224,8 +224,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// What a read-only tool must leave as it was: every file of the books
+4 -1
View File
@@ -107,8 +107,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
+23 -6
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,8 +114,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
@@ -312,6 +321,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 +351,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
}
@@ -616,10 +635,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();
+24 -18
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,8 +113,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
@@ -253,6 +262,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 +273,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);
@@ -914,17 +927,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();
for (tool, args) in [
("books.add_project", json!({"name": "Harbor"})),
(
"books.add_project",
json!({"name": "Dock", "kind": "client"}),
@@ -935,7 +947,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,15 +956,9 @@ 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");
}
+4 -1
View File
@@ -115,8 +115,11 @@ impl Mcp {
mcp
}
/// The journal, without the frames of tool calls (D-88).
fn journal(&self) -> Vec<u8> {
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
common::without_call_lines(
&std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(),
)
}
/// The journal's line types, in order.
+4 -4
View File
@@ -1,11 +1,11 @@
# The format upgrade
- A new version of wanderbooks can keep the books in a newer journal format than the version that wrote them. Books an older version wrote wait for a format upgrade: books.start says so (format_upgrade) and puts it first among its next steps, in every session until it is done.
- Until then they work on their old format: everything that needs nothing new works as before, and whatever would need the new format is refused with format_upgrade_pending, changing nothing. Never retry it, work around it, or post it another way.
- Until then they can be read as ever, but nothing can be written to them: every write is one transaction that happens exactly once, and books an older version wrote can't keep that until they are upgraded. Every write is refused with format_upgrade_pending, changing nothing. Never retry it, work around it, or post it another way.
- An invoice's or bill's number, payment terms, seller and bill-to, references and memo, a line's account, quantity and unit price, the copy of an invoice kept exactly as it was issued, a party's email, default terms and contact details (phone, contact person, billing and shipping addresses, billing email), and the invoicing and bills settings all wait for the documents_v2 upgrade. A document that names none of them is written exactly as before and is never refused; the work that needs one waits, and the books say so.
- Only the owner can agree to the upgrade, with the owner passphrase: in the app, which asks each time it opens the books, or with `wanderbooks books upgrade ID` in a terminal. No tool can, and you never ask for, take or type the passphrase. Tell the human, in plain words: the books wait for their go-ahead, what was refused, and that saying no keeps the books working as they are.
- Only the owner can agree to the upgrade, with the owner passphrase: in the app, which asks each time it opens the books, or with `wanderbooks books upgrade ID` in a terminal. No tool can, and you never ask for, take or type the passphrase. Tell the human, in plain words: the books wait for their go-ahead, what was refused, and that until they give it the books can be read but not changed.
- Before it upgrades, the server makes a backup of the books, their vault and keys included, and proves it whole; a backup that can't be made or proven upgrades nothing. Then the books move to the new format in one step, on the record.
- After the upgrade an older version of wanderbooks can't open these books; the backup made first keeps them as they were. Going back is the owner's choice, never yours.
- This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, those writes are refused and everything else works as before.
- This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, every write is refused (the books can be read).
- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), and `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books.
- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when), and `call_transactions` (D-88: every write one transaction, with the request key each write carries, and the books' own unique id). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books.
+290
View File
@@ -0,0 +1,290 @@
//! Every write a tool makes is one transaction that happens once (plan
//! P15 2a, D-88, D-89): the request key, the repeat, and the frame around
//! a call. The journal's side is `ledger_store::calls`.
//!
//! ```text
//! GOAL: a write whose answer is lost and which is then retried happens
//! once; a call half done is never left looking done; a failed
//! write is on the record.
//! SOURCE: WB-format-8, WB-format-9, WB-format-10, WB-format-11;
//! plan/p15-app-and-relay.md 2a.
//! INVARIANTS:
//! 1. Every tool that can change anything (no readOnlyHint, but for
//! READS_THAT_SEAL, which write nothing and may answer with a TIN) takes a
//! required `request_key` in its schema; a call that writes without
//! one is refused in words, before it runs. A preview (a confirmed
//! tool called without confirmed: true) writes nothing and needs
//! none. The key is taken out of the arguments before the tool sees
//! them, so a tool's own checks and previews are unchanged.
//! 2. A write call runs alone among writes: they take turns, so a
//! call's lines are one run in the journal, and a repeat that
//! arrives while its original still runs waits for it, then gets its
//! answer.
//! 3. A repeat of a (token, key) whose call committed, with the same
//! tool and arguments, returns that call's answer as it was given and
//! writes nothing; with other arguments (or another tool) it is
//! refused as a misuse of the key. The access log records a repeat
//! as `repeat`.
//! 4. A call that answered ok commits with a closing line holding its
//! answer; one that answered with an error, was stopped by a close or
//! failed by any other means rolls back, is journaled as `failed`
//! when it had written lines, and leaves its key unused.
//! 5. Books that haven't declared call_transactions take no write: every
//! write call is refused with the upgrade remedy, before it runs.
//! Reads are never refused for it.
//! 6. No full TIN is kept in the journal (BS-partner-2): no answer holds
//! one (READS_THAT_SEAL, the three that can, are no transaction), and
//! an error text that holds one is kept masked.
//! SCENARIOS:
//! 1. IF a write is called again with the same key after its answer was
//! lost: SHOULD return the first answer, and the books hold one of
//! its effects.
//! 2. IF the same key comes with a different request: SHOULD refuse,
//! saying so and that nothing was changed.
//! 3. IF the process dies between the call's lines: SHOULD leave none
//! of them in the books (ledger_store::calls).
//! ```
use ledger_store::calls::{CallEnd, CallId, MAX_KEY_LEN, MIN_KEY_LEN};
use rmcp::model::{CallToolResponse, CallToolResult};
use serde_json::{Map, Value, json};
use super::BooksServer;
use crate::scopes::{Needs, TABLE};
/// The argument every write call carries.
pub const KEY_FIELD: &str = "request_key";
/// Why a write was refused before it ran, for its access record.
pub(crate) const MISSING_KEY: &str = "request_key_missing";
/// The key was used for another request.
pub(crate) const KEY_REUSED: &str = "request_key_reused";
/// The books are waiting for the owner's format upgrade (D-89).
pub(crate) const UPGRADE_PENDING: &str = "format_upgrade_pending";
/// The call repeated one that committed: its answer was returned.
pub(crate) const REPEAT: &str = "repeat";
/// The words that tell a model what the key is, whenever it is asked for.
const KEY_WORDS: &str = "request_key: any text you make up, 8 to 128 characters (a UUID is fine), new for each different action and never reused for another. If a call's answer is lost, send the same call again with the same key: the books will not do it twice, and will answer what they answered the first time";
/// The tools that are not read-only by their annotation but write nothing
/// to the books: they read what is sealed or put it into a file, and the
/// answer of each may hold a full TIN, which no journal line may (BS-partner-2).
/// They take no request key and are no transaction; they are read as any
/// read is (INVARIANT 1).
pub(crate) const READS_THAT_SEAL: [&str; 3] = [
"books.vendor_1099",
"books.get_w9",
"books.export_cpa_package",
];
/// The tools whose calls can write: no readOnlyHint (`next_steps::
/// mutating_tools`), except [`READS_THAT_SEAL`] (83 of the 86).
pub(crate) fn writes(tool: &str) -> bool {
super::next_steps::mutating_tools().contains(tool) && !READS_THAT_SEAL.contains(&tool)
}
/// Whether a call to `tool` with `args` writes: a write tool, except a
/// confirmed tool called as a preview (INVARIANT 1).
pub(crate) fn is_write_call(tool: &str, args: Option<&Map<String, Value>>) -> bool {
if !writes(tool) {
return false;
}
let previews = TABLE
.iter()
.any(|(n, needs)| *n == tool && *needs == Needs::PostWhenConfirmed);
!(previews
&& !args
.and_then(|a| a.get("confirmed"))
.and_then(Value::as_bool)
.unwrap_or(false))
}
/// Take the request key out of the arguments (INVARIANT 1).
pub(crate) fn take_key(args: &mut Option<Map<String, Value>>) -> Option<Value> {
args.as_mut().and_then(|a| a.remove(KEY_FIELD))
}
/// What is wrong with a call's key, in words; None when it will do.
pub(crate) fn key_problem(key: Option<&Value>) -> Option<String> {
match key {
None | Some(Value::Null) => Some(format!(
"this call changes the books and carries no request_key, so it was not run and nothing was changed. Send it again with a {KEY_WORDS}."
)),
Some(Value::String(k)) => {
let n = k.chars().count();
if k != k.trim() || k.chars().any(char::is_control) {
Some("the request_key has spaces at its ends or control characters in it, so the call was not run and nothing was changed. Send it again with a key of plain text".into())
} else if !(MIN_KEY_LEN..=MAX_KEY_LEN).contains(&n) {
Some(format!(
"the request_key is {n} characters; it must be {MIN_KEY_LEN} to {MAX_KEY_LEN}, so the call was not run and nothing was changed. Send it again with a {KEY_WORDS}."
))
} else {
None
}
}
Some(_) => Some(format!(
"the request_key must be text, so the call was not run and nothing was changed. Send it again with a {KEY_WORDS}."
)),
}
}
/// The key as text, once it has passed [`key_problem`].
pub(crate) fn key_text(key: &Value) -> String {
key.as_str().unwrap_or_default().to_string()
}
/// The tool list's schema for a write tool: `request_key` is a required
/// property (INVARIANT 1). A read-only tool's is left as it is.
pub(crate) fn add_key_to_schema(tool: &mut rmcp::model::Tool) {
if !writes(&tool.name) {
return;
}
let mut schema: Map<String, Value> = (*tool.input_schema).clone();
let props = schema
.entry("properties")
.or_insert_with(|| Value::Object(Map::new()));
if let Value::Object(props) = props {
props.insert(
KEY_FIELD.into(),
json!({
"type": "string",
"minLength": MIN_KEY_LEN,
"maxLength": MAX_KEY_LEN,
"description": KEY_WORDS,
}),
);
}
let required = schema
.entry("required")
.or_insert_with(|| Value::Array(Vec::new()));
if let Value::Array(required) = required
&& !required.iter().any(|r| r == KEY_FIELD)
{
required.push(json!(KEY_FIELD));
}
tool.input_schema = std::sync::Arc::new(schema);
}
/// What opening a call came to.
pub(crate) enum Begun {
/// The call is open: run the tool.
Run,
/// Not run: this is the answer, and the access record's code.
Answer(Box<CallToolResponse>, &'static str),
}
fn refusal(text: String) -> CallToolResponse {
CallToolResponse::Complete(CallToolResult::error(vec![
rmcp::model::ContentBlock::text(text),
]))
}
/// Open a call (INVARIANTS 3, 5): refuse it if the books take no calls;
/// answer it from the books if its key already committed; otherwise open
/// it. Takes the store's lock for the moment it needs; the caller holds
/// the write turn (`SharedStore::write_turn`).
pub(crate) fn begin(server: &BooksServer, id: CallId) -> Result<Begun, String> {
let mut store = server.lock()?;
if let Err(e) = store.ensure_takes_calls() {
return Ok(Begun::Answer(
Box::new(refusal(e.to_string())),
UPGRADE_PENDING,
));
}
if let Some(kept) = store.recorded_call(&id.token, &id.key) {
if kept.tool == id.tool && kept.args == id.args {
return match serde_json::from_str::<CallToolResult>(&kept.answer) {
Ok(answer) => Ok(Begun::Answer(
Box::new(CallToolResponse::Complete(answer)),
REPEAT,
)),
Err(e) => Err(format!(
"the answer kept for this request_key can't be read back: {e}"
)),
};
}
return Ok(Begun::Answer(
Box::new(refusal(format!(
"this request_key was already used for {} with other arguments, so the call was not run and nothing was changed. A key names one action: send this one again with a key of its own",
if kept.tool == id.tool {
"the same tool".to_string()
} else {
kept.tool.clone()
}
))),
KEY_REUSED,
));
}
store.begin_call(id).map_err(|e| e.to_string())?;
Ok(Begun::Run)
}
/// The text of the first text block, or "".
fn first_text(r: &CallToolResult) -> &str {
r.content
.iter()
.find_map(|c| match c {
rmcp::model::ContentBlock::Text(t) => Some(t.text.as_str()),
_ => None,
})
.unwrap_or("")
}
/// Whether a tool's final answer is one that committed: a result that is
/// not an error, and the call not stopped by a close (INVARIANT 4).
pub(crate) fn answered_ok(
out: &Result<CallToolResponse, rmcp::ErrorData>,
stopped_by_close: bool,
) -> bool {
!stopped_by_close
&& matches!(out, Ok(CallToolResponse::Complete(r)) if r.is_error != Some(true))
}
/// Close the open call with how it came out (INVARIANTS 4, 6). An error
/// here means the call could not be closed: the books server stops, and
/// the caller is told so.
pub(crate) fn close(
server: &BooksServer,
out: &Result<CallToolResponse, rmcp::ErrorData>,
ok: bool,
) -> Result<(), String> {
use ledger_core::parties::{has_full_tin, redact_full_tins};
let mut store = server.lock()?;
if !store.in_call() {
return Ok(());
}
let masked = |text: String| {
if has_full_tin(&text) {
redact_full_tins(&text).into_owned()
} else {
text
}
};
let ended = if ok {
let Ok(CallToolResponse::Complete(r)) = out else {
return Err("a call that committed has no answer".into());
};
// Kept as given: no tool's answer holds a full TIN (the three that
// can are no transaction), and a digest of the books' head can hold
// nine digits in a row, which masking would spoil on a repeat.
let text = serde_json::to_string(r).map_err(|e| e.to_string())?;
store.close_call(CallEnd::Done(&text))
} else {
let why = match out {
Ok(CallToolResponse::Complete(r)) => first_text(r).to_string(),
Ok(_) => "the call did not complete".to_string(),
Err(e) => e.message.to_string(),
};
let why = if why.is_empty() {
"the call failed".to_string()
} else {
why
};
store.close_call(CallEnd::Failed(&masked(why)))
};
ended.map_err(|e| e.to_string())
}
/// What a call is told when its closing line could not be written.
pub(crate) const NOT_CLOSED: &str = "this call could not be completed: its closing line could not be written, so none of it counts, and the books server stopped taking requests to protect the books. Ask the human to restart it, then send the call again with the same request_key";
+5 -1
View File
@@ -4769,8 +4769,12 @@ mod tests {
assert_eq!(added.len(), 1, "one line");
assert_eq!(added[0]["type"], "journal.format_set");
let c = ledger_store::format::current();
// The declaration also gives older books their id (plan P15 6a).
let mut declared = added[0]["payload"].clone();
let books_id = declared.as_object_mut().unwrap().remove("books_id");
assert_eq!(books_id.and_then(|v| v.as_str().map(str::len)), Some(32));
assert_eq!(
added[0]["payload"],
declared,
serde_json::json!({"format": c.format, "features": c.features})
);
assert_eq!(done.head.0, backup.head.0 + 1);
+98 -4
View File
@@ -222,6 +222,11 @@ pub struct SharedStore {
running: std::sync::atomic::AtomicUsize,
/// Woken whenever one ends.
ended: tokio::sync::Notify,
/// The write turn (calls.rs INVARIANT 2): held for a write call's
/// whole run, from its key being looked up to its closing line, and
/// for the owner's format upgrade, so a call's lines are one run in
/// the journal.
writes: tokio::sync::Mutex<()>,
/// The books' base currency, fixed at their creation: read without
/// the lock (the connect text names it).
currency: Currency,
@@ -240,6 +245,13 @@ impl SharedStore {
Ok(f(store))
}
/// Wait for the write turn (calls.rs INVARIANT 2). Blocking, on a
/// blocking thread, as the store's lock is; unlike it, the turn is
/// held across a call's awaits, so its guard is `Send`.
pub(crate) fn write_turn(&self) -> tokio::sync::MutexGuard<'_, ()> {
self.writes.blocking_lock()
}
/// Run `f` on the store under its lock, writing: the owner's format
/// upgrade, after its backup (backup.rs). Blocking. Refused once the
/// books are closing or the server stopped (INVARIANTS 2, 3), counted
@@ -257,6 +269,8 @@ impl SharedStore {
if self.closing() {
return Err("the books are closing".into());
}
// Not inside a tool's call: its lines are a run of their own.
let _turn = self.write_turn();
let mut store = self.store.blocking_lock();
if self.stopped() {
return Err(STOPPED.to_string());
@@ -318,6 +332,7 @@ impl SharedStore {
hurry: Arc::default(),
running: std::sync::atomic::AtomicUsize::new(0),
ended: tokio::sync::Notify::new(),
writes: tokio::sync::Mutex::new(()),
})
}
@@ -1514,6 +1529,8 @@ enum ShownDates {
mod access_tools;
#[path = "tools/backup.rs"]
mod backup_tools;
#[path = "calls.rs"]
mod calls;
#[path = "tools/files.rs"]
mod files;
#[path = "guards.rs"]
@@ -1783,11 +1800,17 @@ impl BooksServer {
impl ServerHandler for BooksServer {
async fn call_tool(
&self,
request: rmcp::model::CallToolRequestParams,
mut request: rmcp::model::CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
use crate::access::{self, Call};
use ledger_store::access::Outcome;
// The request key is the call's own, not the tool's: out of the
// arguments here, so no tool, preview digest or record sees it as
// an argument (calls.rs INVARIANT 1). A call writes when its tool
// can change the books and it is not a preview.
let request_key = calls::take_key(&mut request.arguments);
let writing = calls::is_write_call(&request.name, request.arguments.as_ref());
let mut call = Call::new(&self.access, &self.board, &context, "tool", &request.name);
let outcome_of = |out: &Result<rmcp::model::CallToolResponse, rmcp::ErrorData>| match out {
Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => {
@@ -1861,7 +1884,16 @@ impl ServerHandler for BooksServer {
Err(rmcp::ErrorData::invalid_params(why, None)),
)
}),
};
}
// A write without a usable request key isn't run (calls.rs
// INVARIANT 1).
.or_else(|| {
if !writing {
return None;
}
calls::key_problem(request_key.as_ref())
.map(|why| (calls::MISSING_KEY, Ok(tool_error(why))))
});
if let Some((code, answer)) = refusal {
call.digested(refused_digest(request.arguments.clone()).await);
return self.refuse(&call, code, answer).await;
@@ -1900,6 +1932,46 @@ impl ServerHandler for BooksServer {
});
// Counted as running by now (run_blocking): hashed here.
let digest = Call::digest_of(request.arguments.as_ref());
// A write call is one transaction (calls.rs): it takes its
// turn among writes, and is opened, or answered from its
// key, before the tool runs.
let call_id =
request_key
.as_ref()
.filter(|_| writing)
.map(|k| ledger_store::calls::CallId {
token: running_call
.caller()
.map(|c| c.token.id.clone())
.unwrap_or_default(),
tool: tool_name.clone(),
key: calls::key_text(k),
args: digest.clone().unwrap_or_default(),
});
let _turn = call_id.as_ref().map(|_| server.store.write_turn());
let early = match &call_id {
None => None,
Some(id) => match calls::begin(&server, id.clone()) {
Ok(calls::Begun::Run) => None,
Ok(calls::Begun::Answer(answer, code)) => Some((answer, code)),
Err(why) => Some((Box::new(tool_error(why)), access::STOPPED)),
},
};
if let Some((answer, code)) = early {
// Not run: refused (with the guards a refusal carries),
// or answered again from the books as it was first
// answered.
let answer = if code == calls::REPEAT {
Ok(*answer)
} else {
next_steps::apply(&server, &tool_name, envelope_args.as_ref(), Ok(*answer))
};
YOU.with(|y| y.borrow_mut().take());
let mut c = running_call;
c.digested(digest);
let recorded = c.record_blocking(Outcome::Refused(code.into()), None);
return (answer, recorded);
}
let tcc =
rmcp::handler::server::tool::ToolCallContext::new(&server, request, context);
let router = Self::tool_router();
@@ -1927,7 +1999,26 @@ impl ServerHandler for BooksServer {
}
};
// The result envelope (next_steps.rs INVARIANT 1).
let out = next_steps::apply(&server, &tool_name, envelope_args.as_ref(), out);
let mut out = next_steps::apply(&server, &tool_name, envelope_args.as_ref(), out);
let stopped = STOPPED_BY_CLOSE.with(|s| s.replace(false));
// The call is over: its closing line, holding the answer
// the caller is given, commits it (or, for a call that
// failed or was stopped, rolls it back). Only then does it
// count as done (calls.rs INVARIANT 4).
let mut wrote = wrote;
if call_id.is_some() {
let ok = calls::answered_ok(&out, stopped);
if let Err(why) = calls::close(&server, &out, ok) {
eprintln!("wanderbooks: a call could not be closed: {why}");
server.store.stop();
out = Ok(tool_error(calls::NOT_CLOSED.to_string()));
}
// The closing line is this call's last write.
wrote = WROTE
.with(|w| w.borrow_mut().take())
.map(|(seq, hash)| ledger_store::chain::Head { seq, hash })
.or(wrote);
}
// Who asked is the request's alone: a later request on this
// thread (a resource read) must not see it.
YOU.with(|y| y.borrow_mut().take());
@@ -1936,7 +2027,7 @@ impl ServerHandler for BooksServer {
c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take()));
// A call a close stopped is on record as stopped, not as an
// answer it gave (local.rs INVARIANT 10).
let outcome = if STOPPED_BY_CLOSE.with(|s| s.replace(false)) {
let outcome = if stopped {
Outcome::Refused(access::STOPPED_BY_CLOSE.into())
} else {
outcome_of(&out)
@@ -1977,6 +2068,9 @@ impl ServerHandler for BooksServer {
context: RequestContext<RoleServer>,
) -> Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
let mut tools = Self::tool_router().list_all();
// Every tool that can change the books takes a request key
// (calls.rs INVARIANT 1).
tools.iter_mut().for_each(calls::add_key_to_schema);
// A token is shown what it can call (scopes.rs); the list then
// differs by caller, so it may be cached only for this one.
let scopes = crate::access::caller(&context)
+7
View File
@@ -6565,6 +6565,13 @@ impl Store {
crate::cancel::check()?;
replay_line_into_ledger(&mut self.ledger, &lines[i], self.base_currency)?;
}
// A call open now (the verification that heals is itself a call)
// keeps its projection transaction, on the new connection
// (calls.rs). It has written no line a rebuild would lose: it
// reads and rebuilds, nothing more.
if self.call.is_some() {
self.conn.execute_batch("SAVEPOINT call_tx")?;
}
Ok(())
}
+19 -1
View File
@@ -154,8 +154,10 @@ fn a_failed_call_is_on_the_record_and_builds_nothing() {
s.verify().unwrap();
}
type Step = Box<dyn Fn(&mut Store)>;
/// A call of every kind of step, by how far it got.
fn steps() -> Vec<Box<dyn Fn(&mut Store)>> {
fn steps() -> Vec<Step> {
vec![
Box::new(|s| {
s.create_entry(d(2026, 1, 5), "One").unwrap();
@@ -414,3 +416,19 @@ fn a_call_cannot_begin_inside_another_or_after_a_failed_close() {
Err(StoreError::CallRefused(_))
));
}
#[test]
fn a_call_that_rebuilds_the_projection_still_commits() {
// books.verify heals a drifted projection by rebuilding it, and is a
// call like any other: its transaction moves to the new database.
let tmp = tempfile::tempdir().unwrap();
let mut s = books(tmp.path());
s.begin_call(id("key-heal-0001")).unwrap();
s.rebuild().unwrap();
s.close_call(CallEnd::Done("{}")).unwrap();
s.verify().unwrap();
assert!(s.recorded_call("token-1", "key-heal-0001").is_some());
drop(s);
let s = Store::open(tmp.path()).unwrap();
s.verify().unwrap();
}
+28
View File
@@ -611,6 +611,34 @@ with generated URIs, checks after each call that the server still
serves, restarts it after them to check the books reopen, and drives
every tool over every book in ledger-store's `tests/fixtures/old-books`.
## Writes: one transaction, one request key (plan P15 2a, D-88)
Every tool that can change the books (no `readOnlyHint`; 83 of the 140: the
three that read what is sealed and put it in a file, `books.vendor_1099`,
`books.get_w9` and `books.export_cpa_package`, are annotated so but write
nothing and may answer with a full TIN, so they are read like any read)
takes one more argument than its own, `request_key`, and its schema says it
is required: 8 to 128 characters of plain text the agent makes up, new for
each different action and never reused for another. The agent sends the same
call again with the same key when its answer is lost; the books do not do it
twice, and answer what they answered the first time (a repeat is recorded in
the access log as `repeat`, and writes nothing, even after the books were
closed and opened). The same key with other arguments, or another tool, is
refused in words and changes nothing. A key is the token's own. A write
without a usable key is refused in words before it runs. A preview (a tool
with `confirmed`, called without `confirmed: true`) writes nothing and needs
no key. A failed write changes nothing and leaves its key free: the corrected
call may use it; where the call got as far as writing journal lines, the
journal says it failed (`call.closed`, outcome `failed`) and none of them
count. Every write call is one transaction: its lines commit together with
its closing line or not at all, and after a crash a call without its closing
line is not treated as done (WB-format-8 to WB-format-10).
Books an older version wrote take no write at all until the owner gives the
format upgrade its go-ahead (D-89, WB-format-11): every write is refused,
before it runs, with `format_upgrade_pending` and the words "nothing can be
written"; every read works as ever. No tool can give the go-ahead.
## Tool design principles
- **Narrow tools, explicit arguments.** No "do what I mean" tools. The agent
+8
View File
@@ -256,3 +256,11 @@ Three new rows, none above changed status, and the floor stands.
| Books home: a visible folder per book, `<Documents>/Wanderbooks/<id>`, holding `AGENTS.md`, `CLAUDE.md`, `.mcp.json` and `.claude/settings.json` and nothing of the books | A QBO/Xero company has no counterpart; the point is the agent's workplace (D-27) | partial | `books_home_holds_no_books_data`, `a_books_home_made_again_keeps_what_a_person_kept` (`crates/ledger-host/tests/books_home.rs`); `partial` until the macOS home is tried |
| Agent dock: Claude Code or Codex in a terminal along the bottom of the viewer, started in the books home; never required | QBO's assistant panel is a cross-check only | partial | `dock_runs_the_chosen_agent`, `agent_missing_offers_the_installer` (`crates/ledger-gui/tests/dock.rs`); Linux checked; macOS by the CI run; Windows not offered (ConPTY unchecked) |
| First run with no terminal: the viewer sets up the private folder, the owner passphrase, the first books and an agent | QBO's "set up your company" flow | partial | `first_run_onboards_with_no_terminal` (`crates/ledger-gui/tests/welcome.rs`); the AppImage's whole path is the EM's to try on a clean machine |
## P15 T1: every write is one transaction, exactly once (2026-11-21, D-88, D-89)
| Area | Counterpart (a cross-check, not the spec) | Status | Notes |
|---|---|---|---|
| A tool call's lines commit together with a closing line or not at all; a call that never closed, or failed, builds nothing in any replay; a failed call is on the record | A database transaction; QBO and Xero make a write all or nothing and say so on failure | partial | WB-format-8, WB-format-10; `ledger-store` `tests/calls.rs` (`a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_failed_call_is_on_the_record_and_builds_nothing`); partial until the Lean law is in bookspec and a `done` needs a golden |
| Every write carries a request key; a repeat returns the first answer and writes nothing, across a restart; the same key for another request is refused | An idempotency key (a payments API's `Idempotency-Key`); QBO's `requestid` | partial | WB-format-9; `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `books.import_bank_csv` is one transaction (`the_import_is_one_transaction`) |
| Books that haven't declared the feature take no write and still read; every set of books has a unique id | No counterpart; the owner's rule (D-89) | partial | WB-format-11, WB-format-12; `ledger-store` `tests/calls.rs` (`books_that_have_not_declared_the_feature_take_no_call_and_still_read`, `new_books_are_born_with_an_id_and_no_two_share_one`); `ledger-cli` `tests/format_upgrade.rs` (`books_p2_served_cut_over_whole`) |
+5 -2
View File
@@ -258,7 +258,9 @@ restart).
**WB-format-9 Every write call carries a request key, and a repeat of it
writes nothing.** Every tool that can change the books (no `readOnlyHint`;
86 of the 140) takes a required `request_key`, 8 to 128 characters of plain
83 of the 140: the three that only read what is sealed, `books.vendor_1099`,
`books.get_w9` and `books.export_cpa_package`, write nothing and may answer with
a full TIN, so they are reads) takes a required `request_key`, 8 to 128 characters of plain
text, which the agent makes up, new for each action. A write without a usable
key is refused in words before it runs; a preview (a confirmed tool called
without `confirmed: true`) writes nothing and needs none. The key is taken out
@@ -270,7 +272,8 @@ misuse of the key, and nothing is changed. A key is the token's own: two
tokens with one key are two keys. The key table is rebuilt at every open from
the `ok` closing lines alone. A repeat that arrives while its original is
still running waits for it (calls take turns) and gets its answer. An answer
that holds a full TIN is kept masked, so its repeat returns it masked
is kept as given: no tool answer holds a full TIN, and the three tools that
can are no transaction; an error text that holds one is kept masked
(BS-partner-2: no journal line holds one).
*Enforced:* ledger-mcp `calls::is_write_call`, `calls::key_problem`, `calls::begin`, `calls::close`, `calls::add_key_to_schema`, `Store::recorded_call`, `Keys`.
*Checked:* `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `a_write_without_a_usable_key_is_not_run`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`).