From 8d2187bae78594a19b21996f5dfb25d3862550ef Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 11:03:23 -0700 Subject: [PATCH 01/11] refactor(gui): remove "Close the books": the app is the host and a company's tab closes the company The menu item asked a host's lease socket, which the app does not have, and under the app could only answer "the app has these books open". Closing a company's tab closes that company in the app's server (WB-app-2) and closing the window closes them all (WB-app-4), so the item had no job left. The Owner trait loses close_books; the test owners lose their copies. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 4 --- crates/ledger-gui/src/owner.rs | 42 ++++------------------- crates/ledger-gui/tests/assistants.rs | 3 -- crates/ledger-gui/tests/dock.rs | 3 -- crates/ledger-gui/tests/format_upgrade.rs | 3 -- crates/ledger-gui/tests/owner_menu.rs | 23 +++---------- crates/ledger-gui/tests/serving.rs | 6 ---- crates/ledger-gui/tests/sidenav.rs | 3 -- crates/ledger-gui/tests/tabs.rs | 7 ---- crates/ledger-gui/tests/update_notice.rs | 3 -- crates/ledger-gui/tests/welcome.rs | 3 -- 11 files changed, 10 insertions(+), 90 deletions(-) diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 3a6bfb9e..ad72abe7 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -170,10 +170,6 @@ impl ledger_gui::owner::Owner for ViewerOwner { ) } - fn close_books(&self) -> Result { - ledger_host::commands::close_books(&self.common) - } - fn new_books(&self, id: &str, currency: &str) -> Result { ledger_host::commands::new_books_and_home(&self.common, id, currency) } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index 64d4b096..db1f41de 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -1,14 +1,16 @@ //! The viewer's Books menu (plan P2 "Viewer menu", D-19, D-32): the //! owner's own actions on the books, handed to the books server (back up -//! now, restore, new books, close the books, the format upgrade) or to the +//! now, restore, new books, the format upgrade) or to the //! owner's agent (connect). The viewer itself still never writes the //! books. //! //! ```text -//! GOAL: the owner backs up, restores, starts new books, closes the books -//! and connects an agent from the viewer, without a terminal. +//! GOAL: the owner backs up, restores, starts new books and connects an +//! agent from the viewer, without a terminal. (There is no "Close the +//! books": the app is the host, and a company's tab, or the window, +//! closes it: WB-app-2, WB-app-4.) //! SOURCE: plan P2 ("Viewer menu (D-19)": "Back up now", "Restore…", -//! "New books…", "Close the books" and "Connect an assistant…"; the +//! "New books…" and "Connect an assistant…"; the //! page it opens carries the two connect buttons; "Nothing in the viewer writes a book"); D-32 //! (no confinement: the viewer asks the server itself, as the //! command line does); plan 3.9 and D-39 (the format upgrade: the @@ -286,8 +288,6 @@ pub trait Owner: Send + Sync { fn make_key(&self, _book: &str) -> Result { Err("not here".into()) } - /// Close the books: everything holding them lets go. - fn close_books(&self) -> Result; /// New, empty books `id` in `currency`. fn new_books(&self, id: &str, currency: &str) -> Result; /// Back the books `book` up now. @@ -410,8 +410,6 @@ enum Dialog { NewBooks { id: String, currency: String }, /// "Restore…": the backup, then its preview. Restore(Box), - /// "Close the books": asked first. - Close, /// The format upgrade: the go-ahead, with the owner passphrase. Upgrade(Box), } @@ -760,14 +758,6 @@ impl OwnerMenu { Box::new(move || o.apply_update()), )); } - ui.separator(); - if ui - .button(format!("{} Close the books", icon::POWER)) - .on_hover_text("Close the books now: assistants' sessions and every other holder let go") - .clicked() - { - self.dialog = Dialog::Close; - } }) }) .inner; @@ -854,26 +844,6 @@ impl OwnerMenu { ); } } - Dialog::Close => { - egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-close")).show(ctx, |ui| { - ui.heading("Close the books?"); - ui.label("Assistants' sessions and everything else holding them let go. They open again when something holds them."); - ui.horizontal(|ui| { - if ui.button("Close the books").clicked() { - let o = owner.clone(); - run = Some(( - "Close the books".into(), - Effect::Changes("Closing the books"), - Box::new(move || o.close_books().map(|l| vec![l])), - )); - close = true; - } - if ui.button("Cancel").clicked() { - close = true; - } - }); - }); - } Dialog::NewBooks { id, currency } => { egui::Modal::new(self.scope.unwrap_or(egui::Id::NULL).with("owner-new-books")) .show(ctx, |ui| { diff --git a/crates/ledger-gui/tests/assistants.rs b/crates/ledger-gui/tests/assistants.rs index 28ba5ceb..6e1659a9 100644 --- a/crates/ledger-gui/tests/assistants.rs +++ b/crates/ledger-gui/tests/assistants.rs @@ -207,9 +207,6 @@ impl Owner for Fake { self.note(format!("connect {} {book}", agent.key())); Ok(vec![format!("{} reaches the books.", agent.label())]) } - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/dock.rs b/crates/ledger-gui/tests/dock.rs index 067ed350..c9b7f842 100644 --- a/crates/ledger-gui/tests/dock.rs +++ b/crates/ledger-gui/tests/dock.rs @@ -28,9 +28,6 @@ struct Fake { } impl Owner for Fake { - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/format_upgrade.rs b/crates/ledger-gui/tests/format_upgrade.rs index 2ed43663..5d8738f0 100644 --- a/crates/ledger-gui/tests/format_upgrade.rs +++ b/crates/ledger-gui/tests/format_upgrade.rs @@ -80,9 +80,6 @@ struct Fake { } impl Owner for Fake { - fn close_books(&self) -> Result { - Err("not in these tests".into()) - } fn new_books(&self, _id: &str, _currency: &str) -> Result { Err("not in these tests".into()) } diff --git a/crates/ledger-gui/tests/owner_menu.rs b/crates/ledger-gui/tests/owner_menu.rs index cbd2ab1f..ad83141e 100644 --- a/crates/ledger-gui/tests/owner_menu.rs +++ b/crates/ledger-gui/tests/owner_menu.rs @@ -33,10 +33,6 @@ impl Fake { } impl Owner for Fake { - fn close_books(&self) -> Result { - self.said("close".into()); - Ok("The books are closing.".into()) - } fn new_books(&self, id: &str, currency: &str) -> Result { self.said(format!("new {id} {currency}")); Ok(format!("Made new books \"{id}\" ({currency}).")) @@ -247,19 +243,11 @@ fn the_books_menu_hands_each_action_to_the_owner_and_writes_nothing() { "restore /media/disk/acme.git acme 7" ); - // Close the books: asked first; cancelled, nothing; then done. + // There is no "Close the books": a company's tab, or the window, closes + // the books (WB-app-2, WB-app-4). open_menu(&mut h); - h.get_by_label_contains("Close the books").click(); - h.run_steps(3); - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert_eq!(f.asked.lock().unwrap().len(), start + 4); - open_menu(&mut h); - h.get_by_label_contains("Close the books").click(); - h.run_steps(3); - h.get_by_label("Close the books").click(); - settle(&mut h, &f, start + 5); - assert_eq!(f.asked.lock().unwrap()[start + 4], "close"); + assert!(h.query_by_label_contains("Close the books").is_none()); + h.run_steps(2); // The viewer wrote nothing of the books. drop(h); @@ -409,7 +397,4 @@ fn screenshots() { settle(&mut h, &f, n + 1); shot(&mut h, "restore-plan"); h.get_by_label("Cancel").click(); - open_menu(&mut h); - h.get_by_label_contains("Close the books").click(); - shot(&mut h, "close"); } diff --git a/crates/ledger-gui/tests/serving.rs b/crates/ledger-gui/tests/serving.rs index 6c5b7da5..00762696 100644 --- a/crates/ledger-gui/tests/serving.rs +++ b/crates/ledger-gui/tests/serving.rs @@ -173,9 +173,6 @@ impl Owner for Fake { fn serve_exited(&self) -> Option { self.exited.lock().unwrap().clone() } - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } @@ -461,9 +458,6 @@ fn a_window_with_no_server_asks_nothing_of_any() { // An owner that does not host a server: the default. struct Plain; impl Owner for Plain { - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/sidenav.rs b/crates/ledger-gui/tests/sidenav.rs index 2df51108..4c78b799 100644 --- a/crates/ledger-gui/tests/sidenav.rs +++ b/crates/ledger-gui/tests/sidenav.rs @@ -36,9 +36,6 @@ use std::sync::{Arc, OnceLock}; struct Quiet; impl Owner for Quiet { - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index af260588..515176a8 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -578,9 +578,6 @@ struct Agentic { } impl Owner for Agentic { - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } @@ -2095,10 +2092,6 @@ impl Gated { } impl Owner for Gated { - fn close_books(&self) -> Result { - self.block(); - Ok("The books are closing.".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not here".into()) } diff --git a/crates/ledger-gui/tests/update_notice.rs b/crates/ledger-gui/tests/update_notice.rs index 94a691a5..91d3be45 100644 --- a/crates/ledger-gui/tests/update_notice.rs +++ b/crates/ledger-gui/tests/update_notice.rs @@ -33,9 +33,6 @@ impl Fake { } impl Owner for Fake { - fn close_books(&self) -> Result { - Err("not in these tests".into()) - } fn new_books(&self, _: &str, _: &str) -> Result { Err("not in these tests".into()) } diff --git a/crates/ledger-gui/tests/welcome.rs b/crates/ledger-gui/tests/welcome.rs index 05fdb0c1..b8fcc736 100644 --- a/crates/ledger-gui/tests/welcome.rs +++ b/crates/ledger-gui/tests/welcome.rs @@ -35,9 +35,6 @@ impl Fake { } impl Owner for Fake { - fn close_books(&self) -> Result { - Err("not here".into()) - } fn new_books(&self, id: &str, currency: &str) -> Result { self.said(format!("new {id} {currency}")); let (_, root) = self.root_path(); From 22f447c0ba3b471748aa509cdc27f07e1e86a6b6 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 11:03:23 -0700 Subject: [PATCH 02/11] feat(host): nothing starts a detached host but `wanderbooks serve` Plan P15 3.1: the desktop app is the host. The bridge and every command that needs the books now find what runs (a host held by serve, the app's server, or nothing) and never start a host. The permanent run/app-hosted marker is gone: a root is the app's only while a server runs on it with no host. - opener: no host and no server is HoldError::NotRunning for every holder but serve; a server holding run/server.lock with no admin socket yet is waited for, in words (an opening or finishing server); the admin socket answering is the leaseless hold on the app's server, marker or none. - commands: with nothing running, a command that manages the books' files or reads (list, create, adopt, restore, back-up, upgrade, token, connect) runs a server of its own, the one the app starts, for the length of the work and closes it, taking the same server.lock and books.lock; a command that needs an open company held by Wanderbooks (books open/close, upload, download) says "Start Wanderbooks first". The format upgrade goes to the server as an admin request when no host is there. doctor and close say what runs. hold_for_viewer and close_books are removed. - bridge: the line to the app is the default with no host; a bridge whose host went away becomes it. The words an assistant gets name both ways to start the books (the app, or wanderbooks serve). - app server: the child is its own process group on Unix (a terminal Ctrl+C reaches the window alone) and breaks away from a launcher's job on Windows (a kill-on-close job no longer kills it mid-backup); a stale marker from an earlier build is removed. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/app_server.rs | 69 +++- crates/ledger-host/src/app_server.rs | 125 ++++--- crates/ledger-host/src/bridge.rs | 81 +++-- crates/ledger-host/src/commands.rs | 470 ++++++++++++++++---------- crates/ledger-host/src/opener.rs | 113 +++++-- 5 files changed, 573 insertions(+), 285 deletions(-) diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs index 54f2e796..15a08103 100644 --- a/crates/ledger-cli/tests/app_server.rs +++ b/crates/ledger-cli/tests/app_server.rs @@ -28,7 +28,7 @@ //! leaves it alone: nothing is signalled. //! 6. A tab's company is opened and closed in the server by request; a //! company closed is not reachable, one opened is. -//! 7. The bridge, for a root the app has served and with no host: +//! 7. The bridge, with no host (and no mark of any kind on the root): //! "Wanderbooks isn't running" with the app not running, "Company X //! isn't open" with it running and the company not, and neither once //! both are so, in a session that was already running; it starts no @@ -49,9 +49,7 @@ mod common; use common::{BOOK, Home, Server, clean_env}; -use ledger_host::app_server::{ - ANOTHER_HAS_THEM, APP_MARKER, AppHost, AppServer, Stopped, app_hosted, -}; +use ledger_host::app_server::{ANOTHER_HAS_THEM, AppHost, AppServer, RETIRED_MARKER, Stopped}; use ledger_host::opener::{host_lock_held, server_lock_held}; use ledger_mcp::admin::{Request, Response}; use serde_json::{Value, json}; @@ -98,7 +96,10 @@ fn the_server_is_a_child_that_closes_when_its_input_does() { let run = home.run(); let server = start(&home, &[]); server.wait_ready(Duration::from_secs(60)).unwrap(); - assert!(app_hosted(&run), "the root is the app's from now on"); + assert!( + !run.join(RETIRED_MARKER).exists(), + "nothing marks the root as the app's" + ); assert!(server_lock_held(&run), "it holds the server lock"); assert!(!host_lock_held(&run), "no host was started beside it"); assert!( @@ -123,6 +124,49 @@ fn the_server_is_a_child_that_closes_when_its_input_does() { ); } +/// A mark an earlier build left (`run/app-hosted`) means nothing now: the +/// root works as one without it, and the next start of the app's server +/// removes it (app_server.rs INVARIANT 7). +#[test] +fn a_mark_an_earlier_build_left_is_ignored_and_removed() { + let home = Home::new("app-old-mark"); + let run = home.run(); + std::fs::write(run.join(RETIRED_MARKER), b"").unwrap(); + // Nothing runs: the bridge says so in words, mark or none. + let mut bridge = Bridge::start(&home); + assert!(error_of(&bridge.initialize()).starts_with("Wanderbooks isn't running")); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + assert!( + !run.join(RETIRED_MARKER).exists(), + "the old mark is removed" + ); + assert!(matches!(home.admin(Request::List), Response::Books(_))); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); +} + +/// The server is in a process group of its own, so a Ctrl+C at the +/// terminal the window was started from (sent to the terminal's +/// foreground group, the window's) never reaches it: it closes by its +/// input alone (app_server.rs INVARIANT 3). +#[cfg(unix)] +#[test] +fn the_server_has_a_process_group_of_its_own_so_a_terminal_ctrl_c_misses_it() { + let home = Home::new("app-group"); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + let pid = server.pid() as libc::pid_t; + // SAFETY: getpgid and getpgrp only read process-group ids. + let (its, ours) = unsafe { (libc::getpgid(pid), libc::getpgrp()) }; + assert_eq!(its, pid, "it leads a group of its own"); + assert_ne!(its, ours, "it is not in the window's group"); + // The group the terminal signals is the window's: a SIGINT sent to + // every process of that group but ours cannot be shown here, so the + // property is what makes it hold: nothing of the server is in it. + assert_eq!(server.exited(), None); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); +} + #[test] fn opening_and_closing_a_company_drives_the_servers_book() { let home = Home::new("app-tabs"); @@ -162,7 +206,10 @@ fn a_start_is_refused_when_another_program_has_the_books() { let other = Server::start_with(&home, &["--open", "none"]); let refused = try_start().err().expect("refused"); assert_eq!(refused, ANOTHER_HAS_THEM); - assert!(!run.join(APP_MARKER).exists(), "a refusal touches nothing"); + assert!( + !run.join(RETIRED_MARKER).exists(), + "a refusal touches nothing" + ); other.close(); until("the other let go", || !server_lock_held(&run)); // A host holds them. @@ -174,7 +221,7 @@ fn a_start_is_refused_when_another_program_has_the_books() { .unwrap(); lock.lock().unwrap(); assert_eq!(try_start().err().expect("refused"), ANOTHER_HAS_THEM); - assert!(!run.join(APP_MARKER).exists()); + assert!(!run.join(RETIRED_MARKER).exists()); drop(lock); // Held by nobody: it starts. let server = try_start().expect("started"); @@ -399,10 +446,12 @@ fn error_of(answer: &Value) -> String { fn the_bridge_says_the_app_isnt_running_then_works_once_it_is() { let home = Home::new("app-bridge"); let run = home.run(); - // The app has served this root (it wrote its mark), and isn't running. - std::fs::write(run.join(APP_MARKER), b"").unwrap(); + // The app isn't running, and no host is: a root that was never the + // app's, so nothing marks it. let mut bridge = Bridge::start(&home); - let not_running = format!("Wanderbooks isn't running: start Wanderbooks and open {BOOK}."); + let not_running = format!( + "Wanderbooks isn't running: start Wanderbooks and open {BOOK} (on a computer with no screen, run `wanderbooks serve`), then try again." + ); assert_eq!(error_of(&bridge.initialize()), not_running); assert_eq!(error_of(&bridge.start_call()), not_running); // No host was started for it. diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index 91b30fd8..dee59f23 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -41,11 +41,16 @@ //! request, waiting for the server to be ready first; a close that //! says its last backup was not whole is returned as a notice, never //! as a plain success. -//! 7. Starting writes `run/app-hosted`, a file with nothing in it: the -//! root is this app's from then on, and the agents' bridge says -//! "Wanderbooks isn't running" for it, instead of starting a host -//! (bridge.rs INVARIANT 12). The marker is never removed: a root the -//! app has served is the app's for good. +//! 7. Nothing marks a root as the app's. Whether the app (or another +//! server) has a root is read from what is running: no host holds +//! `run/host.lock`, a server holds `run/server.lock`, and its admin +//! socket answers ([`the_apps_server_runs`]). An earlier build wrote +//! a permanent file `run/app-hosted`; it means nothing now and is +//! removed at the next start of the app's server ([`RETIRED_MARKER`]). +//! With the app closed, the agents' bridge says "Wanderbooks isn't +//! running" (bridge.rs INVARIANT 12) whether or not the root was ever +//! the app's, and no program starts a host: only `wanderbooks serve` +//! does. //! 8. A server the window started is either managed by the window or //! stopped, never neither ([`AppHost`]): one that is alive and not //! yet ready is waited for, not given up on; a start that fails, or @@ -72,7 +77,7 @@ //! holds a token's text. //! ``` -use crate::host::{SERVER_LOG, children_executable, open_log, private_options}; +use crate::host::{SERVER_LOG, children_executable, open_log}; use crate::opener::{host_lock_held, server_lock_held}; use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response}; use ledger_store::root::Root; @@ -82,9 +87,10 @@ use std::process::{Command, Stdio}; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant}; -/// The file in `run/` that says the root is the desktop app's -/// (INVARIANT 7). -pub const APP_MARKER: &str = "app-hosted"; +/// The file an earlier build left in `run/` to say the root was the +/// desktop app's. Nothing reads it any more (INVARIANT 7); it is removed +/// when the app's server starts. +pub const RETIRED_MARKER: &str = "app-hosted"; /// How long a server may take to say it is ready: it opens and verifies /// every company it was told to, and a large one rebuilding a drifted @@ -131,6 +137,50 @@ impl Shared { } } +/// Windows: no console window of its own (CREATE_NO_WINDOW), so the +/// window's own Ctrl+C never reaches the server: it closes by its input +/// alone. +#[cfg(windows)] +const NO_WINDOW: u32 = 0x0800_0000; +/// Windows: leave the job the window runs in (CREATE_BREAKAWAY_FROM_JOB). +/// A launcher that puts the window in a job that kills everything in it +/// when the window dies would otherwise kill the server too, in the +/// middle of a backup, where the window's death is meant to reach it as +/// the end of its input and nothing more (INVARIANT 3). The server does +/// not outlive the window by it: it closes when its input does. +#[cfg(windows)] +const BREAKAWAY: u32 = 0x0100_0000; + +/// Spawn the server with its input and output piped and its errors to +/// `log`. Windows: breaking away from the window's job, and without that +/// if the job does not let a process leave it. +fn spawn_child(command: &mut Command, log: &std::fs::File) -> Result { + let again = |e: std::io::Error| format!("can't start the books server: {e}"); + let go = |command: &mut Command| -> Result { + command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(log.try_clone()?) + .spawn() + }; + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(NO_WINDOW | BREAKAWAY); + match go(command) { + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => { + command.creation_flags(NO_WINDOW); + go(command).map_err(again) + } + other => other.map_err(again), + } + } + #[cfg(not(windows))] + { + go(command).map_err(again) + } +} + /// What [`AppServer::stop`] came to. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Stopped { @@ -163,16 +213,11 @@ pub struct AppServer { pid: u32, } -/// Whether the root whose `run/` folder this is belongs to the desktop -/// app (INVARIANT 7). -pub fn app_hosted(run: &Path) -> bool { - run.join(APP_MARKER).is_file() -} - -/// Whether a books server runs for the app now: the root is the app's, -/// no host holds it, and a server does. +/// Whether a server runs for the app (or any program that is not a host) +/// now: no host holds the root, a server does, and its admin socket +/// answers (INVARIANT 7). pub fn the_apps_server_runs(run: &Path) -> bool { - app_hosted(run) && !host_lock_held(run) && server_lock_held(run) + !host_lock_held(run) && server_lock_held(run) && crate::opener::admin_answers(run) == Ok(true) } impl AppServer { @@ -197,12 +242,8 @@ impl AppServer { if host_lock_held(&run) || server_lock_held(&run) { return Err(ANOTHER_HAS_THEM.into()); } - private_options() - .create(true) - .truncate(false) - .write(true) - .open(run.join(APP_MARKER)) - .map_err(|e| format!("can't mark these books as the app's: {}", e.kind()))?; + // The mark an earlier build left means nothing now (INVARIANT 7). + let _ = std::fs::remove_file(run.join(RETIRED_MARKER)); let log = open_log(&run.join(SERVER_LOG)) .map_err(|e| format!("can't open the server's log: {}", e.kind()))?; let mut command = Command::new(exe); @@ -210,27 +251,20 @@ impl AppServer { { use std::os::unix::process::CommandExt; command.arg0("wanderbooks"); + // A group of its own: a Ctrl+C at the terminal the window was + // started from goes to the terminal's foreground group, the + // window's, and never to the server, which would close the + // books under an open window. The server closes by its input + // alone (INVARIANT 3), and a window that dies closes that. + command.process_group(0); } command.arg("server"); if let Some(root) = root { command.arg("--root").arg(root); } command.arg("--open").arg(open_argument(open)); - #[cfg(windows)] - { - use std::os::windows::process::CommandExt; - // CREATE_NO_WINDOW: a console of its own that nobody sees, so - // the window's own Ctrl+C never reaches it (it closes by its - // input alone). - command.creation_flags(0x0800_0000); - } configure(&mut command); - let mut child = command - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(log) - .spawn() - .map_err(|e| format!("can't start the books server: {e}"))?; + let mut child = spawn_child(&mut command, &log)?; let stdin = child.stdin.take(); let stdout = child.stdout.take(); let pid = child.id(); @@ -350,6 +384,13 @@ impl AppServer { } } + /// One admin request, once the server is ready (a command's own + /// server: commands.rs `Reached`): its answer, or why not in words. + pub fn call(&self, request: Request, wait: Option) -> Result { + self.wait_ready(READY_WAIT)?; + self.ask(request, wait) + } + /// Open the company `id` in the server, so assistants can reach it /// (INVARIANT 6): `Ok(None)` when it is open now, `Err` with why not. /// It waits for the server to be ready, and for the open. @@ -891,12 +932,10 @@ mod tests { } #[test] - fn a_root_is_the_apps_only_once_marked() { + fn a_root_is_read_from_what_runs_and_not_from_a_file() { let dir = tempfile::tempdir().unwrap(); - assert!(!app_hosted(dir.path())); - std::fs::write(dir.path().join(APP_MARKER), b"").unwrap(); - assert!(app_hosted(dir.path())); - // No server runs there: not the app's server. + // A mark an earlier build left is nothing: no server runs there. + std::fs::write(dir.path().join(RETIRED_MARKER), b"").unwrap(); assert!(!the_apps_server_runs(dir.path())); } } diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 4bdfb238..91b25088 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -54,19 +54,22 @@ //! refusal, which says how the human makes one; but when the token //! file is there and couldn't be read, with that instead: the token //! is not said to be missing. The token is never written to the agent or to stderr. -//! 12. For a root the desktop app serves (app_server.rs INVARIANT 7) with -//! no host running, the bridge is a thin line to the app's server -//! and nothing more: it holds no lease and starts no host (a -//! detached host is not how the desktop runs). With the app not -//! running, every call is answered "Wanderbooks isn't running: -//! start Wanderbooks and open BOOK." (`not_running_words`); with -//! the app running but BOOK not open in it, "Company BOOK isn't -//! open: open it in Wanderbooks." (`not_open_words`, for the -//! server's `closed` refusal at the door). Neither is final: the -//! call after the app starts, or the company opens, goes through, -//! in a session that was already running. A root no app has served, -//! and any root a host holds, behave as in 1 to 11 (`wanderbooks -//! serve`, the headless host). +//! 12. With no host running (every root but a headless `wanderbooks +//! serve`'s), the bridge is a thin line to whatever server runs and +//! nothing more: it holds no lease and starts no host (a detached +//! host is not how the desktop runs; only `wanderbooks serve` starts +//! one). With nothing running, every call is answered "Wanderbooks +//! isn't running: start Wanderbooks and open BOOK (on a computer +//! with no screen, run `wanderbooks serve`), then try again." +//! (`not_running_words`); with the app running but BOOK not open in +//! it, "Company BOOK isn't open: open it in Wanderbooks." +//! (`not_open_words`, for the server's `closed` refusal at the +//! door). Neither is final: the call after the app starts, or the +//! company opens, goes through, in a session that was already +//! running. A root a host holds (`wanderbooks serve`, the headless +//! host) behaves as in 1 to 11: the bridge holds a lease on it; and +//! when that host goes and nothing takes its place, the bridge +//! becomes the line above, in words, instead of starting another. //! ``` use crate::knobs::{FLAG, Knobs}; @@ -100,7 +103,9 @@ const MAYBE_RAN: &str = "the connection to the books server broke while this cal /// What the agent is told when the app is not running (INVARIANT 12). fn not_running_words(book: &str) -> String { - format!("Wanderbooks isn't running: start Wanderbooks and open {book}.") + format!( + "Wanderbooks isn't running: start Wanderbooks and open {book} (on a computer with no screen, run `wanderbooks serve`), then try again." + ) } /// What the agent is told when the app runs but the company is not open @@ -191,8 +196,9 @@ struct Bridge { /// The server's channel, for its owner check (INVARIANT 9). endpoint: ledger_mcp::ipc::Endpoint, /// Whether this is the line to the desktop app's server, with no host - /// and no lease (INVARIANT 12). - app: bool, + /// and no lease (INVARIANT 12). It turns true when a host the bridge + /// held is gone and nothing took its place. + app: std::sync::atomic::AtomicBool, } /// Who has the server's socket, when it isn't plainly this account. @@ -923,7 +929,7 @@ impl Bridge { Some(Link::Failed(why)) => return self.answer(&id, error(&id, why)), // The desktop app can't be reached, or the company isn't open // in it: said now, not "opening" (INVARIANT 12). - Some(Link::Refused(why)) if self.app => return self.answer(&id, error(&id, why)), + Some(Link::Refused(why)) if self.is_app() => return self.answer(&id, error(&id, why)), _ => None, }; let result = result.unwrap_or_else(|| { @@ -955,7 +961,7 @@ impl Bridge { let run_dir = opener.run_dir().to_path_buf(); let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); let account = crate::tokens::Account::new(&root, &self.book, &self.token_name); - let _ = self.token_file.set((account, run_dir)); + let _ = self.token_file.set((account, run_dir.clone())); let mut epoch = 0u64; loop { let mut lease = match opener.hold().await { @@ -965,6 +971,15 @@ impl Bridge { self.link.send_replace(Link::Closed); return; } + // The host this bridge held is gone (`wanderbooks serve` + // ended) and nothing runs: the bridge becomes the line to + // whatever runs next, and says so in words until then + // (INVARIANT 12). + Err(crate::opener::HoldError::NotRunning) => { + self.app.store(true, std::sync::atomic::Ordering::SeqCst); + self.link.send_replace(Link::Opening); + return self.keep_in_app(run_dir).await; + } Err(crate::opener::HoldError::Failed(why)) => { self.link.send_replace(Link::Failed(why)); return; @@ -1051,11 +1066,16 @@ impl Bridge { } } + /// Whether this is the line to the app's (or any host-less) server. + fn is_app(&self) -> bool { + self.app.load(std::sync::atomic::Ordering::SeqCst) + } + /// The words for a refusal at the server's door: for the desktop app's /// `closed` refusal, the bridge's own (INVARIANT 12); else the /// server's. fn refusal_words(&self, closed: bool, body: &str) -> String { - if self.app && closed { + if self.is_app() && closed { not_open_words(&self.book) } else { body.trim().chars().take(500).collect() @@ -1382,11 +1402,11 @@ async fn skip_line(input: &mut R) -> bool { } } -/// Whether the bridge is the line to the desktop app's server for the -/// root whose `run/` folder this is (INVARIANT 12): an app has served the -/// root, and no host holds it. +/// Whether the bridge is the line to the app's server for the root whose +/// `run/` folder this is (INVARIANT 12): no host holds it. The server +/// answering, or not running at all, is looked at call by call. fn serves_the_app(run: &std::path::Path) -> bool { - crate::app_server::app_hosted(run) && !crate::opener::host_lock_held(run) + !crate::opener::host_lock_held(run) } fn usage(prog: &str) { @@ -1470,7 +1490,7 @@ pub fn run( next_id: std::sync::atomic::AtomicU64::new(1), pending: Mutex::new(std::collections::HashMap::new()), endpoint, - app, + app: std::sync::atomic::AtomicBool::new(app), }); let keeper = if app { tokio::spawn(bridge.clone().keep_in_app(run_dir)) @@ -1834,7 +1854,7 @@ mod against_a_server { next_id: std::sync::atomic::AtomicU64::new(1), pending: Mutex::new(std::collections::HashMap::new()), endpoint, - app, + app: std::sync::atomic::AtomicBool::new(app), }); (bridge, rx) } @@ -2605,7 +2625,7 @@ mod against_a_server { fn the_two_messages_are_plain_and_name_the_company() { assert_eq!( not_running_words("acme"), - "Wanderbooks isn't running: start Wanderbooks and open acme." + "Wanderbooks isn't running: start Wanderbooks and open acme (on a computer with no screen, run `wanderbooks serve`), then try again." ); assert_eq!( not_open_words("acme"), @@ -2614,12 +2634,13 @@ mod against_a_server { } #[test] - fn a_root_is_the_apps_only_when_marked_and_no_host_holds_it() { + fn a_root_is_the_line_to_the_app_when_no_host_holds_it() { let dir = tempfile::tempdir().unwrap(); - assert!(!serves_the_app(dir.path()), "no app has served it"); - std::fs::write(dir.path().join(crate::app_server::APP_MARKER), b"").unwrap(); + assert!(serves_the_app(dir.path()), "no host holds it"); + // A mark an earlier build left changes nothing. + std::fs::write(dir.path().join(crate::app_server::RETIRED_MARKER), b"").unwrap(); assert!(serves_the_app(dir.path())); - // A host holding the root is the headless path, marked or not. + // A host holding the root is the headless path. let lock = std::fs::File::create(dir.path().join(crate::lease::HOST_LOCK)).unwrap(); lock.lock().unwrap(); assert!(!serves_the_app(dir.path())); diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index eb2c74a5..107cf8dd 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -108,7 +108,7 @@ fn exit(code: i32) -> Box { async fn open(opener: &mut Opener) -> Result { let deadline = tokio::time::Instant::now() + opener.knobs().open_wait; let too_long = || -> HoldError { - "the books didn't open in time: run `wanderbooks doctor` to see why".into() + "the books didn't open in time (Wanderbooks may still be opening a large company: try again in a moment): run `wanderbooks doctor` to see why".into() }; loop { let mut lease = tokio::time::timeout_at(deadline, opener.hold()) @@ -145,6 +145,135 @@ async fn open(opener: &mut Opener) -> Result { } } +/// Whether a command can do its work with no program holding the books +/// open, and what its own server then has open. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Direct { + /// It needs the books held open by Wanderbooks (the app, or `serve`): + /// with none running it says so ([`START_WANDERBOOKS`]). + No, + /// It manages the books' files, or reads: with nothing running it runs + /// a books server of its own for as long as the work takes (the same + /// server, taking the same locks, started the way the app starts its + /// own), with these companies open, and lets go of it when it is done. + With(Vec), +} + +/// What a request needs (the table in docs/spec/claims/app.md, WB-app-5). +fn direct_for(request: &Request) -> Direct { + match request { + // Opening and closing a company in a running server mean nothing + // with none running; the sessions and the backfill are of a + // running server's. + Request::OpenBook { .. } + | Request::CloseBook { .. } + | Request::Sessions + | Request::Extract { .. } => Direct::No, + // Work on an open company. + Request::BackUpNow { id, .. } | Request::UpgradeFormat { id, .. } => { + Direct::With(vec![id.clone()]) + } + // The rest read the list, or make and move files and tokens. + _ => Direct::With(Vec::new()), + } +} + +/// How long a command waits for its own server to close when it is done: +/// the same as the window's (a last backup of what it opened). +const OWN_STOP_WAIT: Duration = crate::app_server::STOP_WAIT; + +/// What a command holds while it works: a lease on a host or on the app's +/// server (no host behind it), or its own server, which it closes when it +/// is done. +struct Reached { + run_dir: PathBuf, + /// Held while the work runs (None for the app's server). + lease: Option, + /// The command's own server, when nothing else ran. + own: Option>, +} + +/// What a command says when the books were closed under it. +fn closed_just_now() -> String { + "the books were closed just now (Close the books): nothing was done".to_string() +} + +/// A hold that failed, in words. +fn hold_words(e: HoldError) -> String { + match e { + HoldError::ClosedByOwner => closed_just_now(), + HoldError::NotRunning => crate::opener::START_WANDERBOOKS.to_string(), + HoldError::Failed(why) => why, + } +} + +impl Reached { + /// The admin socket of what is held. + fn admin_socket(&self) -> PathBuf { + self.run_dir.join(ledger_mcp::local::ADMIN_SOCKET) + } + + /// One admin request, off the async threads. + async fn ask(&self, request: Request, wait: Option) -> Result { + let socket = self.admin_socket(); + tokio::task::spawn_blocking(move || admin::call_within(&socket, request, wait)) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string()) + } + + /// Let go: the lease ends, and a server of the command's own is + /// closed (its last backups made), waited for, and said so when it is + /// still at it. + async fn release(self) { + drop(self.lease); + if let Some(own) = self.own { + let stopped = tokio::task::spawn_blocking(move || own.stop(OWN_STOP_WAIT)).await; + match stopped { + Ok(crate::app_server::Stopped::Closed) | Err(_) => {} + Ok(crate::app_server::Stopped::Failed(why)) => { + eprintln!("warning: {why}: `wanderbooks doctor` has its last words"); + } + Ok(crate::app_server::Stopped::StillClosing) => { + eprintln!("note: {}", crate::app_server::STILL_CLOSING); + } + } + } + } +} + +/// Hold the books for a command, or, with nothing running and the work +/// one `direct` allows, run a server of its own (WB-app-5). +async fn reach(opener: &mut Opener, common: &Common, direct: &Direct) -> Result { + let run_dir = opener.run_dir().to_path_buf(); + match open(opener).await { + Ok(lease) => Ok(Reached { + run_dir, + lease: Some(lease), + own: None, + }), + Err(HoldError::NotRunning) => { + let Direct::With(books) = direct else { + return Err(crate::opener::START_WANDERBOOKS.to_string()); + }; + let (root, books) = (common.root.clone(), books.clone()); + let own = tokio::task::spawn_blocking(move || { + let server = crate::app_server::AppServer::start(root.as_deref(), &books)?; + server.wait_ready(crate::app_server::READY_WAIT)?; + Ok::<_, String>(server) + }) + .await + .map_err(|e| e.to_string())??; + Ok(Reached { + run_dir, + lease: None, + own: Some(std::sync::Arc::new(own)), + }) + } + Err(e) => Err(hold_words(e)), + } +} + /// Ask the server's admin socket, holding the books open meanwhile. fn with_server(common: &Common, request: Request) -> Result { with_server_in(common, request).map(|(answer, _)| answer) @@ -153,34 +282,40 @@ fn with_server(common: &Common, request: Request) -> Result { /// [`with_server`], with the root's `run/` folder too (where the /// token files live). fn with_server_in(common: &Common, request: Request) -> Result<(Response, PathBuf), String> { + let direct = direct_for(&request); + with_server_as(common, request, direct) +} + +/// [`with_server_in`] with what a command with nothing running may do +/// ([`Direct`]) said by the caller: a list that must show what an open +/// company waits for, for one. +fn with_server_as( + common: &Common, + request: Request, + direct: Direct, +) -> Result<(Response, PathBuf), String> { let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .map_err(|e| e.to_string())?; let outcome = rt.block_on(async { let mut opener = Opener::new(common.root.as_deref(), common.knobs, Kind::Cli, None)?; - let lease = open(&mut opener).await.map_err(|e| match e { - HoldError::ClosedByOwner => { - "the books were closed just now (Close the books): nothing was done".to_string() - } - HoldError::Failed(why) => why, - })?; - let run_dir = opener.run_dir().to_path_buf(); + let reached = reach(&mut opener, common, &direct).await?; + let run_dir = reached.run_dir.clone(); // The books are open: asked about a format upgrade first - // (INVARIANT 6). - if common.ask_upgrades && !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst) { + // (INVARIANT 6). (A server of the command's own has only what + // the command named open: nothing waits there to be offered.) + if common.ask_upgrades + && reached.own.is_none() + && !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst) + { let run = run_dir.clone(); let _ = tokio::task::spawn_blocking(move || offer_upgrades(&run)).await; } - let socket = run_dir.join(ledger_mcp::local::ADMIN_SOCKET); // A list is quick; a create or an adoption takes what it takes. let wait = matches!(request, Request::List | Request::TokenList).then_some(LIST_WAIT); - let answer = - tokio::task::spawn_blocking(move || admin::call_within(&socket, request, wait)) - .await - .map_err(|e| e.to_string())? - .map_err(|e| e.to_string()); - drop(lease); + let answer = reached.ask(request, wait).await; + reached.release().await; answer.map(|a| (a, run_dir)) }); // Past its deadline, the command ends: nothing pending holds it. @@ -222,7 +357,7 @@ fn no_host(server_lock_held: bool) -> &'static str { if server_lock_held { "The books are closing: a books server is finishing its last call." } else { - "The books are closed." + "The books are closed: Wanderbooks isn't running. Open the Wanderbooks app, or, on a computer with no screen, run `wanderbooks serve`." } } @@ -327,8 +462,8 @@ pub fn serve( println!("The books were closed (Close the books)."); return Ok(()); } - Err(HoldError::Failed(why)) => { - eprintln!("error: {why}"); + Err(e @ (HoldError::Failed(_) | HoldError::NotRunning)) => { + eprintln!("error: {}", hold_words(e)); return Err(exit(1)); } }; @@ -427,6 +562,14 @@ pub fn close( exit(1) })?; match asked { + None if crate::app_server::the_apps_server_runs(&run) => { + println!("{APP_HAS_THEM}."); + Ok(()) + } + None if crate::opener::server_lock_held(&run) => { + println!("The books are closing: a books server is finishing its last call."); + Ok(()) + } None => { println!("The books are already closed."); Ok(()) @@ -558,7 +701,21 @@ pub fn books( // (INVARIANT 6), unless it is the upgrade itself. common.ask_upgrades = !matches!(words.as_slice(), ["upgrade", ..]); let answer = match words.as_slice() { - ["list"] => with_server(&common, Request::List), + ["list"] => match listed_while_closed(&common) { + Ok(Some(ids)) => { + if ids.is_empty() { + println!("No books yet: `wanderbooks books create ID` starts some."); + } + for id in ids { + println!( + "{id} not open: Wanderbooks isn't running (start it, or run `wanderbooks serve`, to open it)" + ); + } + return Ok(()); + } + Ok(None) => with_server(&common, Request::List), + Err(why) => Err(why), + }, ["create", new] => with_server( &common, Request::Create { @@ -745,6 +902,21 @@ pub fn books( } /// One book, as `books list` and `doctor` show it. +/// The books of the root by name, read from the folder and no more, when +/// nothing runs: no host and no server holds the root, so there is no open +/// or closed to tell, and nothing is changed or read of the books, which +/// is why it takes no lock (WB-app-5). `None` when something runs: ask it. +fn listed_while_closed(common: &Common) -> Result>, String> { + let found = + ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; + let run = found.run_dir().map_err(|e| e.to_string())?; + if crate::opener::host_lock_held(&run) || crate::opener::server_lock_held(&run) { + return Ok(None); + } + let ids = found.list_books().map_err(|e| e.to_string())?; + Ok(Some(ids.iter().map(|id| id.to_string()).collect())) +} + fn book_line(b: &admin::BookStatus) -> String { if b.closed { return format!( @@ -915,13 +1087,36 @@ fn consent_now(run: &Path, book: &str, passphrase: &str) -> Result, // Refused: nothing was done (the server says so too). Some(HostMsg::Refused(why)) => Err(format!("not upgraded: {why}")), Some(HostMsg::Uncertain(why)) => Err(why), - // Sent, and the host gone without an answer (closed, or killed): - // its server may have done it all the same. - None => Err( - "the books' host gave no answer, so it may or may not have been done: `wanderbooks books list` says whether the books still wait for it" + // No host: the app's server, or one of the command's own, takes + // it as an admin request (WB-app-2). + None => upgrade_by_admin(run, book, passphrase), + Some(other) => Err(format!("the books' host answered oddly: {other:?}")), + } +} + +/// The format upgrade as an admin request to the server that runs with no +/// host (the app's, or a command's own): what it said, a line each; or +/// why not, which says whether it may have been done all the same. +fn upgrade_by_admin(run: &Path, book: &str, passphrase: &str) -> Result, String> { + let request = Request::UpgradeFormat { + id: book.to_string(), + passphrase: admin::Passphrase(passphrase.to_string()), + }; + match admin::call_within( + &run.join(ledger_mcp::local::ADMIN_SOCKET), + request, + Some(UPGRADE_WAIT), + ) { + Ok(Response::FormatUpgraded(u)) => Ok(upgraded_lines(&u)), + Ok(Response::Refused(why)) => Err(format!("not upgraded: {why}")), + Ok(_) => Err( + "the books server answered oddly, so it may or may not have been done: `wanderbooks books list` says whether the books still wait for it" .into(), ), - Some(other) => Err(format!("the books' host answered oddly: {other:?}")), + Err(admin::CallError::NotSent(why)) => Err(format!("not upgraded: {why}")), + Err(admin::CallError::Unknown(why)) => Err(format!( + "{why}, so it may or may not have been done: `wanderbooks books list` says whether the books still wait for it" + )), } } @@ -947,18 +1142,16 @@ pub fn upgrade_format( let not_sent = |why: String| format!("not upgraded: {why}"); let mut opener = Opener::new(common.root.as_deref(), common.knobs, Kind::Cli, None).map_err(not_sent)?; - let lease = open(&mut opener).await.map_err(|e| match e { - HoldError::ClosedByOwner => { - "not upgraded: the books were closed just now (Close the books): nothing was done" - .to_string() - } - HoldError::Failed(why) => not_sent(why), - })?; - let run = opener.run_dir().to_path_buf(); + // With nothing running, a server of its own with this company + // open does it. + let reached = reach(&mut opener, common, &Direct::With(vec![book.clone()])) + .await + .map_err(not_sent)?; + let run = reached.run_dir.clone(); let asked = tokio::task::spawn_blocking(move || consent_now(&run, &book, &passphrase)) .await .map_err(|e| e.to_string())?; - drop(lease); + reached.release().await; asked }); rt.shutdown_timeout(Duration::from_secs(1)); @@ -1057,9 +1250,14 @@ fn upgrade(common: &Common, book: &str) -> Result<(), Box Ok(id) => id.to_string(), Err(e) => return fail(e.to_string()), }; - let listed = match with_server(common, Request::List) { + // With nothing running, the list is of a server of its own with this + // company open, so what it waits for shows. + let listed = match with_server_as(common, Request::List, Direct::With(vec![book.clone()])) + .map(|(answer, _)| answer) + { Ok(Response::Books(books)) => books, - Ok(Response::Refused(why)) | Err(why) => return fail(why), + Ok(Response::Refused(why)) => return fail(why), + Err(why) => return fail(why), Ok(other) => return fail(format!("the books server answered oddly: {other:?}")), }; let Some(status) = listed.into_iter().find(|b| b.id == book) else { @@ -1129,37 +1327,10 @@ pub fn new_books(common: &Common, id: &str, currency: &str) -> Result Result { - let found = - ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; - let run = found.run_dir().map_err(|e| e.to_string())?; - // The app's own server: no host to ask (it isn't "closed": it is open). - if crate::app_server::the_apps_server_runs(&run) { - return Err(APP_HAS_THEM.into()); - } - match crate::opener::ask_once_within(&run, Ask::Intent(Intent::Close), HOST_WAIT)? { - None => Ok("The books are closed.".into()), - Some(HostMsg::Done { detail }) => Ok(detail - .map(|d| { - let mut c = d.chars(); - c.next() - .map(|first| format!("{}{}.", first.to_uppercase(), c.as_str())) - .unwrap_or_default() - }) - .filter(|d| !d.is_empty()) - .unwrap_or_else(|| "The books are closing.".into())), - Some(HostMsg::Refused(why)) => Err(why), - Some(HostMsg::Uncertain(why)) => Err(why), - Some(other) => Err(format!("the books' host answered oddly: {other:?}")), - } -} - /// An update the host has downloaded and checked, waiting for the owner /// (the viewer's notice; P11a step 4). #[derive(Clone, Debug, PartialEq, Eq)] @@ -1276,61 +1447,6 @@ const NO_SELF_UPDATE: &str = "self-update isn't available on this platform"; /// The longest an agent's own command may take to add the books. const CONNECT_WAIT: Duration = Duration::from_secs(60); -/// How long the viewer's hold waits before trying again after books that -/// wouldn't open. -const VIEWER_RETRY: Duration = Duration::from_secs(30); - -/// Hold the books `book` open while the viewer runs (a lease of kind -/// app), on a thread of its own: the window never waits for it. It lets -/// go only when the owner closes the books (and when the viewer ends, -/// with the process); books that stop, or won't open, are tried again. -pub fn hold_for_viewer(common: &Common, book: Option) -> std::thread::JoinHandle<()> { - let common = common.clone(); - std::thread::spawn(move || { - let Ok(rt) = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - else { - return; - }; - rt.block_on(async { - let Ok(mut opener) = Opener::new(common.root.as_deref(), common.knobs, Kind::App, book) - else { - return; - }; - loop { - // The same opener each time round (it knows it held the - // books, so it never reopens books the owner closed); its - // failures counted afresh. - opener.forget_failures(); - loop { - let mut lease = match open(&mut opener).await { - Ok(lease) => lease, - Err(HoldError::ClosedByOwner) => return, - Err(HoldError::Failed(_)) => break, - }; - match lease.next().await { - Some(HostMsg::Ending { - reason: Reason::ClosedByOwner, - .. - }) => return, - Some(HostMsg::Ending { - reason: Reason::Restarting | Reason::Closing, - .. - }) => {} - _ => { - if opener.failed().await.is_err() { - break; - } - } - } - } - tokio::time::sleep(VIEWER_RETRY).await; - } - }); - }) -} - /// What a backup made now came to, a line each. pub fn backed_up_lines(head_seq: u64, targets: &[admin::BackedUpTarget]) -> Vec { if targets.is_empty() { @@ -2775,6 +2891,52 @@ fn log_tail(run: &Path, name: &str, root: &Path, n: usize) -> Vec { .collect() } +/// `doctor`'s look at a running server through its admin socket: each +/// book and why one didn't open, the agents' tokens, who is connected. +fn admin_report(run: &Path) { + // Each book, and why one didn't open. + let socket = run.join(ledger_mcp::local::ADMIN_SOCKET); + // A quick look: a wedged server doesn't hang the doctor. + let listed = admin::call_within(&socket, Request::List, Some(DOCTOR_WAIT)); + if let Err(why) = &listed { + println!(" The books server doesn't answer: {why}"); + } + if let Ok(admin::Response::Books(books)) = listed { + for b in books { + println!(" {}", book_line(&b)); + if let Some(line) = database_line(&b) { + println!(" {line}"); + } + } + // Agents' tokens: how many each book has. + match admin::call_within(&socket, Request::TokenList, Some(DOCTOR_WAIT)) { + Ok(admin::Response::Tokens(tokens)) if tokens.is_empty() => { + println!("Agents' tokens: none yet (`wanderbooks token create --book ID`).") + } + Ok(admin::Response::Tokens(tokens)) => { + println!("Agents' tokens:"); + for t in tokens { + println!(" {} {} {}", t.book, t.name, t.scopes.join(",")); + } + } + Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"), + Ok(_) | Err(_) => {} + } + // Who is connected to each open book, and what it is doing. + match admin::call_within(&socket, Request::Sessions, Some(DOCTOR_WAIT)) { + Ok(admin::Response::Sessions(open)) => { + for line in session_lines(&open) { + println!("{line}"); + } + } + Ok(admin::Response::Refused(why)) => { + println!("Assistants connected: {why}") + } + Ok(_) | Err(_) => {} + } + } +} + /// `wanderbooks doctor`: whether the books are open, who holds them, and /// what the host and the server last said. It names no folder. pub fn doctor( @@ -2824,51 +2986,20 @@ pub fn doctor( } let run = root.run_dir().map_err(|e| e.to_string())?; match crate::opener::ask_once_within(&run, Ask::Leases, DOCTOR_WAIT) { - Ok(None) => println!("{}", no_host(crate::opener::server_lock_held(&run))), + // No host: the app's server (or another that runs without one), + // one still opening or finishing, or nothing (WB-app-3). + Ok(None) if crate::app_server::the_apps_server_runs(&run) => { + println!("The books are open: Wanderbooks (the app) has them."); + admin_report(&run); + } + Ok(None) if crate::opener::server_lock_held(&run) => println!( + "Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet." + ), + Ok(None) => println!("{}", no_host(false)), Ok(Some(HostMsg::Leases { ready, leases })) => { if ready { println!("The books are open."); - // Each book, and why one didn't open. - let socket = run.join(ledger_mcp::local::ADMIN_SOCKET); - // A quick look: a wedged server doesn't hang the doctor. - let listed = admin::call_within(&socket, Request::List, Some(DOCTOR_WAIT)); - if let Err(why) = &listed { - println!(" The books server doesn't answer: {why}"); - } - if let Ok(admin::Response::Books(books)) = listed { - for b in books { - println!(" {}", book_line(&b)); - if let Some(line) = database_line(&b) { - println!(" {line}"); - } - } - // Agents' tokens: how many each book has. - match admin::call_within(&socket, Request::TokenList, Some(DOCTOR_WAIT)) { - Ok(admin::Response::Tokens(tokens)) if tokens.is_empty() => println!( - "Agents' tokens: none yet (`wanderbooks token create --book ID`)." - ), - Ok(admin::Response::Tokens(tokens)) => { - println!("Agents' tokens:"); - for t in tokens { - println!(" {} {} {}", t.book, t.name, t.scopes.join(",")); - } - } - Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"), - Ok(_) | Err(_) => {} - } - // Who is connected to each open book, and what it is doing. - match admin::call_within(&socket, Request::Sessions, Some(DOCTOR_WAIT)) { - Ok(admin::Response::Sessions(open)) => { - for line in session_lines(&open) { - println!("{line}"); - } - } - Ok(admin::Response::Refused(why)) => { - println!("Assistants connected: {why}") - } - Ok(_) | Err(_) => {} - } - } + admin_report(&run); } else { println!("The books are opening (the books server isn't ready yet)."); } @@ -3240,12 +3371,8 @@ fn on_the_socket( Kind::Cli, None, )?; - let lease = open(&mut opener).await.map_err(|e| match e { - HoldError::ClosedByOwner => { - "the books were closed just now (Close the books): nothing was done".to_string() - } - HoldError::Failed(why) => why, - })?; + // A call to an open book: with nothing running there is none. + let reached = reach(&mut opener, common, &Direct::No).await?; let run_dir = opener.run_dir().to_path_buf(); let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); let account = crate::tokens::Account::new(&root, book, token_name); @@ -3277,7 +3404,7 @@ fn on_the_socket( .await .map_err(|e| format!("the books server's answer was cut off: {e}"))? .to_vec(); - drop(lease); + reached.release().await; Ok::<_, String>((status, headers, body)) }); rt.shutdown_timeout(Duration::from_secs(1)); @@ -3782,7 +3909,8 @@ mod tests { #[test] fn doctor_tells_closing_from_closed() { assert!(no_host(true).contains("closing")); - assert_eq!(no_host(false), "The books are closed."); + assert!(no_host(false).starts_with("The books are closed: Wanderbooks isn't running.")); + assert!(no_host(false).contains("wanderbooks serve")); } fn adopted() -> admin::Adopted { diff --git a/crates/ledger-host/src/opener.rs b/crates/ledger-host/src/opener.rs index 4d2d5f62..b5f468d5 100644 --- a/crates/ledger-host/src/opener.rs +++ b/crates/ledger-host/src/opener.rs @@ -1,19 +1,21 @@ //! Holding the books: how every holder takes its lease (plan 3.9). //! //! ```text -//! GOAL: a holder gets its lease on the one host, starting one when none -//! answers, even when several holders start at once; across a +//! GOAL: a holder gets its lease on the one host (the headless `serve`'s, +//! started by `serve` alone, even when several start at once) or on +//! the desktop app's own server; across a //! restart it simply holds again; a host that keeps failing is //! given up on, plainly, instead of retried forever. //! SOURCE: plan/served.md 3.9 ("One host, even in a race", "Closing": //! backoff 1, 2, 4 … 60 s, at most five tries; "Restarting": -//! openers wait on update.lock); tests host_respawns, -//! respawn_backs_off. +//! openers wait on update.lock); plan/p15-app-and-relay.md 3.1 +//! (only `serve` keeps a host; the app is the host otherwise), +//! WB-app-3, WB-app-5; tests host_respawns, respawn_backs_off. //! INVARIANTS: //! 1. Before each try the holder waits while a restart holds //! run/update.lock. -//! 2. No host answering: it starts one (cleanly, start.rs) and keeps -//! trying; +//! 2. No host answering: `serve` starts one (cleanly, start.rs) and keeps +//! trying (7); //! a host that is closing or restarting turns it away and it tries //! again until a host takes the lease. //! 3. A start that brings no lease within START_WAIT (or whose host @@ -28,12 +30,21 @@ //! 5. A holder that has held before, turned away because the owner //! closed the books, stays closed (HoldError::ClosedByOwner); a new //! holder waits for a new host. -//! 6. A root the desktop app has served (app_server.rs INVARIANT 7) -//! with the app's own server running and no host: a command's or -//! the viewer's hold is a lease on that server with no host behind -//! it (ready at once, never ended: the app decides when the books -//! close), no host is started beside it, and `wanderbooks serve` -//! is told the app has the books. +//! 6. No host answering, a books server holding the books (`run/ +//! server.lock`), and its admin socket answering: the desktop app's +//! own server (P15 3.1). A holder other than `wanderbooks serve` +//! takes a lease on it with no host behind it (ready at once, never +//! ended: the app decides when the books close), and no host is +//! started beside it; `wanderbooks serve` is told the app has the +//! books. The server's lock held and no admin socket yet is a server +//! still opening its companies (or finishing its last backup): the +//! holder waits for it, in words, for as long as its own wait lasts. +//! 7. No host, no server: only `wanderbooks serve` starts a host (the +//! headless path, plan 3.1). Every other holder is turned away with +//! [`HoldError::NotRunning`], and says, in words, to start +//! Wanderbooks; a command that can do its work without the books +//! being held open runs its own server for the length of the work +//! instead (commands.rs). //! ``` use crate::knobs::Knobs; @@ -69,14 +80,22 @@ pub enum HoldError { /// The owner closed the books, and this holder had held them /// (INVARIANT 5). ClosedByOwner, + /// Nothing holds the books (no host, no server), and this holder + /// starts none (INVARIANT 7). + NotRunning, /// Anything else, in plain words. Failed(String), } +/// What a person is told when nothing is running and the work needs the +/// books held open (INVARIANT 7). +pub const START_WANDERBOOKS: &str = "Start Wanderbooks first: nothing has the books open. Open the Wanderbooks app, or, on a computer with no screen, run `wanderbooks serve` and leave it running."; + impl std::fmt::Display for HoldError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { HoldError::ClosedByOwner => write!(f, "the owner closed the books"), + HoldError::NotRunning => f.write_str(START_WANDERBOOKS), HoldError::Failed(why) => f.write_str(why), } } @@ -220,31 +239,44 @@ impl Opener { Ok(()) } - /// Start counting failures over (a holder that waited a while after - /// giving up tries again); what it has held is kept (INVARIANT 5). - pub fn forget_failures(&mut self) { - self.failures = 0; - } - - /// Take a lease, starting a host if none answers (INVARIANTS 1-4). + /// Take a lease: on a host, on the app's server, or (`serve` alone) on + /// a host started for it (INVARIANTS 1-7). pub async fn hold(&mut self) -> Result { let mut started: Option = None; + let mut said_waiting = false; loop { // The app has the books: its own server serves them, and no // host is started beside it (INVARIANT 6). - if crate::app_server::the_apps_server_runs(&self.run) { - if self.kind == Kind::Serve { - return Err(HoldError::Failed( - "Wanderbooks (the app) has these books open: close it first, or use it" - .into(), - )); + if !host_lock_held(&self.run) && server_lock_held(&self.run) { + match admin_answers(&self.run) { + Ok(true) => { + if self.kind == Kind::Serve { + return Err(HoldError::Failed( + "Wanderbooks (the app) has these books open: close it first, or use it" + .into(), + )); + } + self.has_held = true; + return Ok(Lease { + id: 0, + link: None, + told_ready: false, + }); + } + Ok(false) => { + // Opening its companies, or finishing its last + // backup: wait for it, and say so once. + if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge + { + eprintln!( + "Wanderbooks is still opening (or closing) the books: waiting for it…" + ); + } + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + Err(why) => return Err(HoldError::Failed(why)), } - self.has_held = true; - return Ok(Lease { - id: 0, - link: None, - told_ready: false, - }); } wait_for_restart(&self.run).await; let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET) @@ -280,6 +312,11 @@ impl Opener { // for it rather than start another. let held = host_lock_held(&self.run); match started { + // Nothing runs, and only `serve` starts a host + // (INVARIANT 7). + None if !held && self.kind != Kind::Serve => { + return Err(HoldError::NotRunning); + } // A start that fails (a spawn error) is a // failure like any other (INVARIANT 3). None if !held => match self.start().await { @@ -420,6 +457,20 @@ pub fn host_lock_held(run: &Path) -> bool { } } +/// Whether the admin socket answers: the books server is up and ready +/// (it binds its sockets only once every company has been tried). A +/// socket of another account is an error. +pub fn admin_answers(run: &Path) -> Result { + let endpoint = ledger_mcp::ipc::Endpoint::new(run, ledger_mcp::local::ADMIN_SOCKET) + .map_err(|e| format!("can't reach the books server: {e}"))?; + match ledger_mcp::ipc::connect_std(&endpoint) { + Ok(stream) if ledger_mcp::ipc::peer_is_us(&stream) => Ok(true), + Ok(_) => Err("the books server's socket belongs to another account: not used".into()), + Err(e) if no_host(&e) => Ok(false), + Err(e) => Err(format!("can't reach the books server: {}", e.kind())), + } +} + /// Wait while a restart holds run/update.lock (INVARIANT 1). async fn wait_for_restart(run: &Path) { // Looked at, not waited on in a thread: a holder that gives up while From d81f6d5c83efe710c60920c4cd8b00b9cfceb774 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 11:29:34 -0700 Subject: [PATCH 03/11] feat(host): a command that names a company opens it in its own server; a bridge says a server is still opening A command with nothing running opens in its own server the one company it names (token create, check, revoke, back-up, upgrade, extract), so the owner is still told of a format upgrade that company waits for and the work that needs the company open can run. A bridge facing a server that holds the books but has no socket yet (the app opening large companies, or finishing a last backup) says it is still opening, not that Wanderbooks isn't running. The lib and commands spec blocks follow (WB-app-5). Co-Authored-By: Claude Fable 5.2 --- crates/ledger-host/src/bridge.rs | 47 ++++++++++++++++++--- crates/ledger-host/src/commands.rs | 65 +++++++++++++++++------------- crates/ledger-host/src/lib.rs | 27 ++++++++----- 3 files changed, 94 insertions(+), 45 deletions(-) diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 91b25088..6cda67f8 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -61,8 +61,10 @@ //! one). With nothing running, every call is answered "Wanderbooks //! isn't running: start Wanderbooks and open BOOK (on a computer //! with no screen, run `wanderbooks serve`), then try again." -//! (`not_running_words`); with the app running but BOOK not open in -//! it, "Company BOOK isn't open: open it in Wanderbooks." +//! (`not_running_words`); with a server holding the books and no +//! socket yet (the app opening large companies), "Wanderbooks is +//! still opening its companies…: try again shortly." +//! (`opening_words`); with the app running but BOOK not open in it, "Company BOOK isn't open: open it in Wanderbooks." //! (`not_open_words`, for the server's `closed` refusal at the //! door). Neither is final: the call after the app starts, or the //! company opens, goes through, in a session that was already @@ -108,6 +110,15 @@ fn not_running_words(book: &str) -> String { ) } +/// What the agent is told when a server holds the books and is not +/// answering yet: the app opening its companies (a large one takes a +/// while), or finishing a last backup (INVARIANT 12). +fn opening_words(book: &str) -> String { + format!( + "Wanderbooks is still opening its companies, or finishing the last backup of the last session: {book} can be reached in a moment. Try again shortly." + ) +} + /// What the agent is told when the app runs but the company is not open /// in it (INVARIANT 12). fn not_open_words(book: &str) -> String { @@ -1091,7 +1102,7 @@ impl Bridge { async fn keep_in_app(self: Arc, run_dir: PathBuf) { let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); let account = crate::tokens::Account::new(&root, &self.book, &self.token_name); - let _ = self.token_file.set((account, run_dir)); + let _ = self.token_file.set((account, run_dir.clone())); let mut epoch = 0u64; loop { if matches!(&*self.link.borrow(), Link::Opening) { @@ -1101,8 +1112,14 @@ impl Bridge { return; } Err(Owner::Unreachable) => { - self.link - .send_replace(Link::Refused(not_running_words(&self.book))); + // A server holding the books with no socket yet is + // opening (or finishing), not absent. + let words = if crate::opener::server_lock_held(&run_dir) { + opening_words(&self.book) + } else { + not_running_words(&self.book) + }; + self.link.send_replace(Link::Refused(words)); } Ok(()) => match self.open_session(epoch + 1).await { Ok(up) => { @@ -2691,6 +2708,26 @@ mod against_a_server { keeper.abort(); } + #[tokio::test] + async fn with_a_server_still_opening_the_answer_says_so_and_not_that_nothing_runs() { + let dir = tempfile::tempdir().unwrap(); + // A server holds the books and has bound no socket yet. + let lock = std::fs::File::create(dir.path().join(ledger_mcp::local::SERVER_LOCK)).unwrap(); + lock.lock().unwrap(); + let (b, mut rx) = app_bridge_at(&dir.path().join("mcp.sock"), knobs(3000, 3000)); + let keeper = tokio::spawn(b.clone().keep_in_app(dir.path().to_path_buf())); + let call: Value = serde_json::from_str(CALL).unwrap(); + b.waiting(&json!(7)); + b.clone().request_on(call, json!(7), "tools/call").await; + let said = told(&mut rx, 3000).await.unwrap()["error"]["message"] + .as_str() + .unwrap() + .to_string(); + assert_eq!(said, opening_words("acme")); + assert!(!said.contains("isn't running")); + keeper.abort(); + } + #[tokio::test] async fn with_the_app_running_a_company_that_is_not_open_is_said_in_words() { let server = Server::start(); diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 107cf8dd..c54c8285 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -7,17 +7,27 @@ //! //! ```text //! GOAL: from a terminal, or the viewer's menu, the owner holds the books -//! open, closes them, makes, adopts, backs up and restores books and -//! connects agents, without ever naming or touching the books' -//! private folder. +//! open (`serve`), closes them, makes, adopts, backs up and restores +//! books and connects agents, without ever naming or touching the +//! books' private folder, and without any command leaving a host or a +//! server running that nothing manages. //! SOURCE: plan/served.md 3.9 (a terminal running `wanderbooks serve`, and -//! any command that needs the server, holds a lease; "Close the -//! books" ends every lease), 3.1 (the CLI talks to admin.sock and -//! never reads the books), 5.5 (adopt; preview and confirmation at -//! the terminal). +//! any command that needs a host, holds a lease), 3.1 (the CLI +//! talks to admin.sock and never reads the books), 5.5 (adopt; +//! preview and confirmation at the terminal); +//! plan/p15-app-and-relay.md 3.1 (the app is the host; only `serve` +//! keeps a detached host), WB-app-5. //! INVARIANTS: -//! 1. A command that needs the server holds a lease while it runs, and -//! lets go when it ends. +//! 1. A command that needs the server finds what holds the books: a +//! host (it holds a lease while it runs, and lets go when it ends), +//! the app's server (no lease: the app decides when the books +//! close), or nothing. With nothing running it starts no host: a +//! command that only reads, or manages the books' files, runs a +//! server of its own for the length of the work and closes it +//! (waiting for its last backup); one that needs a company held open +//! says "Start Wanderbooks first" ([`Direct`], [`reach`]; WB-app-5). +//! A server of its own takes the locks the app's server takes, so +//! two programs never hold one set of books. //! 2. Nothing printed names the data root. //! 3. Adoption and restoring are previewed first and go ahead only on a //! yes at the terminal, or --yes; a vault beside the books must be @@ -31,8 +41,7 @@ //! makes the books' agent token only when there is no token file for //! it, replacing the server's (no one could be using it: the bridge //! reads its token from this file). -//! 5. The viewer's hold lets go only when the owner closes the books; -//! books that stop, or won't open, are tried again. +//! 5. (Retired with the viewer's lease: the app is the host.) //! 6. Books waiting for a format upgrade (plan 3.9, D-39): the owner's //! commands that open the books (`serve`, `books`, `token`, //! `connect`) ask for the go-ahead once each time they run, at a @@ -40,7 +49,8 @@ //! the foreground: the question, then the owner passphrase, which only //! the server checks); elsewhere they only say so, on stderr. Only a passphrase typed //! at a terminal (or in the viewer) is sent, through the lease -//! socket's consent_format_upgrade; declining changes nothing. +//! socket's consent_format_upgrade (a host), or as the admin request +//! `UpgradeFormat` (no host); declining changes nothing. //! ``` use crate::knobs::{FLAG, Knobs}; @@ -163,17 +173,17 @@ enum Direct { fn direct_for(request: &Request) -> Direct { match request { // Opening and closing a company in a running server mean nothing - // with none running; the sessions and the backfill are of a - // running server's. - Request::OpenBook { .. } - | Request::CloseBook { .. } - | Request::Sessions - | Request::Extract { .. } => Direct::No, - // Work on an open company. - Request::BackUpNow { id, .. } | Request::UpgradeFormat { id, .. } => { - Direct::With(vec![id.clone()]) - } - // The rest read the list, or make and move files and tokens. + // with none running, and the sessions are of a running server's. + Request::OpenBook { .. } | Request::CloseBook { .. } | Request::Sessions => Direct::No, + // Work on one company, which the server opens (so the owner is + // told of a format upgrade it waits for, INVARIANT 6). + Request::BackUpNow { id, .. } + | Request::UpgradeFormat { id, .. } + | Request::Extract { id, .. } => Direct::With(vec![id.clone()]), + Request::TokenCreate { book, .. } + | Request::TokenCheck { book, .. } + | Request::TokenRevoke { book, .. } => Direct::With(vec![book.clone()]), + // The rest read the list, or make and move files. _ => Direct::With(Vec::new()), } } @@ -303,12 +313,9 @@ fn with_server_as( let reached = reach(&mut opener, common, &direct).await?; let run_dir = reached.run_dir.clone(); // The books are open: asked about a format upgrade first - // (INVARIANT 6). (A server of the command's own has only what - // the command named open: nothing waits there to be offered.) - if common.ask_upgrades - && reached.own.is_none() - && !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst) - { + // (INVARIANT 6). (A server of the command's own has only the + // company the command names open.) + if common.ask_upgrades && !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst) { let run = run_dir.clone(); let _ = tokio::task::spawn_blocking(move || offer_upgrades(&run)).await; } diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index e49ba2d4..bd6bfb2a 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -1,15 +1,20 @@ -//! The books open while something holds them (plan 3.9, D-21, D-23). +//! The books open while something holds them (plan 3.9, D-21, D-23; plan +//! P15 3.1, D-77, D-84). //! -//! Nothing runs in the background: the first holder (the app, an agent's -//! bridge, `wanderbooks serve`, or a command that needs the books) starts -//! the **host**, which starts the books server and holds it open while -//! any lease on its socket lasts, and closes it 10 s after the last one -//! ends. Each part is a mode of the one `wanderbooks` executable: -//! [`host::run`] (`wanderbooks host`), [`bridge::run`] (`wanderbooks -//! mcp`), and the owner's commands in [`commands`] (`serve`, `close`, -//! `books`, `token`, `connect`, `doctor`, `passphrase`, and what the -//! viewer's Books menu does). Agents' tokens are kept in files under the data root -//! ([`tokens`]). +//! On the desktop the app is the host: [`app_server`] starts the books +//! server as the window's child and closes it by closing its input. +//! Nothing else on the desktop starts a detached host. The headless +//! `wanderbooks serve` keeps one, as before: its host starts the books +//! server and holds it open while any lease on its socket lasts, and +//! closes it 10 s after the last one ends. Each part is a mode of the one +//! `wanderbooks` executable: [`host::run`] (`wanderbooks host`), +//! [`bridge::run`] (`wanderbooks mcp`, a line to whatever runs, in words +//! when nothing does), and the owner's commands in [`commands`] (`serve`, +//! `close`, `books`, `token`, `connect`, `doctor`, `passphrase`, and what +//! the viewer's Books menu does), which talk to the running app's (or +//! host's) server, or with nothing running run a server of their own for +//! the length of the work, or say "Start Wanderbooks first". Agents' +//! tokens are kept in files under the data root ([`tokens`]). pub mod app_server; pub mod bridge; From e9a520138d6d902dc412b9e239e5cd80ef77c90a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 11:34:19 -0700 Subject: [PATCH 04/11] test(cli): the detached-host tests follow the new shape: only serve starts a host Plan P15 unit A5. Nothing but `wanderbooks serve` starts a host, so the tests that had a bridge or a command start one now have `serve` hold the books (a `serve` the harness keeps: Home::keep_host), or run a server of their own (the commands), or are retired. Every test of the three files plan section 6 names, and what became of it: open_while_held.rs (44 tests) KEPT, still true for serve (28): closing_the_books_ends_every_lease_and_the_bridge_stays_closed, closing_during_a_burst_of_posts_through_the_bridge_loses_nothing, a_killed_host_is_replaced_by_its_holders, holders_back_off_and_give_up_on_a_host_that_keeps_failing, the_lease_socket_takes_only_the_owners_intents, a_restart_is_not_a_close, another_apps_appimage_is_never_run_as_the_host, the_host_outlives_the_app_scope_that_started_it, the_bridge_serves_a_client_without_initialize, the_bridge_recovers_when_the_server_dies_under_it, a_message_too_large_is_refused_and_the_session_goes_on, malformed_and_boundary_input_never_ends_the_session, the_host_starts_without_a_scope_when_systemd_run_fails, a_scrubbed_app_scope_doesnt_take_the_host_with_it, doctor_doesnt_hang_on_a_frozen_host, doctor_doesnt_hang_on_a_frozen_server, serve_hears_ctrl_c_while_it_waits_to_try_again, every_malformed_message_is_answered, books_that_didnt_open_refuse_plainly, close_and_list_dont_hang_on_frozen_processes, the_books_command_takes_its_flags_and_asks_before_adopting, adopted_books_old_copies_are_put_aside_from_the_command_line, the_token_commands_and_the_bridge (the bridges there are held by serve through Agent::start), an_agent_sends_and_saves_files_with_the_commands_it_is_given, a_backup_is_restored_from_the_command_line, books_are_backed_up_now_from_the_command_line, connect_makes_anew_a_token_whose_file_is_gone_and_says_when_an_agent_refuses, token_check_says_where_the_token_file_stands_and_an_unreadable_one_is_said (these commands now run a server of their own with nothing running). MOVED, rewritten for the new shape (15): a_command_opens_the_books_and_they_close_after_the_last_holder -> a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder; openers_share_one_host_and_one_server -> serve_and_the_bridges_share_one_host_and_one_server (two serves at once are the race now); the_bridge_opens_closed_books_and_holds_them_for_the_session -> the_bridge_reaches_the_books_serve_holds_and_holds_them_for_the_session; the_host_starts_clean_from_a_hostile_bridge -> the_host_serve_starts_is_clean_from_a_hostile_serve; the_bridge_answers_initialize_itself_during_a_slow_start, the_bridge_gives_up_on_books_that_never_open, a_call_cancelled_at_once_is_never_made, a_signalled_bridge_goes_at_once, books_made_mid_session_and_bad_requests (a slow `serve` holds the host; the bridge starts after it holds the root); books_commands_hold_the_books_while_they_run (serve holds, the commands lease); a_command_ends_at_its_deadline_during_a_restart (`token list`: `books list` with nothing running reads the folder and waits for nothing); a_bridge_started_without_stderr_keeps_its_descriptors_apart, the_commands_given_run_as_the_agents_own_token, an_agent_is_connected_and_reaches_the_books_by_what_it_was_given (Home::keep_host); doctor_says_whether_the_books_are_open_and_what_holds_them (new closed words). RETIRED (1): the_viewers_hold_new_books_and_close_the_books. Its viewer lease (hold_for_viewer) and "Close the books" (close_books) no longer exist: the app is the host. Covered by ledger-gui serving.rs (a_tab_opening_asks_the_server_to_open_that_company, a_tab_closing_asks_the_server_to_close_that_company, closing_the_window_stops_the_server_and_waits_for_it), owner_menu.rs (no "Close the books" item), and the replacement the_viewers_new_books_are_made_by_the_server (new_books through a server). Behaviours retired inside the moved tests, and what covers them: a command or a bridge starting a host and holding it for the close delay does not exist (app_server.rs: a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running, with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks, the_bridge_says_the_app_isnt_running_then_works_once_it_is, a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder); the close delay itself is kept for serve's host (same test). update.rs (16 tests) KEPT (6): an_update_replaces_the_program_keeps_the_old_one_and_rollback_brings_it_back, update_is_atomic, failed_update_rolls_back, unsigned_update_refused, package_managed_install_refuses_update, rollback_refuses_after_a_book_consented_to_a_newer_format, an_update_never_replaces_another_apps_appimage (the `update` command and the AppImage guard: no host involved). MOVED (9): bridge_survives_update, update_waits_for_a_running_call, a_replaced_appimage_restarts_the_books, the_host_stages_a_daily_update_and_the_next_start_applies_it, a_daily_update_that_is_not_ours_is_not_staged, update_installs_the_copy_the_host_staged_without_downloading_again, a_staged_update_that_was_tampered_with_is_dropped_not_applied, books_start_says_an_update_waits, the_owner_accepts_a_staged_update_in_the_app: the host they describe is serve's (restart onto a replaced file, update.lock, the daily look, the staged copy applied before a host starts), so the harness's Agent::start has a `serve` hold the books (Home::keep_host); the bridge's tool calls carry the request_key every write needs since D-88. RETIRED (0). translocation.rs (1 test) KEPT: translocated_app_refuses_to_connect. The refusal stays: an agent's pointer file records this program's path, which a quarantined download loses when the app closes, whatever starts the books. app_server.rs: no test retired. Changed: the_bridge_says_the_app_isnt_running_then_works_once_it_is (no marker; the words now name `wanderbooks serve`), a refusal touches nothing (the retired marker). New: a_mark_an_earlier_build_left_is_ignored_and_removed, a_terminal_ctrl_c_reaches_the_window_and_never_the_server (fails without the server's own process group: checked by removing it), a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running, with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks, a_command_waits_in_words_for_a_server_that_is_still_opening. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/app_server.rs | 215 +++++++++++++++++++-- crates/ledger-cli/tests/open_while_held.rs | 213 +++++++++++++------- crates/ledger-cli/tests/update.rs | 33 ++++ 3 files changed, 380 insertions(+), 81 deletions(-) diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs index 15a08103..555e3457 100644 --- a/crates/ledger-cli/tests/app_server.rs +++ b/crates/ledger-cli/tests/app_server.rs @@ -148,25 +148,212 @@ fn a_mark_an_earlier_build_left_is_ignored_and_removed() { /// The server is in a process group of its own, so a Ctrl+C at the /// terminal the window was started from (sent to the terminal's /// foreground group, the window's) never reaches it: it closes by its -/// input alone (app_server.rs INVARIANT 3). +/// input alone (app_server.rs INVARIANT 3). The window here is a process +/// of its own in a group of its own, that ignores the signal as a window +/// that handles Ctrl+C does; the group is sent SIGINT, as a terminal does. #[cfg(unix)] #[test] -fn the_server_has_a_process_group_of_its_own_so_a_terminal_ctrl_c_misses_it() { - let home = Home::new("app-group"); +fn a_terminal_ctrl_c_reaches_the_window_and_never_the_server() { + let home = Home::new("app-ctrl-c"); + let run = home.run(); + let mut window = { + use std::os::unix::process::CommandExt; + Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "a_window_that_is_about_to_die", "--nocapture"]) + .env("WB_APP_DYING_HOME", home.dir.path()) + .env("WB_APP_IGNORE_SIGINT", "1") + .process_group(0) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap() + }; + struct Reap(Child); + impl Drop for Reap { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let mut lines = BufReader::new(window.stdout.take().unwrap()).lines(); + let mut server_pid = None; + loop { + let line = lines.next().expect("the window said ready").unwrap(); + if let Some(pid) = line.strip_prefix(CHILD_PID) { + server_pid = pid.trim().parse::().ok(); + } + if line == READY { + break; + } + } + let mut window = Reap(window); + let server_pid = server_pid.expect("the window gave the server's pid"); + let window_group = window.0.id() as i32; + // SAFETY: getpgid only reads a process-group id. + let (its, ours) = unsafe { (libc::getpgid(server_pid), libc::getpgrp()) }; + assert_ne!(its, window_group, "the server is in the window's group"); + assert_ne!(its, ours); + // The terminal's Ctrl+C: SIGINT to the window's whole group. + // SAFETY: the group of a process this test started and leads. + assert_eq!(unsafe { libc::killpg(window_group, libc::SIGINT) }, 0); + // The window is still there, and so is the server, with its books + // open and answering: nothing closed them. + std::thread::sleep(Duration::from_millis(1500)); + assert!(window.0.try_wait().unwrap().is_none(), "the window died"); + assert!(server_lock_held(&run), "the server closed on Ctrl+C"); + assert!(matches!(home.admin(Request::List), Response::Books(_))); + // The window going is what closes it. + window.0.kill().unwrap(); + window.0.wait().unwrap(); + until("the server let go of the books", || !server_lock_held(&run)); +} + +/// A command run (as a subprocess, as a person's terminal does) while the +/// app's server runs goes to it: no host, no second server, and what it +/// says is the app's (WB-app-5). It never closes the app's books. +#[test] +fn a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running() { + let home = Home::new("app-command"); + let run = home.run(); let server = start(&home, &[]); server.wait_ready(Duration::from_secs(60)).unwrap(); - let pid = server.pid() as libc::pid_t; - // SAFETY: getpgid and getpgrp only read process-group ids. - let (its, ours) = unsafe { (libc::getpgid(pid), libc::getpgrp()) }; - assert_eq!(its, pid, "it leads a group of its own"); - assert_ne!(its, ours, "it is not in the window's group"); - // The group the terminal signals is the window's: a SIGINT sent to - // every process of that group but ours cannot be shown here, so the - // property is what makes it hold: nothing of the server is in it. + home.create(BOOK, "USD"); + let command = |args: &[&str]| { + let mut c = Command::new(exe()); + c.args(args) + .arg("--root") + .arg(home.root()) + .stdin(Stdio::null()); + clean_env(&mut c, home.dir.path()); + c.output().unwrap() + }; + let said = |o: &std::process::Output| String::from_utf8_lossy(&o.stdout).into_owned(); + let listed = command(&["books", "list"]); + assert!(listed.status.success(), "{listed:?}"); + assert!( + said(&listed).contains(&format!("{BOOK} open")), + "{listed:?}" + ); + // A company is opened and closed in the app's server by the command. + let closed = command(&["books", "close", BOOK]); + assert!(closed.status.success(), "{closed:?}"); + assert!(!open_in_server(&home, BOOK)); + let opened = command(&["books", "open", BOOK]); + assert!(opened.status.success(), "{opened:?}"); + assert!(open_in_server(&home, BOOK)); + // `close` and `doctor` say whose the books are, in words. + let said_close = command(&["close"]); + assert!( + said(&said_close).contains("Wanderbooks (the app) has these books open"), + "{said_close:?}" + ); + let doctor = command(&["doctor"]); + assert!( + said(&doctor).contains("Wanderbooks (the app) has them") + && said(&doctor).contains(&format!("{BOOK} open")), + "{doctor:?}" + ); + // Through all of it: no host, one server, still the app's. + assert!(!host_lock_held(&run)); + assert!(!run.join("lease.sock").exists()); assert_eq!(server.exited(), None); + assert!(server_lock_held(&run)); assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); } +/// With nothing running, a command that manages the books' files runs a +/// server of its own and leaves nothing behind; one that needs an open +/// company says to start Wanderbooks (WB-app-5). +#[test] +fn with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks() { + let home = Home::new("app-own"); + let run = home.run(); + let command = |args: &[&str]| { + let mut c = Command::new(exe()); + c.args(args) + .arg("--root") + .arg(home.root()) + .stdin(Stdio::null()); + clean_env(&mut c, home.dir.path()); + c.output().unwrap() + }; + let created = command(&["books", "create", BOOK]); + assert!(created.status.success(), "{created:?}"); + assert!(!server_lock_held(&run), "the command's server was left"); + assert!(!host_lock_held(&run)); + // The folder is read for a list: nothing is open. + let listed = command(&["books", "list"]); + assert!( + String::from_utf8_lossy(&listed.stdout) + .contains(&format!("{BOOK} not open: Wanderbooks isn't running")), + "{listed:?}" + ); + // Work on a company opens it in the command's own server, then closes. + let token = command(&["token", "create", "--book", BOOK]); + assert!(token.status.success(), "{token:?}"); + let backed = command(&["books", "back-up", BOOK]); + assert!( + backed.status.success() || String::from_utf8_lossy(&backed.stderr).contains("backup"), + "{backed:?}" + ); + assert!(!server_lock_held(&run), "the command's server was left"); + // Opening a company means nothing with no server: said in words. + let open = command(&["books", "open", BOOK]); + assert_eq!(open.status.code(), Some(1), "{open:?}"); + let err = String::from_utf8_lossy(&open.stderr); + assert!( + err.contains("Start Wanderbooks first") && err.contains("wanderbooks serve"), + "{err}" + ); + assert!(!server_lock_held(&run)); +} + +/// A command arriving while a server holds the books and has no admin +/// socket yet (the app opening large companies, or finishing a backup) +/// waits, says so in words, and then says plainly that it is still +/// opening: it neither fails with a connection error nor starts a second +/// server beside it (WB-app-5). Here the server is stood in for by its +/// lock. +#[test] +fn a_command_waits_in_words_for_a_server_that_is_still_opening() { + let home = Home::new("app-opening"); + let run = home.run(); + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(run.join("server.lock")) + .unwrap(); + lock.lock().unwrap(); + let mut c = Command::new(exe()); + c.args(["token", "list", "--root"]) + .arg(home.root()) + .args(["--test-knobs", "open_wait=1500"]) + .stdin(Stdio::null()); + clean_env(&mut c, home.dir.path()); + let started = Instant::now(); + let out = c.output().unwrap(); + assert_eq!(out.status.code(), Some(1), "{out:?}"); + let (said, err) = ( + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + assert!( + err.contains("Wanderbooks is still opening (or closing) the books: waiting for it"), + "{said} {err}" + ); + assert!( + err.contains("didn't open in time") && err.contains("try again in a moment"), + "{err}" + ); + assert!(!err.contains("can't reach"), "a connection error: {err}"); + assert!(started.elapsed() < Duration::from_secs(10)); + // No server of its own was started beside the one holding the lock. + assert!(!host_lock_held(&run)); + drop(lock); +} + #[test] fn opening_and_closing_a_company_drives_the_servers_book() { let home = Home::new("app-tabs"); @@ -242,6 +429,12 @@ fn a_window_that_is_about_to_die() { return; }; let home = std::path::PathBuf::from(home); + #[cfg(unix)] + if std::env::var_os("WB_APP_IGNORE_SIGINT").is_some() { + // A window that survives its terminal's Ctrl+C (it handles it). + // SAFETY: setting a signal's disposition to ignore. + unsafe { libc::signal(libc::SIGINT, libc::SIG_IGN) }; + } let root = ledger_store::root::default_root(&home); let dir = home.clone(); let server = AppServer::start_in(exe(), Some(&root), &[], move |c: &mut Command| { diff --git a/crates/ledger-cli/tests/open_while_held.rs b/crates/ledger-cli/tests/open_while_held.rs index b505d5d6..39c46ac1 100644 --- a/crates/ledger-cli/tests/open_while_held.rs +++ b/crates/ledger-cli/tests/open_while_held.rs @@ -28,6 +28,11 @@ const KNOBS: &str = struct Home { dir: tempfile::TempDir, exe: PathBuf, + /// The `wanderbooks serve` that holds this home's books for the + /// agents of the test ([`Home::keep_host`]): since P15 only `serve` + /// starts a host, so an agent's bridge finds it running or finds + /// nothing. + serving: std::sync::Mutex>, } /// Wait until a program just copied can be run. A child another test @@ -70,6 +75,16 @@ impl Home { Self { dir, exe: PathBuf::from(env!("CARGO_BIN_EXE_wanderbooks")), + serving: std::sync::Mutex::new(None), + } + } + + /// Run `wanderbooks serve` for this home and keep it running until the + /// home goes: the one thing that starts a host (WB-app-5). Once only. + fn keep_host(&self) { + let mut serving = self.serving.lock().unwrap(); + if serving.is_none() { + *serving = Some(serve(self)); } } @@ -315,6 +330,7 @@ struct Agent { impl Agent { fn start(home: &Home, book: &str) -> Self { + home.keep_host(); let mut c = home.cmd("mcp"); c.args(["--book", book]); let mut a = Self::from(c); @@ -474,6 +490,21 @@ fn post_one(a: &mut Agent, n: u64) -> Result { Ok(id) } +/// A `serve` whose server is slow to open (the knobs' `server_delay`), +/// waited for only until its host holds the root: a bridge started then is +/// held by it and waits for the books, as a bridge once did for a host it +/// started itself (P15: only `serve` starts a host). +fn slow_serve(home: &Home, knobs: &str) -> Running { + let mut c = home.cmd("serve"); + c.args(["--test-knobs", knobs]); + let r = Running::start(c); + assert!( + wait_for(20, || ledger_host::opener::host_lock_held(&home.run_dir())), + "the host never started" + ); + r +} + fn serve(home: &Home) -> Running { let r = Running::start(home.cmd("serve")); // The first time, it says how to let go. @@ -481,49 +512,73 @@ fn serve(home: &Home) -> Running { r } +/// P15 (WB-app-5): a command with nothing running runs a server of its own +/// and leaves nothing behind: no host, no server, no socket. The host `serve` +/// holds still closes `close_after` after its last holder lets go, whoever +/// that is. #[test] -fn a_command_opens_the_books_and_they_close_after_the_last_holder() { +fn a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder() { let home = Home::new("last"); assert!(home.host().is_none()); home.create("acme"); - // The command let go; the books stay open for the close delay, then - // close. - assert!(home.host().is_some(), "closed at once"); - assert!(home.wait_closed(10), "never closed"); + // The commands (a create, a token) ran a server of their own and let go + // of it: nothing of the root is left. + assert!(home.host().is_none(), "a command started a host"); + assert!(home.pids("server").is_empty(), "a server was left running"); for sock in ["lease.sock", "mcp.sock", "admin.sock"] { assert!(!home.run_dir().join(sock).exists(), "{sock} left behind"); } - // A lease arriving within the delay cancels the close. - home.create("beta"); - std::thread::sleep(Duration::from_millis(200)); - let host = home.host().unwrap(); - home.create("gamma"); - std::thread::sleep(Duration::from_millis(1000)); - assert_eq!( - home.host(), - Some(host), - "closed though a lease came in time" + assert!(!ledger_host::opener::server_lock_held(&home.run_dir())); + // An agent session with nothing running starts no host either. + let mut a = Agent::from({ + let mut c = home.cmd("mcp"); + c.args(["--book", "acme"]); + c + }); + let init = a.initialize(); + assert!( + init["error"]["message"] + .as_str() + .is_some_and(|m| m.starts_with("Wanderbooks isn't running")), + "{init}" ); - assert!(home.wait_closed(10)); - // An agent session killed outright: closed after the delay, too. - let mut a = Agent::start(&home, "acme"); - a.initialize(); - a.call("books.start", json!({})).unwrap(); - a.run.child.kill().unwrap(); - a.run.child.wait().unwrap(); - std::thread::sleep(Duration::from_millis(300)); - assert!(home.host().is_some(), "closed before the delay"); - assert!(home.wait_closed(10), "never closed after the bridge died"); + assert!(home.host().is_none(), "a bridge started a host"); + drop(a); // A holder that is killed: closed after the delay, not before. let mut held = serve(&home); let leases = home.lease_line("{\"proto\":1,\"leases\":null}\n"); assert!(leases.contains("\"serve\""), "{leases}"); assert!(leases.contains(&held.child.id().to_string()), "{leases}"); + // A command while serve holds the books shares its host: a lease that + // comes in time cancels nothing, and no second host starts. + home.create("beta"); + assert_eq!(home.pids("host").len(), 1, "one host"); held.child.kill().unwrap(); held.child.wait().unwrap(); std::thread::sleep(Duration::from_millis(300)); assert!(home.host().is_some(), "closed before the delay"); assert!(home.wait_closed(10), "never closed after the holder died"); + // The last holder is an agent's bridge: serve lets go (Ctrl-C), the + // host stays for the bridge past the close delay, and closes after the + // bridge is killed, not before. + let mut held = serve(&home); + let mut bridge = Running::start({ + let mut c = home.cmd("mcp"); + c.args(["--book", "acme"]); + c + }); + assert!(wait_for(30, || home + .lease_line("{\"proto\":1,\"leases\":null}\n") + .contains("\"bridge\""))); + held.signal(libc::SIGINT); + assert!(held.wait(10).is_some_and(|s| s.success())); + std::thread::sleep(Duration::from_millis(3500)); + assert!(home.host().is_some(), "closed under a bridge that holds"); + bridge.child.kill().unwrap(); + bridge.child.wait().unwrap(); + std::thread::sleep(Duration::from_millis(300)); + assert!(home.host().is_some(), "closed before the delay"); + assert!(home.wait_closed(10), "never closed after the bridge died"); // Ctrl-C at the terminal: serve lets go, and the books close. let mut held = serve(&home); held.signal(libc::SIGINT); @@ -535,13 +590,21 @@ fn a_command_opens_the_books_and_they_close_after_the_last_holder() { } #[test] -fn openers_share_one_host_and_one_server() { +fn serve_and_the_bridges_share_one_host_and_one_server() { let home = Home::new("share"); home.create("acme"); assert!(home.wait_closed(10)); - // All at once, from closed. - let mut holders = vec![ + // Two `serve`s at once, from closed (the only programs that start a + // host): one host, one server, and both hold it. + let held = vec![ Running::start(home.cmd("serve")), + Running::start(home.cmd("serve")), + ]; + for h in &held { + h.expect("The books are open", 30); + } + // Two bridges and a command, all at once, on the host they started. + let holders = vec![ Running::start({ let mut c = home.cmd("mcp"); c.args(["--book", "acme"]); @@ -558,7 +621,6 @@ fn openers_share_one_host_and_one_server() { c.arg("list").stdin(Stdio::null()); move || c.output().unwrap() }); - holders[0].expect("The books are open", 30); let out = list.join().unwrap(); assert!( String::from_utf8_lossy(&out.stdout).contains("acme open"), @@ -576,15 +638,17 @@ fn openers_share_one_host_and_one_server() { == 2), "the bridges' leases" ); - holders.clear(); + drop(holders); + drop(held); assert!(home.wait_closed(15)); } #[test] -fn the_bridge_opens_closed_books_and_holds_them_for_the_session() { +fn the_bridge_reaches_the_books_serve_holds_and_holds_them_for_the_session() { let home = Home::new("bridge"); home.create("acme"); assert!(home.wait_closed(10)); + // Held by `serve` (Agent::start): the bridge starts no host itself. let mut a = Agent::start(&home, "acme"); let init = a.initialize(); // Ready in time: the server's own answer, its connect text. @@ -605,7 +669,7 @@ fn the_bridge_opens_closed_books_and_holds_them_for_the_session() { assert!(a.call("books.get_entry", json!({"entry_id": 999})).is_err()); let unknown = a.request("no/such/method", json!({}), 20); assert!(unknown.get("error").is_some(), "{unknown}"); - // Held while the session lasts, even past the close delay. + // Held (by serve, and by the bridge's own lease) past the close delay. std::thread::sleep(Duration::from_millis(1500)); assert!(home.host().is_some()); // The bridge never uses TCP (no_local_agent_tcp), and TCP is off. @@ -615,7 +679,8 @@ fn the_bridge_opens_closed_books_and_holds_them_for_the_session() { assert!(tcp_sockets(pid).is_empty(), "pid {pid} has TCP sockets"); } assert!(a.end().is_some_and(|s| s.success())); - assert!(home.wait_closed(10)); + // The session's end leaves the host to `serve`, which still holds. + assert!(home.host().is_some(), "serve's host went with a session"); // Unknown books: a plain error, no folder named. let mut a = Agent::start(&home, "nobody"); a.initialize(); @@ -656,6 +721,10 @@ fn the_bridge_answers_initialize_itself_during_a_slow_start() { let home = Home::new("cold"); home.create("acme"); assert!(home.wait_closed(10)); + let _slow = slow_serve( + &home, + "close_after=1500,backoff=50,server_delay=3000,init_wait=300,queue_wait=30000", + ); let mut c = home.cmd("mcp"); c.args([ "--book", @@ -725,6 +794,10 @@ fn the_bridge_gives_up_on_books_that_never_open() { let home = Home::new("never"); home.create("acme"); assert!(home.wait_closed(10)); + let _slow = slow_serve( + &home, + "close_after=800,backoff=50,server_delay=20000,init_wait=200,queue_wait=1000", + ); let mut c = home.cmd("mcp"); c.args([ "--book", @@ -833,17 +906,16 @@ fn closing_during_a_burst_of_posts_through_the_bridge_loses_nothing() { } #[test] -fn the_host_starts_clean_from_a_hostile_bridge() { +fn the_host_serve_starts_is_clean_from_a_hostile_serve() { let home = Home::new("clean"); home.create("acme"); assert!(home.wait_closed(10)); - // A pipe the bridge inherits; the host must not. + // A pipe `serve` inherits; the host it starts must not (start.rs). let (read_end, write_end) = std::io::pipe().unwrap(); use std::os::fd::AsRawFd; let leaked = write_end.as_raw_fd(); - let mut c = home.cmd("mcp"); - c.args(["--book", "acme"]) - .env("XDG_DATA_HOME", "/tmp/wb-evil-data") + let mut c = home.cmd("serve"); + c.env("XDG_DATA_HOME", "/tmp/wb-evil-data") .env("LD_PRELOAD", "/nonexistent/wb-evil.so") .env("WB_EVIL", "1") .env("XDG_RUNTIME_DIR", "/tmp") @@ -861,9 +933,8 @@ fn the_host_starts_clean_from_a_hostile_bridge() { }); } } - let mut a = Agent::from(c); - a.initialize(); - a.call("books.start", json!({})).unwrap(); + let held = Running::start(c); + held.expect("The books are open", 30); let host = home.host().expect("a host"); let environ = std::fs::read(format!("/proc/{host}/environ")).unwrap(); let vars: Vec = environ @@ -915,7 +986,7 @@ fn the_host_starts_clean_from_a_hostile_bridge() { let after = stat.rsplit_once(") ").unwrap().1.to_string(); after.split_whitespace().nth(3).unwrap().to_string() }; - assert_ne!(session(host), session(a.run.child.id())); + assert_ne!(session(host), session(held.child.id())); assert_eq!( session(host), host.to_string(), @@ -1129,6 +1200,9 @@ fn books_commands_hold_the_books_while_they_run() { String::from_utf8_lossy(&out.stdout).contains("No books yet"), "{out:?}" ); + // Held open by `serve`, so what the commands make is open (a command + // with nothing running makes it and lets go: WB-app-5). + home.keep_host(); home.create("acme"); let out = home.books(&["create", "acme"]); assert_eq!(out.status.code(), Some(1)); @@ -1363,6 +1437,10 @@ fn a_call_cancelled_at_once_is_never_made() { let home = Home::new("cancel"); home.create("acme"); assert!(home.wait_closed(10)); + let _slow = slow_serve( + &home, + "close_after=1500,backoff=50,server_delay=1500,init_wait=200,queue_wait=30000", + ); let mut c = home.cmd("mcp"); c.args([ "--book", @@ -1411,7 +1489,11 @@ fn doctor_says_whether_the_books_are_open_and_what_holds_them() { assert!(home.wait_closed(10)); let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).into_owned(); let closed = text(home.cmd("doctor").output().unwrap()); - assert!(closed.contains("The books are closed."), "{closed}"); + assert!( + closed.contains("The books are closed: Wanderbooks isn't running.") + && closed.contains("wanderbooks serve"), + "{closed}" + ); assert!(closed.contains("same_user (advisory)"), "{closed}"); let _held = serve(&home); let open = text(home.cmd("doctor").output().unwrap()); @@ -1434,6 +1516,10 @@ fn a_signalled_bridge_goes_at_once() { let home = Home::new("sigbridge"); home.create("acme"); assert!(home.wait_closed(10)); + let _slow = slow_serve( + &home, + "close_after=1500,backoff=50,server_delay=20000,init_wait=200,queue_wait=30000", + ); let mut c = home.cmd("mcp"); c.args([ "--book", @@ -1661,7 +1747,7 @@ fn a_command_ends_at_its_deadline_during_a_restart() { lock.lock().unwrap(); let started = Instant::now(); let out = home - .cmd("books") + .cmd("token") .args(["list", "--test-knobs", "open_wait=1000,close_after=2500"]) .stdin(Stdio::null()) .output() @@ -1872,6 +1958,10 @@ fn books_made_mid_session_and_bad_requests() { let home2 = Home::new("dupid"); home2.create("acme"); assert!(home2.wait_closed(10)); + let _slow = slow_serve( + &home2, + "close_after=2500,backoff=50,server_delay=2000,init_wait=200,queue_wait=30000", + ); let mut c = home2.cmd("mcp"); c.args([ "--book", @@ -2107,6 +2197,7 @@ fn a_bridge_started_without_stderr_keeps_its_descriptors_apart() { use std::os::unix::process::CommandExt; let home = Home::new("nostderr"); home.create("acme"); + home.keep_host(); let mut c = home.cmd("mcp"); c.args(["--book", "acme"]); // SAFETY: close is async-signal-safe. @@ -2412,6 +2503,7 @@ fn the_commands_given_run_as_the_agents_own_token() { .output() .unwrap(); assert!(out.status.success(), "{out:?}"); + home.keep_host(); let mut c = home.cmd("mcp"); c.args(["--book", "acme", "--token", "bookkeeper"]); let mut a = Agent::from(c); @@ -2711,6 +2803,7 @@ fn an_agent_is_connected_and_reaches_the_books_by_what_it_was_given() { assert!(!said.contains("wb_"), "a token's text was shown"); // The command it was given reaches the books (with the token kept). let given: Vec<&str> = add.split(" -- ").nth(1).unwrap().split(' ').collect(); + home.keep_host(); let mut c = Command::new(given[0]); c.args(&given[1..]) .env_clear() @@ -2808,28 +2901,20 @@ fn books_are_backed_up_now_from_the_command_line() { } /// The viewer's owner (ledger-cli's `ViewerOwner`, over these ledger-host -/// functions): its hold is a lease of kind app; new books are made by the -/// server; "Close the books" ends every lease, the viewer's hold with it. -/// (A `serve` holds the books first: run in this test's process, a hold -/// that had to start the host would start this test's own program.) +/// functions): new books are made by the server that runs (here a `serve` +/// host's; under the app, the app's). The viewer's hold and "Close the +/// books" are gone: the app is the host (WB-app-5). #[test] -fn the_viewers_hold_new_books_and_close_the_books() { - use ledger_host::commands::{Common, close_books, hold_for_viewer, new_books}; +fn the_viewers_new_books_are_made_by_the_server() { + use ledger_host::commands::{Common, new_books}; let home = Home::new("viewer-owner"); home.create("acme"); - let serving = serve(&home); + let _serving = serve(&home); let common = Common { root: Some(home.root()), knobs: ledger_host::knobs::Knobs::parse(KNOBS).unwrap(), ..Default::default() }; - let hold = hold_for_viewer(&common, Some("acme".into())); - assert!( - wait_for(20, || home - .lease_line("{\"proto\":1,\"leases\":null}\n") - .contains("\"app\"")), - "the viewer's lease never showed" - ); assert_eq!( new_books(&common, "beta", "USD").unwrap(), "Made new books \"beta\" (USD)." @@ -2844,18 +2929,6 @@ fn the_viewers_hold_new_books_and_close_the_books() { String::from_utf8_lossy(&out.stdout).contains("beta open"), "{out:?}" ); - let said = close_books(&common).unwrap(); - assert!(said.starts_with("The books are closing"), "{said}"); - // The viewer's hold lets go, for good (closed by the owner). - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let _ = tx.send(hold.join().is_ok()); - }); - assert_eq!(rx.recv_timeout(Duration::from_secs(30)), Ok(true)); - serving.expect("closed", 30); - assert!(home.wait_closed(30)); - // Closed: said so. - assert_eq!(close_books(&common).unwrap(), "The books are closed."); } #[test] diff --git a/crates/ledger-cli/tests/update.rs b/crates/ledger-cli/tests/update.rs index 5c4b1b17..c6e49c13 100644 --- a/crates/ledger-cli/tests/update.rs +++ b/crates/ledger-cli/tests/update.rs @@ -83,6 +83,9 @@ struct Home { /// from an image's mount, and `APPIMAGE` names this other file, the /// one an update replaces. image: Option, + /// The `wanderbooks serve` that holds the books for the test's agents + /// ([`Home::keep_host`]): since P15 only `serve` starts a host. + serving: std::sync::Mutex>, } impl Home { @@ -106,6 +109,7 @@ impl Home { dir, exe, image: None, + serving: std::sync::Mutex::new(None), }; home.runnable(); home @@ -147,6 +151,32 @@ impl Home { } } + /// Hold the books with a `wanderbooks serve` (started again when the + /// last one has ended, as a `close` ends it): the one program that + /// starts a host (WB-app-5). It starts, as a host does, applying a + /// staged update first, and the bridges of the test then lease it. + fn keep_host(&self) { + let mut serving = self.serving.lock().unwrap(); + if let Some(child) = serving.as_mut() + && child.try_wait().unwrap().is_none() + { + return; + } + let child = self + .cmd("serve") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + *serving = Some(child); + let sock = self.root().join("run/mcp.sock"); + assert!( + wait_for(60, || sock.exists()), + "the books never opened under serve" + ); + } + /// The environment of the pretend AppImage, if this is one. fn image_env(&self, c: &mut Command) { if let Some(image) = &self.image { @@ -618,6 +648,7 @@ struct Agent { impl Agent { fn start(home: &Home, book: &str) -> Self { + home.keep_host(); let mut c = home.cmd("mcp"); c.args(["--book", book]); let mut child = c @@ -651,6 +682,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.child.stdin.as_mut().unwrap(); writeln!(stdin, "{message}").unwrap(); stdin.flush().unwrap(); From 6b95ce59adf4d073cbc215e79380bd3dd29e2ef7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 11:34:19 -0700 Subject: [PATCH 05/11] docs: how an assistant and a command reach the books under the app (WB-app-1, 3, 5) WB-app-1 and WB-app-3 lose the permanent run/app-hosted marker; WB-app-5 is new: a command finds what runs, never starts a host, and with nothing running runs a server of its own for the work or says "Start Wanderbooks first", with the table command by command. architecture.md, deploy/README.md and mcp-interface.md say the app is the host and only serve keeps a detached one. Co-Authored-By: Claude Fable 5.2 --- deploy/README.md | 9 +++ docs/architecture.md | 36 ++++++++++-- docs/mcp-interface.md | 13 +++-- docs/spec/claims/app.md | 121 ++++++++++++++++++++++++++++++++-------- 4 files changed, 147 insertions(+), 32 deletions(-) diff --git a/deploy/README.md b/deploy/README.md index fe454b31..8f5641d5 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -203,6 +203,15 @@ door with the token. Logs: journalctl -u wanderbooks-server -f ``` +`serve` is the one program that starts a host: on this machine there is no +app, so an assistant's bridge (`wanderbooks mcp`) reaches the books only +while `serve` runs, and otherwise says in words that Wanderbooks isn't +running and to run `wanderbooks serve`. The owner's commands (`wanderbooks +books …`, `token …`) work with `serve` stopped, running a server of their +own for the length of the work, except those that need a company open +(`books open`/`close`, `upload`, `download`), which say to start +Wanderbooks first. + The server runs no jobs in the background: `serve` holds the books open until systemd stops it. On a stop it finishes the call in progress, makes a last backup and closes (3.9), so `TimeoutStopSec=600` is generous rather diff --git a/docs/architecture.md b/docs/architecture.md index a7c7cb33..afee12cb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,7 +36,7 @@ the specification in `bookspec/` (which never depends on the engine). | `ledger-import` | formats: QuickBooks CSV in; IIF, XLSX, Typst PDFs (statements, the invoice, labels, the audit workpaper) out | `ledger-core`, `ledger-reader` | | `ledger-package` | the shared read-only view over `Store` or `Snapshot` (`PackageBooks`): the CPA package, the 1099 worksheet, the invoice document, Needs attention | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-vault` | | `ledger-mcp` | the books server: the MCP tools (122), resources, the handbook, scopes, the door and the access log, backups' scheduling | all of the above | -| `ledger-host` | the host and its leases, the agent bridge (`wanderbooks mcp`), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` | +| `ledger-host` | the app's books server as the window's child (`app_server`, P15), the headless host and its leases (`serve` alone starts one), the agent bridge (`wanderbooks mcp`, a line to whatever runs), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` | | `ledger-gui` | the viewer: read-only, live, egui, one window with a tab per open company (P15); the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` | | `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, `licenses`, …) and the over-the-wire test suites | everything | | `bookspec/checker`, `bookspec/runner` | the example schema and parser, the rule catalogue, the `Engine` trait; the per-rule runner | nothing of ours (the adapter in `ledger-core`'s tests depends on them) | @@ -432,6 +432,32 @@ inward from the adapter. `just check` runs the bookspec workspace's format, clippy and tests beside the wanderbooks workspace's, so an example cannot rot (P13 step 1). +## How an assistant, or a command, reaches the books (P15, D-77, D-84) + +The desktop app is the host. It starts the books server as its own child +(`ledger-host`'s `app_server.rs`) and closes it by closing its input. No +other program on the desktop starts a detached host: a company is reachable +by an assistant exactly while the app has it open. + +- `wanderbooks mcp --book X` (the bridge) is a line to `run/mcp.sock`. With + the app closed it answers the assistant in words that Wanderbooks isn't + running and how to start it (the app, or `wanderbooks serve` on a computer + with no screen); it is never a host and holds no lease unless a headless + host holds the root. +- The owner's commands (`books`, `token`, `connect`, `doctor`, `close`) find + what holds the root. With the app (or a `serve` host) running they ask its + server. With nothing running, a command that only reads or manages the + books' files runs a server of its own for the length of the work and + closes it, under the same `run/server.lock` and `run/books.lock`; one that + needs a company held open says "Start Wanderbooks first". WB-app-5 has the + table, command by command. +- `wanderbooks serve` keeps the host, its leases, the 10 s close delay, the + scrubbed start, the restart onto a replaced program and the daily update + look, for the headless build (P9a); it is the only program that starts one. +- Nothing marks a root as the app's; whose the books are is read from the + locks and the admin socket. The `run/app-hosted` file an earlier build + wrote is ignored and removed. + ## Self-host: the same server, another account (P9a, D-51) The books can live on a machine the owner controls (plan 3.8). It is the @@ -510,15 +536,17 @@ downgrading is theirs). Anything else (an AppImage, whose file is named by looks at the feed at most once a day (`update_check` knob; the look is noted in `updates/checked`), and only downloads and verifies a newer release into `/updates/staged/`. It never swaps. The staged program - is applied by an opener just before it starts a host (no host runs, so no - call is cut off), after a second check against the key, or by + is applied by `wanderbooks serve` just before it starts its host (no host + runs, so no call is cut off), after a second check against the key, or by `wanderbooks update`, the owner's say-so, which reuses the staged copy. A local release is named in `/updates/feed` (a `file://` address, then the key file), the same rule as `--trusted-key`; - **the owner accepts one in the app**: the viewer reads the staged `meta.json` (`Owner::update_waiting`) and shows a notice with "Update now", and Books has "Check for updates" (`Owner::check_for_updates`) and - "Update to X"; accepting is the host's lease intent `apply_update`, which + "Update to X"; accepting is the headless host's lease intent `apply_update` + (with no host, the program installs the staged copy itself; the desktop app's + own update is an ordinary app update, settled by the packaging unit), which installs the staged copy as `update` does and lets the host's own replaced-program watch restart onto it once no call runs. `books.start` carries the same notice to an agent as `update_waiting`, with a next step diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 65c5ab81..dd58f98d 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -187,8 +187,8 @@ features) is refused before anything is journaled, its error beginning go-ahead, with the owner passphrase, in the app or with `wanderbooks books upgrade ID` at a terminal, and that no tool can. No tool consents: none is offered, and the server takes the go-ahead only on its admin -socket, from the host's lease intent `consent_format_upgrade` (the app's -dialog, `books upgrade`), with the passphrase it checks. Before the +socket, as an admin request from the app's dialog or `books upgrade` (or the +headless host's lease intent `consent_format_upgrade`), with the passphrase it checks. Before the upgrade the server commits the books to their own backup repository and proves the copy holds them exactly (journal, stored files, vault, keys); then one `journal.format_set` declares the whole format, and the same @@ -264,9 +264,12 @@ as it is made. Books are served one way (plan D-44): by the books server, which agents reach through the bridge. -- **Served books** (`wanderbooks server`, started by the host; an agent - connects with `wanderbooks mcp --book ID`, the bridge: stdio to the - agent, the server's socket upstream): every book +- **Served books** (`wanderbooks server`, started by the desktop app as its + child, or by the host `wanderbooks serve` keeps on a headless machine; an + agent connects with `wanderbooks mcp --book ID`, the bridge: stdio to the + agent, the server's socket upstream; with nothing running it answers in + words that Wanderbooks isn't running and to start the app or `wanderbooks + serve`: WB-app-3): every book in the data root that is open (all of them at the start, unless `wanderbooks server --open none|ID[,ID…]` says otherwise; one is opened or closed while the server runs, "Opening and closing one book" below), diff --git a/docs/spec/claims/app.md b/docs/spec/claims/app.md index b3cb4dab..00f8c9cc 100644 --- a/docs/spec/claims/app.md +++ b/docs/spec/claims/app.md @@ -28,14 +28,17 @@ by the window or stopped: one that is alive but not yet ready (opening big companies, or waiting for another server to finish) is waited for, in view; a start that fails, or a window closed before the start has the child, closes the child's input and waits for it, so none is left running that -nothing manages. The `run/app-hosted` marker, written by every start, is -permanent: nothing ever removes it, so a root the app has served is the -app's for good. A headless user who ran the desktop app once on a root sees, -from then on, an agent's bridge (`wanderbooks mcp`) answer "Wanderbooks isn't -running" when no app runs, and not start a host on demand as it did before; -a host they start themselves (`wanderbooks serve`) holds the root and the -bridge uses it as always (WB-app-3). Deleting the marker by hand gives the -root back to the on-demand host. +nothing manages. Nothing marks a root as the app's: an earlier build wrote a permanent +`run/app-hosted` file, which means nothing now and is removed at the next +start of the app's server; a root that has one works as one that does not. +Whose the books are is read from what runs (WB-app-5). The server is in a +process group of its own on Unix, so a Ctrl+C at the terminal the window +was started from reaches the window alone and never closes the books under +an open window; on Windows it breaks away from the job a launcher runs the +window in (and, where that job does not allow it, runs inside it), so a +launcher whose job kills everything in it when the window dies does not kill +the server in the middle of a backup: the window's death reaches it as the +end of its input, and it closes cleanly. *Enforced:* `ledger_host::app_server::AppServer` (`start_in`, `stop`, its drop), `AppHost::start` and `AppHost::stop`, `ANOTHER_HAS_THEM`; the server's own close, ledger-mcp `local::run` (INVARIANT 6). @@ -45,7 +48,10 @@ drop), `AppHost::start` and `AppHost::stop`, `ANOTHER_HAS_THEM`; the server's ow `a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so`, `a_server_that_never_gets_ready_is_stopped_with_the_window_and_not_left_behind`, `a_window_closed_before_the_child_was_stored_stops_the_child`, -`a_late_server_is_waited_for_and_stays_the_windows_to_manage`). +`a_late_server_is_waited_for_and_stays_the_windows_to_manage`, +`a_mark_an_earlier_build_left_is_ignored_and_removed`, +`a_terminal_ctrl_c_reaches_the_window_and_never_the_server`). The Windows +breakaway is checked by type only; no test runs it. **WB-app-2 A tab is a company open in the server.** A company has a tab exactly while the server has it open to assistants: the companies the @@ -81,24 +87,34 @@ request to this same server (`UpgradeFormat`), since there is no host. `an_open_that_did_not_happen_says_why`). **WB-app-3 The bridge speaks to the running app and says so in words.** -`wanderbooks mcp --book X` connects to the root's `run/mcp.sock`. For a -root the app has served (it wrote `run/app-hosted`) with no host holding -it, the bridge holds no lease and starts no host. With the app not -running, every call is answered "Wanderbooks isn't running: start -Wanderbooks and open X."; with the app running but the company not open in -it, "Company X isn't open: open it in Wanderbooks." Neither answer is -final: the call after the app starts, or the company is opened, goes -through, in a session already running. A root no app has served, and any -root a host holds (`wanderbooks serve`, the headless host), behave as they -did: the bridge holds a lease and starts a host. -*Enforced:* `ledger_host::bridge` (`serves_the_app`, `keep_in_app`, -`not_running_words`, `not_open_words`), INVARIANT 12. +`wanderbooks mcp --book X` connects to the root's `run/mcp.sock`. With no +host holding the root (every root but a headless `wanderbooks serve`'s), it +holds no lease and starts no host: no program starts one but `serve`. With +nothing running, every call is answered "Wanderbooks isn't running: start +Wanderbooks and open X (on a computer with no screen, run `wanderbooks +serve`), then try again."; with a server holding the books and no socket yet +(the app opening large companies, or finishing a last backup), "Wanderbooks +is still opening its companies, or finishing the last backup of the last +session: X can be reached in a moment. Try again shortly."; with the app +running but the company not open in it, "Company X isn't open: open it in +Wanderbooks." None is final: the call after the app starts, or the company +is opened, goes through, in a session already running. A root a host holds +(`wanderbooks serve`) is served as it was: the bridge holds a lease on the +host; and when that host goes and nothing takes its place the bridge says +the words above instead of starting another. +*Enforced:* `ledger_host::bridge` (`serves_the_app`, `keep_in_app`, `keep`, +`not_running_words`, `opening_words`, `not_open_words`), INVARIANT 12; +`ledger_host::opener::Opener::hold` (INVARIANTS 6, 7). *Checked:* `ledger-host` bridge tests (`with_the_app_not_running_every_call_is_answered_in_words`, +`with_a_server_still_opening_the_answer_says_so_and_not_that_nothing_runs`, `with_the_app_running_a_company_that_is_not_open_is_said_in_words`, -`a_host_bridge_passes_the_servers_words_on_as_they_are`); +`a_host_bridge_passes_the_servers_words_on_as_they_are`, +`a_root_is_the_line_to_the_app_when_no_host_holds_it`); `ledger-cli` `app_server.rs` (`the_bridge_says_the_app_isnt_running_then_works_once_it_is`: not running, then running with the company closed, then open, then closed -again, then the window closed, in one session, with no host started). +again, then the window closed, in one session, with no host started); +`open_while_held.rs` (`a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder`: +a bridge with nothing running starts no host). **WB-app-4 Closing the window is bounded and visible.** Asked to close, the window stays up and says it is closing the books (finishing what is @@ -121,3 +137,62 @@ their companies. (`a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so`, `a_closing_backup_that_was_not_whole_is_said_when_the_window_closes`, `a_server_that_exits_badly_is_said_when_the_window_closes`). + +**WB-app-5 A command finds what runs, never starts a host, and does its +work or says to start Wanderbooks.** Every `wanderbooks …` command that +needs the books, and the window's own menu work, finds what holds the root: +a host (`wanderbooks serve`: it takes a lease, as before), the app's server +(no host holds the root, a server holds `run/server.lock`, and its admin +socket answers: it asks that server and leaves it running), or nothing. A +server that holds the lock and has no admin socket yet is opening its +companies or finishing a backup: the command says so ("Wanderbooks is still +opening (or closing) the books: waiting for it…") and waits, for as long as +its own wait lasts (`open_wait`, 120 s), then says it is still opening and +to try again; it never fails with a connection error and never starts a +second server beside it. With nothing running, no command starts a host. +One that only reads, or manages the books' files and tokens, runs a books +server of its own, the one the app starts, for the length of the work and +closes it (waiting for its last backup, 90 s at most, and saying so if it +is still finishing); it takes the same `run/server.lock` and `run/books.lock` +the app's server takes, so two programs never hold one set of books, and a +start is refused in words when another has them. One that needs a company +held open by Wanderbooks says "Start Wanderbooks first: nothing has the +books open. Open the Wanderbooks app, or, on a computer with no screen, run +`wanderbooks serve` and leave it running." `wanderbooks serve` is the only +program that starts a detached host (the headless path); it keeps the lease +protocol, the 10 s close delay, the scrubbed environment, the restart onto a +replaced program and its daily look for an update. + +| Command | The app (or `serve`) running | Nothing running | +|---|---|---| +| `books list` | the server's list, open or closed | the folder's companies, "not open", no lock taken (nothing is read of them) | +| `books create`, `adopt`, `restore` | the server does it | its own server, no company open, closed after | +| `books put-aside` | works on the folder itself, as it always has: it never asked a server, and moves only copies outside the root into `legacy/` after reading the company's journal head; it takes no lock | the same | +| `books back-up ID`, `books upgrade ID`, `books extract ID N` | the server does it (the upgrade as an admin request when there is no host) | its own server with ID open, closed after | +| `books open ID`, `books close ID` | the server opens or closes ID | "Start Wanderbooks first" (there is no server to open it in) | +| `token create`, `list`, `check`, `revoke` | the server's admin socket | its own server (ID open when one is named) | +| `token print` | the token file | the token file (it never asked a server) | +| `connect`, the books home | a token as above, the pointer file | the same, its own server for the token | +| `upload`, `download` | the book's door, with the token's file | "Start Wanderbooks first" | +| `doctor` | says whose the books are and lists them, tokens and assistants | says the books are closed and Wanderbooks isn't running, and how to start it | +| `close` | on a host, closes the books; on the app, says the app's tabs and window do | "already closed" | +| `serve` | on the app, refuses ("the app has these books open"); on a host, joins it | starts the host | +| `mcp` | the bridge (WB-app-3) | the bridge says it in words | + +There is no "Close the books" in the app: closing a company's tab closes +the company (WB-app-2) and closing the window closes them all (WB-app-4). +*Enforced:* `ledger_host::opener::Opener::hold` (`HoldError::NotRunning`, +`admin_answers`), `ledger_host::commands` (`direct_for`, `reach`, +`Reached::release`, `listed_while_closed`, `upgrade_by_admin`, `doctor`, +`close`). +*Checked:* `ledger-cli` `app_server.rs` +(`a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running`, +`with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks`, +`a_command_waits_in_words_for_a_server_that_is_still_opening`); +`open_while_held.rs` (`a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder`, +`serve_and_the_bridges_share_one_host_and_one_server`, +`books_commands_hold_the_books_while_they_run`, +`a_command_ends_at_its_deadline_during_a_restart`, +`the_viewers_new_books_are_made_by_the_server`); +`format_upgrade.rs` (`format_upgrade_waits_for_consent`: a command's own +server shows the upgrade its company waits for). From 2ff2913274de5801ee80f2af7566ae671eb65f83 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:12:28 -0700 Subject: [PATCH 06/11] fix(host): what holds the books is known, not guessed; a command joins what starts beside it Plan P15 unit A5, fix round. A server answering its admin socket with no host over it was taken to be "the app". Three wrong outcomes followed: a `serve` started while a killed host's server was still finishing its last backup was told "the app has these books open" and exited, `close` and `doctor` said "the app" during such a close, and a command attached to another command's short-lived server as if it were the app (refused "not open" for another company, or its server closed under the other). A server now says what it is. `wanderbooks server --started-by app|host|command` writes run/server.info beside its lock (who started it, its pid, whether it has begun to close), moved into place whole as soon as the lock is its, rewritten `closing` the moment it is told to close, removed just before the lock goes. It is read only while the lock is held, which is when it is the lock holder's. A file beside the lock, not a field in the admin hello: it also covers a server that has no admin socket yet (opening) and costs the older admin protocol nothing. A server that says nothing (an earlier build's) is taken for the app's, as before. `opener::what_holds` reads it: only a server the app started, not closing and answering, is the app. A command's server, or one that is closing (the app's, or the orphan of a host that went), is waited for, said in words, bounded by `open_wait` (a bridge waits as long as its session does), and the holder or command goes on once it is gone. `close`, `doctor` and the bridge say the true thing for each. A command racing another program's start no longer fails with "close it" or waits silently 300 s: if its own server loses the lock to a program that started after its look, it lets its start go and joins what runs (`wait_ready_unless_beaten`, `reach`), inside one `open_wait`. A command's own server is started clean, as a host is: the host's environment only, the root as an absolute path, `/` as its folder (Windows: `run/`), and every server closes the descriptors above 2 at its start, so one that outlives its command (still closing after 90 s) holds none of the invoker's pipes. The app's own child keeps its environment: it is the window's child, closes with the window and needs the user's session (ssh agent, git configuration) for backups; it too loses stray descriptors, since the server does that for any starter. Test knobs: `--start-delay` (a server's slow start) and `timer_hold=1` for a command's own server, following `--timer-hold`. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 4 + crates/ledger-host/src/app_server.rs | 120 +++++++++++++++++- crates/ledger-host/src/bridge.rs | 33 ++++- crates/ledger-host/src/commands.rs | 153 +++++++++++++++++------ crates/ledger-host/src/host.rs | 13 +- crates/ledger-host/src/knobs.rs | 10 ++ crates/ledger-host/src/opener.rs | 180 ++++++++++++++++++++++----- crates/ledger-host/src/start.rs | 18 +++ crates/ledger-mcp/src/local.rs | 147 ++++++++++++++++++++++ 9 files changed, 598 insertions(+), 80 deletions(-) diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index ad72abe7..59540690 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -473,6 +473,10 @@ fn owner_passphrase(root: &ledger_store::root::Root) -> i32 { /// `wanderbooks server`: the books server for the data root, on its /// local sockets (plan 3.9). The host starts it. fn run_server(args: Vec) -> i32 { + // Whoever started the server, it holds none of that program's pipes or + // sockets: a server still closing after its starter has gone must not + // keep them open. + ledger_host::host::close_stray_descriptors(); match ledger_mcp::local::run("wanderbooks server", args) { Ok(()) => 0, Err(e) => match e.downcast_ref::() { diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index dee59f23..2727d5ea 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -80,6 +80,7 @@ use crate::host::{SERVER_LOG, children_executable, open_log}; use crate::opener::{host_lock_held, server_lock_held}; use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response}; +pub use ledger_mcp::local::StartedBy; use ledger_store::root::Root; use std::io::BufRead; use std::path::{Path, PathBuf}; @@ -102,6 +103,19 @@ pub const READY_WAIT: Duration = Duration::from_secs(300); /// and running calls finish first. pub const STOP_WAIT: Duration = Duration::from_secs(90); +/// How long another program holding the books, while this server has not +/// taken them, is seen before this one is taken to have lost the race. +const BEATEN_AFTER: Duration = Duration::from_millis(300); + +/// What [`AppServer::wait_ready_unless_beaten`] came to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Waited { + /// The server is ready. + Ready, + /// Another program took the books first. + Beaten, +} + /// What a refused start says (INVARIANT 1). pub const ANOTHER_HAS_THEM: &str = "Another program has these books open: another Wanderbooks window, `wanderbooks serve`, or a books server that is still finishing its last backup. Close it (`wanderbooks close` closes the books) or wait a moment, then start Wanderbooks again."; @@ -217,7 +231,7 @@ pub struct AppServer { /// now: no host holds the root, a server does, and its admin socket /// answers (INVARIANT 7). pub fn the_apps_server_runs(run: &Path) -> bool { - !host_lock_held(run) && server_lock_held(run) && crate::opener::admin_answers(run) == Ok(true) + crate::opener::what_holds(run) == Ok(crate::opener::Holder::App) } impl AppServer { @@ -229,6 +243,38 @@ impl AppServer { Self::start_in(&children_executable(), root, open, |_| {}) } + /// The server of a command that does its own work with nothing else + /// running (commands.rs `reach`): the same server, started clean as a + /// host starts it (INVARIANT 13), saying it is a command's. + pub fn start_for_command( + root: Option<&Path>, + open: &[String], + knobs: &crate::knobs::Knobs, + ) -> Result { + let d = crate::knobs::Knobs::default(); + Self::start_as( + &children_executable(), + root, + open, + StartedBy::Command, + |command| { + // The timings a test shortened, as the host passes them on. + for (flag, now, default) in [ + ("--backup-quiet", knobs.backup_quiet, d.backup_quiet), + ("--drill-first", knobs.drill_first, d.drill_first), + ("--start-delay", knobs.server_delay, d.server_delay), + ] { + if now != default { + command.arg(flag).arg(now.as_millis().to_string()); + } + } + if knobs.timer_hold { + command.arg("--timer-hold"); + } + }, + ) + } + /// [`AppServer::start`] from the program `exe`, `configure` having the /// last word on its command (tests give it an environment of its own). pub fn start_in( @@ -236,6 +282,19 @@ impl AppServer { root: Option<&Path>, open: &[String], configure: impl FnOnce(&mut Command), + ) -> Result { + Self::start_as(exe, root, open, StartedBy::App, configure) + } + + /// [`AppServer::start_in`] for a server started `by` the app or a + /// command, which it says of itself (`--started-by`, INVARIANT 13). + /// A command's is started clean (INVARIANT 13). + pub fn start_as( + exe: &Path, + root: Option<&Path>, + open: &[String], + by: StartedBy, + configure: impl FnOnce(&mut Command), ) -> Result { let found = Root::find(root).map_err(|e| e.to_string())?; let run = found.run_dir().map_err(|e| e.to_string())?; @@ -259,7 +318,20 @@ impl AppServer { command.process_group(0); } command.arg("server"); - if let Some(root) = root { + command.arg("--started-by").arg(by.flag()); + if by == StartedBy::Command { + // Nothing of the invoker's reaches a server that may outlive + // the command (INVARIANT 13): the host's environment, and a + // folder of its own to stand in (the root's absolute path + // goes on, as the host's does). Its descriptors are closed by + // the server itself at its start. + command.arg("--root").arg(found.path()); + crate::start::clean_environment(&mut command)?; + #[cfg(unix)] + command.current_dir("/"); + #[cfg(windows)] + command.current_dir(&run); + } else if let Some(root) = root { command.arg("--root").arg(root); } command.arg("--open").arg(open_argument(open)); @@ -364,6 +436,50 @@ impl AppServer { } } + /// Wait for the server to be ready, up to `within`, but not for + /// another program that took the books first: if, while this server + /// is not ready, a host or another server holds them (a command racing + /// the app's start, or `serve`'s), this one has lost the race and the + /// caller is to join what runs (commands.rs `reach`). Seen for as long + /// as [`BEATEN_AFTER`], so the moment between this server taking the + /// lock and saying so is not taken for losing. + pub fn wait_ready_unless_beaten(&self, within: Duration) -> Result { + let deadline = Instant::now() + within; + let mut beaten_since: Option = None; + loop { + let slice = Duration::from_millis(50).min( + deadline + .checked_duration_since(Instant::now()) + .unwrap_or_default(), + ); + match self.wait_ready(slice) { + Ok(()) => return Ok(Waited::Ready), + Err(why) if self.exited().is_some() => return Err(why), + Err(why) => { + if Instant::now() >= deadline { + return Err(why); + } + } + } + if self.another_holds() { + let since = *beaten_since.get_or_insert_with(Instant::now); + if since.elapsed() >= BEATEN_AFTER { + return Ok(Waited::Beaten); + } + } else { + beaten_since = None; + } + } + } + + /// Whether a host, or a server that is not this one, holds the books. + fn another_holds(&self) -> bool { + host_lock_held(&self.run) + || (server_lock_held(&self.run) + && ledger_mcp::local::read_server_info(&self.run) + .is_none_or(|info| info.pid != self.pid)) + } + /// Whether the server has said it is ready (and is still there). pub fn is_ready(&self) -> bool { matches!(&*self.shared.phase(), Phase::Ready) diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 6cda67f8..ae9486f9 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -119,6 +119,15 @@ fn opening_words(book: &str) -> String { ) } +/// What the agent is told when a command of the owner's has the books for +/// a moment (a server of its own, for the length of its work): the app is +/// not running, and it is not that either. +fn command_words(book: &str) -> String { + format!( + "A wanderbooks command has the books for a moment: {book} can be reached in a moment. Try again shortly." + ) +} + /// What the agent is told when the app runs but the company is not open /// in it (INVARIANT 12). fn not_open_words(book: &str) -> String { @@ -1106,7 +1115,19 @@ impl Bridge { let mut epoch = 0u64; loop { if matches!(&*self.link.borrow(), Link::Opening) { - match self.socket_is_ours() { + // What holds the books is read before a session is tried + // (opener.rs INVARIANT 6a): a command's server, or one + // that is closing, is not the app, whatever its socket + // answers. + let held = + crate::opener::what_holds(&run_dir).unwrap_or(crate::opener::Holder::Nothing); + let owner_check = match held { + crate::opener::Holder::Command | crate::opener::Holder::Closing => { + Err(Owner::Unreachable) + } + _ => self.socket_is_ours(), + }; + match owner_check { Err(Owner::Other(why)) => { self.link.send_replace(Link::Failed(why)); return; @@ -1114,10 +1135,12 @@ impl Bridge { Err(Owner::Unreachable) => { // A server holding the books with no socket yet is // opening (or finishing), not absent. - let words = if crate::opener::server_lock_held(&run_dir) { - opening_words(&self.book) - } else { - not_running_words(&self.book) + let words = match held { + crate::opener::Holder::Command => command_words(&self.book), + _ if crate::opener::server_lock_held(&run_dir) => { + opening_words(&self.book) + } + _ => not_running_words(&self.book), }; self.link.send_replace(Link::Refused(words)); } diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index c54c8285..78611be3 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -55,7 +55,7 @@ use crate::knobs::{FLAG, Knobs}; use crate::lease::{Ask, HostMsg, Intent, Kind, Reason}; -use crate::opener::{HoldError, Lease, Opener}; +use crate::opener::{HoldError, Holder, Lease, Opener}; use ledger_mcp::admin::{self, Request, Response}; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -116,12 +116,20 @@ fn exit(code: i32) -> Box { /// Hold the books and wait until they are open (INVARIANT 1). async fn open(opener: &mut Opener) -> Result { - let deadline = tokio::time::Instant::now() + opener.knobs().open_wait; + // One bounded wait for the whole command: the deadline a caller set + // (`reach`), else `open_wait` from now. The opener's own waits for + // another program's server (WB-app-5) end at it with their own words; + // the timeout here is a moment later, for what has none. + let deadline = opener + .deadline() + .unwrap_or_else(|| tokio::time::Instant::now() + opener.knobs().open_wait); + opener.wait_until(deadline); + let grace = Duration::from_millis(500); let too_long = || -> HoldError { "the books didn't open in time (Wanderbooks may still be opening a large company: try again in a moment): run `wanderbooks doctor` to see why".into() }; loop { - let mut lease = tokio::time::timeout_at(deadline, opener.hold()) + let mut lease = tokio::time::timeout_at(deadline + grace, opener.hold()) .await .map_err(|_| too_long())??; loop { @@ -254,33 +262,78 @@ impl Reached { /// Hold the books for a command, or, with nothing running and the work /// one `direct` allows, run a server of its own (WB-app-5). +/// +/// Whatever is found is joined: a host, the app's server, and, once its +/// work is done, a command's server or a closing one is waited for. A +/// program that takes the books between the look and the command's own +/// server taking them (the app starting, `serve`, another command) is +/// joined too: the command's server has not got them, it lets go of its +/// start and looks again. One wait covers all of it, `open_wait`, said in +/// words (`Opener::hold` says what it waits for). async fn reach(opener: &mut Opener, common: &Common, direct: &Direct) -> Result { let run_dir = opener.run_dir().to_path_buf(); - match open(opener).await { - Ok(lease) => Ok(Reached { - run_dir, - lease: Some(lease), - own: None, - }), - Err(HoldError::NotRunning) => { - let Direct::With(books) = direct else { - return Err(crate::opener::START_WANDERBOOKS.to_string()); + let deadline = tokio::time::Instant::now() + opener.knobs().open_wait; + opener.wait_until(deadline); + let mut said = false; + loop { + match open(opener).await { + Ok(lease) => { + return Ok(Reached { + run_dir, + lease: Some(lease), + own: None, + }); + } + Err(HoldError::NotRunning) => {} + Err(e) => return Err(hold_words(e)), + } + let Direct::With(books) = direct else { + return Err(crate::opener::START_WANDERBOOKS.to_string()); + }; + let (root, books, knobs) = (common.root.clone(), books.clone(), common.knobs); + let started = tokio::task::spawn_blocking(move || { + let server = match crate::app_server::AppServer::start_for_command( + root.as_deref(), + &books, + &knobs, + ) { + Ok(server) => server, + // Another program took the books since the look. + Err(why) if why == crate::app_server::ANOTHER_HAS_THEM => { + return Ok(None); + } + Err(why) => return Err(why), }; - let (root, books) = (common.root.clone(), books.clone()); - let own = tokio::task::spawn_blocking(move || { - let server = crate::app_server::AppServer::start(root.as_deref(), &books)?; - server.wait_ready(crate::app_server::READY_WAIT)?; - Ok::<_, String>(server) - }) - .await - .map_err(|e| e.to_string())??; - Ok(Reached { + match server.wait_ready_unless_beaten(crate::app_server::READY_WAIT)? { + crate::app_server::Waited::Ready => Ok(Some(server)), + // Another program took them first: this one's start is let + // go of (it has not opened anything), and what runs is + // looked at again. + crate::app_server::Waited::Beaten => { + server.stop(Duration::from_secs(10)); + Ok(None) + } + } + }) + .await + .map_err(|e| e.to_string())??; + if let Some(own) = started { + return Ok(Reached { run_dir, lease: None, own: Some(std::sync::Arc::new(own)), - }) + }); } - Err(e) => Err(hold_words(e)), + if tokio::time::Instant::now() >= deadline { + return Err(format!( + "Other programs kept the books for {} s while this command waited: try again in a moment (`wanderbooks doctor` says what has them).", + opener.knobs().open_wait.as_secs() + )); + } + if !std::mem::replace(&mut said, true) { + eprintln!("Another program started the books just now: waiting for it…"); + } + tokio::time::sleep(Duration::from_millis(50)).await; } } @@ -359,6 +412,23 @@ fn past(deadline: std::time::Instant, now: std::time::Instant) -> bool { now > deadline } +/// What is said of a server that is not the app's, in the words of its +/// own state (`close`, `doctor`): never "the app" for what is not. +fn held_words(holder: Holder) -> &'static str { + match holder { + Holder::Command => { + "A wanderbooks command has the books open for a moment: they close when its work is done." + } + Holder::Closing => "The books are closing: a books server is finishing its last backups.", + Holder::Opening => { + "Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet." + } + Holder::Host | Holder::App | Holder::Nothing => { + "The books are held: `wanderbooks doctor` says by what." + } + } +} + /// What `doctor` says of books no host holds. fn no_host(server_lock_held: bool) -> &'static str { if server_lock_held { @@ -569,16 +639,18 @@ pub fn close( exit(1) })?; match asked { - None if crate::app_server::the_apps_server_runs(&run) => { - println!("{APP_HAS_THEM}."); - Ok(()) - } - None if crate::opener::server_lock_held(&run) => { - println!("The books are closing: a books server is finishing its last call."); - Ok(()) - } + // No host: what holds the books is read (WB-app-5), so what is + // said of it is true. None => { - println!("The books are already closed."); + match crate::opener::what_holds(&run) { + Ok(Holder::App) => println!("{APP_HAS_THEM}."), + Ok(Holder::Nothing) => println!("The books are already closed."), + Ok(other) => println!("{}", held_words(other)), + Err(why) => { + eprintln!("error: {why}"); + return Err(exit(1)); + } + } Ok(()) } Some(HostMsg::Done { .. }) => { @@ -2995,14 +3067,15 @@ pub fn doctor( match crate::opener::ask_once_within(&run, Ask::Leases, DOCTOR_WAIT) { // No host: the app's server (or another that runs without one), // one still opening or finishing, or nothing (WB-app-3). - Ok(None) if crate::app_server::the_apps_server_runs(&run) => { - println!("The books are open: Wanderbooks (the app) has them."); - admin_report(&run); - } - Ok(None) if crate::opener::server_lock_held(&run) => println!( - "Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet." - ), - Ok(None) => println!("{}", no_host(false)), + Ok(None) => match crate::opener::what_holds(&run) { + Ok(Holder::App) => { + println!("The books are open: Wanderbooks (the app) has them."); + admin_report(&run); + } + Ok(Holder::Nothing) => println!("{}", no_host(false)), + Ok(other) => println!("{}", held_words(other)), + Err(why) => println!("The books server can't be asked: {why}"), + }, Ok(Some(HostMsg::Leases { ready, leases })) => { if ready { println!("The books are open."); diff --git a/crates/ledger-host/src/host.rs b/crates/ledger-host/src/host.rs index 16e29dcf..fe0d1298 100644 --- a/crates/ledger-host/src/host.rs +++ b/crates/ledger-host/src/host.rs @@ -94,11 +94,13 @@ pub(crate) fn private_options() -> std::fs::OpenOptions { /// Windows passes no descriptor to a child unless asked to, so there is /// nothing to close (INVARIANT 2). #[cfg(not(unix))] -fn close_stray_descriptors() {} +pub fn close_stray_descriptors() {} -/// Close every descriptor above 2 (INVARIANT 2). +/// Close every descriptor above 2 (INVARIANT 2). The host does it at its +/// start, and so does every books server (`wanderbooks server`), whoever +/// started it: it holds none of its starter's pipes or sockets. #[cfg(unix)] -fn close_stray_descriptors() { +pub fn close_stray_descriptors() { #[cfg(target_os = "linux")] { // SAFETY: close_range only closes descriptors; nothing is open @@ -765,6 +767,11 @@ impl Host { #[cfg(unix)] command.arg0("wanderbooks"); command.arg("server"); + // Said in its `run/server.info`: this host's, so that one found + // with no host is known to be an orphan finishing (opener.rs). + command + .arg("--started-by") + .arg(ledger_mcp::local::StartedBy::Host.flag()); if self.explicit_root { command.arg("--root").arg(self.root.path()); } diff --git a/crates/ledger-host/src/knobs.rs b/crates/ledger-host/src/knobs.rs index bd7dd0c1..d1d2be46 100644 --- a/crates/ledger-host/src/knobs.rs +++ b/crates/ledger-host/src/knobs.rs @@ -36,6 +36,11 @@ pub struct Knobs { /// How long between the host's looks for a newer release (plan /// P11a step 4: a day). pub update_check: Duration, + /// A command's own server holds the jobs it runs inside their phases + /// while `run/timer-hold` names them (the server's `--timer-hold`; + /// tests of what a command holds while it works). Given as + /// `timer_hold=1`. + pub timer_hold: bool, } impl Default for Knobs { @@ -51,6 +56,7 @@ impl Default for Knobs { backup_quiet: Duration::from_secs(30), drill_first: Duration::from_secs(60), update_check: Duration::from_secs(24 * 60 * 60), + timer_hold: false, } } } @@ -81,6 +87,7 @@ impl Knobs { "backup_quiet" => k.backup_quiet = d, "drill_first" => k.drill_first = d, "update_check" => k.update_check = d, + "timer_hold" => k.timer_hold = ms != 0, other => return Err(format!("{FLAG}: there is no knob {other:?}")), } } @@ -108,6 +115,9 @@ impl Knobs { parts.push(format!("{name}={}", now.as_millis())); } } + if self.timer_hold { + parts.push("timer_hold=1".to_string()); + } (!parts.is_empty()).then(|| parts.join(",")) } diff --git a/crates/ledger-host/src/opener.rs b/crates/ledger-host/src/opener.rs index b5f468d5..ed019d33 100644 --- a/crates/ledger-host/src/opener.rs +++ b/crates/ledger-host/src/opener.rs @@ -39,6 +39,17 @@ //! books. The server's lock held and no admin socket yet is a server //! still opening its companies (or finishing its last backup): the //! holder waits for it, in words, for as long as its own wait lasts. +//! 6a. What holds the books is known, not guessed: a server says what +//! started it and whether it is closing (`run/server.info`, ledger-mcp +//! local.rs INVARIANT 16) and [`what_holds`] reads it. Only a server +//! the app started, not closing, is "the app". A server a command +//! started, a closing server (the app's, or the orphan of a host +//! that was killed), is waited for: the holder says so, in words, and +//! goes on once it is gone, for as long as its own wait lasts +//! (`open_wait`, 120 s; a bridge waits as long as the session does), +//! then says in words what it is still waiting for. A server that +//! says nothing (an earlier build's) is taken for the app's, as it +//! was before. //! 7. No host, no server: only `wanderbooks serve` starts a host (the //! headless path, plan 3.1). Every other holder is turned away with //! [`HoldError::NotRunning`], and says, in words, to start @@ -62,6 +73,9 @@ const START_WAIT: Duration = Duration::from_secs(45); const LOCK_WAIT: Duration = Duration::from_secs(2); /// How long the host has to answer a hello. const ANSWER_WAIT: Duration = Duration::from_secs(10); +/// How long `hold` looks again while it waits for a server that is +/// closing or a command's (INVARIANT 6a). +const WAIT_LOOK: Duration = Duration::from_millis(100); /// Tries after a failure before giving up (INVARIANT 3). pub const MAX_TRIES: u32 = 5; /// How long the books must stay open for earlier failures to be @@ -128,6 +142,10 @@ pub struct Opener { /// Flags the server this opener starts is started with (P9a): /// `--isolation` and `--http`. Empty for every ordinary holder. server_flags: Vec, + /// Until when a wait for another program's server lasts (INVARIANT + /// 6a); the caller's own deadline, else `open_wait` from the first + /// wait. A bridge has none. + deadline: Option, } /// A held lease: the books stay open while it lives. @@ -193,9 +211,21 @@ impl Opener { opened_at: None, has_held: false, server_flags: Vec::new(), + deadline: None, }) } + /// Wait for another program's server (a command's, or one closing) no + /// longer than until `deadline` (INVARIANT 6a). + pub fn wait_until(&mut self, deadline: Instant) { + self.deadline = Some(deadline); + } + + /// The deadline set by [`Opener::wait_until`], if any. + pub fn deadline(&self) -> Option { + self.deadline + } + /// Start the server this opener brings up with these flags (P9a: /// `--isolation`, `--http`). Only `serve` uses it: on the owner's own /// machine it is the one holder, so the host it starts is the server's @@ -244,39 +274,54 @@ impl Opener { pub async fn hold(&mut self) -> Result { let mut started: Option = None; let mut said_waiting = false; + let mut waited_from: Option = None; loop { - // The app has the books: its own server serves them, and no - // host is started beside it (INVARIANT 6). - if !host_lock_held(&self.run) && server_lock_held(&self.run) { - match admin_answers(&self.run) { - Ok(true) => { - if self.kind == Kind::Serve { - return Err(HoldError::Failed( - "Wanderbooks (the app) has these books open: close it first, or use it" - .into(), - )); - } - self.has_held = true; - return Ok(Lease { - id: 0, - link: None, - told_ready: false, - }); + // What holds the books is read, not guessed (INVARIANT 6a). + match what_holds(&self.run)? { + // The app has the books: its own server serves them, and + // no host is started beside it (INVARIANT 6). + Holder::App => { + if self.kind == Kind::Serve { + return Err(HoldError::Failed( + "Wanderbooks (the app) has these books open: close it first, or use it" + .into(), + )); } - Ok(false) => { - // Opening its companies, or finishing its last - // backup: wait for it, and say so once. - if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge - { - eprintln!( - "Wanderbooks is still opening (or closing) the books: waiting for it…" - ); - } - tokio::time::sleep(Duration::from_millis(100)).await; - continue; - } - Err(why) => return Err(HoldError::Failed(why)), + self.has_held = true; + return Ok(Lease { + id: 0, + link: None, + told_ready: false, + }); } + // Opening its companies, or finishing its last backup: + // wait for it, and say so once. + Holder::Opening => { + if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge { + eprintln!( + "Wanderbooks is still opening (or closing) the books: waiting for it…" + ); + } + tokio::time::sleep(WAIT_LOOK).await; + continue; + } + // A command's server, or one closing: it ends soon, and + // the books are free; wait for it, bounded (INVARIANT 6a). + held @ (Holder::Command | Holder::Closing) => { + let from = *waited_from.get_or_insert_with(Instant::now); + if self.kind != Kind::Bridge { + let until = self.deadline.unwrap_or_else(|| from + self.knobs.open_wait); + if Instant::now() >= until { + return Err(HoldError::Failed(held.still_waiting_words())); + } + } + if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge { + eprintln!("{}", held.waiting_words()); + } + tokio::time::sleep(WAIT_LOOK).await; + continue; + } + Holder::Host | Holder::Nothing => {} } wait_for_restart(&self.run).await; let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET) @@ -457,6 +502,80 @@ pub fn host_lock_held(run: &Path) -> bool { } } +/// What holds the books now, read from the locks, the server's own word +/// about itself and its admin socket (INVARIANT 6a). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Holder { + /// Nothing: no host, no server. + Nothing, + /// A host holds `run/host.lock` (`wanderbooks serve`'s, or an earlier + /// build's): leases go to it. + Host, + /// The app's server, not closing, answering: no host behind it. + App, + /// A server the app started (or an earlier build's, which says + /// nothing of itself) that is not answering yet: opening its + /// companies, or finishing its last backup. + Opening, + /// A server a command started, for the length of its work. + Command, + /// A server that has begun to close (the app's, or the orphan of a + /// host that went): finishing its last backups. + Closing, +} + +impl Holder { + /// What is said while waiting for this to finish (INVARIANT 6a). + pub fn waiting_words(self) -> &'static str { + match self { + Holder::Command => { + "Another wanderbooks command has the books open for a moment: waiting for it to finish…" + } + _ => { + "Wanderbooks is closing the books (a last backup is being made): waiting for it to finish…" + } + } + } + + /// What is said when the wait ran out (INVARIANT 6a). + pub fn still_waiting_words(self) -> String { + match self { + Holder::Command => "Another wanderbooks command still has the books open after waiting for it: try again in a moment (`wanderbooks doctor` says what has them).".into(), + _ => "Wanderbooks is still closing the books after waiting for it (a last backup is still being made): try again in a moment.".into(), + } + } +} + +/// What holds the books of the root whose `run/` folder this is +/// (INVARIANT 6a). `Err` in words when the server's socket is another +/// account's. +pub fn what_holds(run: &Path) -> Result { + use ledger_mcp::local::StartedBy; + if host_lock_held(run) { + return Ok(Holder::Host); + } + if !server_lock_held(run) { + return Ok(Holder::Nothing); + } + let info = ledger_mcp::local::read_server_info(run); + Ok(match info { + Some(i) if i.closing => Holder::Closing, + Some(i) if i.by == StartedBy::Command => Holder::Command, + // No host holds the books, so a server a host started is the + // orphan of one that went: it is closing, as its input ended. + Some(i) if i.by == StartedBy::Host => Holder::Closing, + // The app's, or one that says nothing (an earlier build's, or a + // newer one's, a moment before it writes its word). + Some(_) | None => { + if admin_answers(run)? { + Holder::App + } else { + Holder::Opening + } + } + }) +} + /// Whether the admin socket answers: the books server is up and ready /// (it binds its sockets only once every company has been tried). A /// socket of another account is an error. @@ -569,6 +688,7 @@ mod tests { opened_at: None, has_held: false, server_flags: Vec::new(), + deadline: None, }; for _ in 0..MAX_TRIES { o.failed().await.unwrap(); diff --git a/crates/ledger-host/src/start.rs b/crates/ledger-host/src/start.rs index 45f2f9ae..47690f43 100644 --- a/crates/ledger-host/src/start.rs +++ b/crates/ledger-host/src/start.rs @@ -258,6 +258,24 @@ fn host_env( env } +/// Give `command` the environment a host has (INVARIANT 1) and nothing of +/// this process's: the books server a command runs for itself is started +/// so, as the host's own is, since it may outlive the command that +/// started it (commands.rs `reach`). +pub(crate) fn clean_environment(command: &mut Command) -> Result<(), String> { + let home = ledger_store::root::account_home().map_err(|e| e.to_string())?; + command.env_clear(); + #[cfg(unix)] + command.envs(host_env( + &home, + std::env::var_os("SSH_AUTH_SOCK").as_deref(), + this_appimage().as_ref(), + )); + #[cfg(windows)] + command.envs(host_env(&home)); + Ok(()) +} + #[cfg(unix)] /// Whether this process sits in a unit under this account's user manager /// (an app's scope or service, as uwsm makes for every app), whose stop diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 4aed2d6b..78ff4ec7 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -311,6 +311,16 @@ //! request that arrives once the server is closing and finds a book's //! door shut is refused as closing (503, `closing`), not recorded: //! the door is shut (INVARIANT 11), as in a close of one book. +//! 16. A server says what it is, beside its lock (`run/server.info`), +//! when it is started with `--started-by`: who started it (the app, +//! a `serve` host, or a command that runs one for the length of its +//! work), its process id, and whether it has begun to close. The +//! file is written whole and moved into place as soon as the lock is +//! the server's, rewritten with `closing` the moment it is told to +//! close, and removed just before the lock is let go; it is read only +//! while the lock is held, which is when it is the lock holder's. A +//! program that finds a server holding the books reads it before it +//! decides what that server is. //! SCENARIOS: //! 1. Two books open; one is closed while agents call both: the other //! answers throughout, the closed one's calls are refused unrun @@ -414,6 +424,90 @@ pub const ADMIN_SOCKET: &str = "admin.sock"; pub const SERVER_LOCK: &str = "server.lock"; /// What the server prints on stdout when it is ready (INVARIANT 5). pub const READY: &str = "ready"; +/// What a server says of itself, beside its lock: who started it, and +/// whether it has begun to close (INVARIANT 16). +pub const SERVER_INFO: &str = "server.info"; + +/// Who started a server (INVARIANT 16): the program a caller finds holding +/// the books decides what to do from it, and so the words it says are the +/// true ones. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StartedBy { + /// The desktop app: the books server is its child, for as long as its + /// window runs. + App, + /// A `wanderbooks serve` host: the host holds `run/host.lock` as long + /// as it lives, so a server of its starting that is found with no host + /// is an orphan, closing. + Host, + /// A command that runs a server of its own for the length of its work. + Command, +} + +impl StartedBy { + /// The flag value (`--started-by`). + pub fn flag(self) -> &'static str { + match self { + StartedBy::App => "app", + StartedBy::Host => "host", + StartedBy::Command => "command", + } + } + + fn parse(value: &str) -> Result { + match value { + "app" => Ok(StartedBy::App), + "host" => Ok(StartedBy::Host), + "command" => Ok(StartedBy::Command), + other => Err(format!( + "--started-by takes app, host or command, not {other}" + )), + } + } +} + +/// What a server says of itself in `run/server.info` (INVARIANT 16). +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ServerInfo { + /// Who started it. + pub by: StartedBy, + /// Its process id. + pub pid: u32, + /// It has begun to close: running calls finish, the last backups are + /// made. It still answers its admin socket until it is gone. + pub closing: bool, +} + +/// What the server holding `run/server.lock` says of itself: `None` when +/// there is no such file, or it is not (yet) readable: a server of an +/// earlier build says nothing, and a starting one says it just after it +/// takes the lock. Only meaningful while that lock is held. +pub fn read_server_info(run: &Path) -> Option { + let text = std::fs::read_to_string(run.join(SERVER_INFO)).ok()?; + serde_json::from_str(&text).ok() +} + +/// Say what this server is (INVARIANT 16): written whole beside the lock +/// and moved into place, so a reader sees one version or the other. +fn write_server_info(run: &Path, info: &ServerInfo) -> std::io::Result<()> { + let text = serde_json::to_string(info).map_err(std::io::Error::other)?; + let temp = run.join(format!("{SERVER_INFO}.{}.tmp", info.pid)); + std::fs::write(&temp, text)?; + std::fs::rename(&temp, run.join(SERVER_INFO)).inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }) +} + +/// Removes `run/server.info` when the server is done with it, before the +/// lock goes (INVARIANT 16). +struct InfoGuard(PathBuf); + +impl Drop for InfoGuard { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} /// How large an MCP request may be (plan 3.2): files come only through /// uploads (`/b/{book}/u/{upload}`), never in a request (D-46). @@ -3220,6 +3314,9 @@ fn print_usage(prog: &str) { eprintln!(" --http [ADDR]: also serve the MCP door on loopback only (default"); eprintln!(" 127.0.0.1:7411), for a TLS proxy or a tunnel in front of it. Off unless"); eprintln!(" given; any other address is refused."); + eprintln!(" --start-delay MS: wait this long before taking the lock (tests)."); + eprintln!(" --started-by app | host | command: who started it, said in run/server.info"); + eprintln!(" so a program that finds it holding the books knows what it is."); eprintln!(" --open all | none | ID[,ID...]: which books are open at the start (default"); eprintln!(" all). A book left closed opens when asked (`wanderbooks books open ID`)."); } @@ -3237,6 +3334,8 @@ pub fn run( let mut isolation = Isolation::SameUser; let mut tunnel: Option = None; let mut open_at_start = OpenAtStart::All; + let mut started_by: Option = None; + let mut start_delay = Duration::ZERO; let mut args = args.into_iter().peekable(); while let Some(arg) = args.next() { match arg.as_str() { @@ -3266,6 +3365,26 @@ pub fn run( open_at_start = OpenAtStart::parse(&args.next().ok_or("--open needs all, none, or ids")?)?; } + // Who started this server (INVARIANT 16): the app, a `serve` + // host or a command. Without it a server says nothing of + // itself, as every earlier build's did not. + "--started-by" => { + started_by = Some(StartedBy::parse( + &args + .next() + .ok_or("--started-by needs app, host or command")?, + )?); + } + // How long this server waits before it first tries to take the + // lock (tests of a program that starts or finds the books in + // that time: a slow start). + "--start-delay" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--start-delay needs milliseconds")?; + start_delay = Duration::from_millis(ms); + } // How long the books stay unwritten before a backup (tests). "--backup-quiet" => { let ms: u64 = args @@ -3359,6 +3478,11 @@ pub fn run( let _in_runtime = rt.enter(); watch_for_close(&stops)?; } + // The test knob `--start-delay`: a slow start, told to close or not. + let delayed = std::time::Instant::now(); + while delayed.elapsed() < start_delay && !stops.close.is_cancelled() { + std::thread::sleep(Duration::from_millis(10)); + } // INVARIANT 1: a server still finishing (its host gone) has the lock; // this one waits for it, touching nothing, until told to close. let mut said = false; @@ -3394,6 +3518,28 @@ pub fn run( ledger_store::winsec::set_owner_only(&lock_path) .map_err(|e| format!("can't make the server lock private: {}", e.kind()))?; } + // INVARIANT 16: what this server is, said as soon as the lock is its + // and until just before it lets the lock go; `closing` from the moment + // it is told to close. + let info_guard = match started_by { + Some(by) => { + let mut info = ServerInfo { + by, + pid: std::process::id(), + closing: stops.close.is_cancelled(), + }; + write_server_info(&run, &info) + .map_err(|e| format!("can't say what this server is: {}", e.kind()))?; + let (close, there) = (stops.close.clone(), run.clone()); + rt.spawn(async move { + close.cancelled().await; + info.closing = true; + let _ = write_server_info(&there, &info); + }); + Some(InfoGuard(run.join(SERVER_INFO))) + } + None => None, + }; let books = Arc::new( Books::new(root.clone(), backup_quiet, drill_first, isolation).with_timers(timers), ); @@ -3442,6 +3588,7 @@ pub fn run( for name in [MCP_SOCKET, ADMIN_SOCKET] { let _ = std::fs::remove_file(run.join(name)); } + drop(info_guard); drop(lock); served } From 6164d0fa683658400c1d547f6100447160a13455 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:16:24 -0700 Subject: [PATCH 07/11] fix(host): a bridge that held a host follows the app that takes its place Plan P15 unit A5, fix round. A bridge started under a `serve` host, when that host went and the app started in its place, took a lease on the app's server: a lease with no host behind it, which never ends. When the app later closed, the assistant got a generic timeout and never "Wanderbooks isn't running". A lease with no host now turns the bridge into the line to whatever runs, as a bridge that began without a host is (`Lease::is_hostless`, `Bridge::keep`), and it answers in the same words when the app is closed. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-host/src/bridge.rs | 11 +++++++++++ crates/ledger-host/src/opener.rs | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index ae9486f9..3d23a9f2 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -1005,6 +1005,17 @@ impl Bridge { return; } }; + // The host this bridge held went, and the app started in its + // place: its lease is on a server with no host, which never + // ends, so it would never see the app go. The bridge becomes + // the line to whatever runs, as a fresh one is, and says the + // same words when the app closes (INVARIANT 12). + if lease.is_hostless() { + drop(lease); + self.app.store(true, std::sync::atomic::Ordering::SeqCst); + self.link.send_replace(Link::Opening); + return self.keep_in_app(run_dir).await; + } // Until this lease ends: whenever the server is ready and no // session is up, open one. The lease is always heard, even // while a session is being opened or a try waits (INVARIANT 1). diff --git a/crates/ledger-host/src/opener.rs b/crates/ledger-host/src/opener.rs index ed019d33..8e50099d 100644 --- a/crates/ledger-host/src/opener.rs +++ b/crates/ledger-host/src/opener.rs @@ -166,6 +166,13 @@ struct HostLink { } impl Lease { + /// Whether this lease is on the app's server with no host behind it + /// (INVARIANT 6): it never ends, so a holder that has one follows + /// what runs by looking, as a bridge with no host does. + pub fn is_hostless(&self) -> bool { + self.link.is_none() + } + /// The host's next word: `Ready`, or `Ending` with why; `None` when /// the host is gone without a word. pub async fn next(&mut self) -> Option { From c47144a4010fc2f0b48e575fdc4d8508074c6bb5 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:19:46 -0700 Subject: [PATCH 08/11] feat(gui): the notice for a host that holds the books has a button that closes it Plan P15 unit A5, fix round. When an older build's detached host (or `wanderbooks serve`) holds the books, the app's start is refused, and the notice said to run `wanderbooks close`. A packaged Mac or Windows install may have no command line on the path. The notice now says what will happen, and carries a "Close it" button that asks the host to close the books and waits until it has (`commands::close_the_host`, what `wanderbooks close` does, over the unchanged lease protocol, which an older host speaks), then starts the app's own server and takes the notice away. The line to type stays in the words as the fallback. A close that fails says why and offers the button again; a start refused for any other reason offers none. The `Owner` trait gets two methods with default bodies (`serve_host_holds`, `serve_close_host`), so existing implementations, test mocks included, are untouched. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/src/main.rs | 8 + crates/ledger-gui/src/app.rs | 14 ++ crates/ledger-gui/src/owner.rs | 13 ++ crates/ledger-gui/src/serving.rs | 71 +++++++- crates/ledger-gui/tests/host_holds.rs | 235 ++++++++++++++++++++++++++ crates/ledger-host/src/commands.rs | 48 ++++++ 6 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 crates/ledger-gui/tests/host_holds.rs diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 59540690..38680ba9 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -96,6 +96,14 @@ impl ledger_gui::owner::Owner for ViewerOwner { self.server.start(open) } + fn serve_host_holds(&self) -> bool { + ledger_host::commands::a_host_holds(self.common.root.as_deref()) + } + + fn serve_close_host(&self) -> Result { + ledger_host::commands::close_the_host(self.common.root.as_deref()) + } + fn serve_open(&self, book: &str) -> Result, String> { self.server.open_book(book) } diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 30b61cd1..2c92c98f 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -535,12 +535,20 @@ impl App { self.notices.extend(self.serving.take_notices()); let starting = self.serving.is_starting(); let down = self.serving.is_down(); + // The refusal by a host is over once the start is on its way again + // (the host was closed): its words go, whether or not they were + // dismissed. + if !down { + self.notices.retain(|n| n != crate::serving::HOST_HOLDS); + } if self.notices.is_empty() && !starting && !down { return; } let p = pal(ui.ctx()); let mut dismiss = None; let mut retry = false; + let mut close_host = false; + let host_blocks = self.serving.host_blocks(); egui::Panel::top("server_notices") .resizable(false) .frame( @@ -563,6 +571,9 @@ impl App { for (i, words) in self.notices.iter().enumerate() { ui.horizontal_wrapped(|ui| { ui.label(RichText::new(words).color(p.text)); + if host_blocks && ui.button("Close it").clicked() { + close_host = true; + } if down && ui.button("Try again").clicked() { retry = true; } @@ -578,6 +589,9 @@ impl App { if retry { self.serving.retry(); } + if close_host { + self.serving.close_host(); + } if let Some(i) = dismiss { self.notices.remove(i); } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index db1f41de..dd93c718 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -229,6 +229,19 @@ pub trait Owner: Send + Sync { fn serve_start(&self, _open: &[String]) -> Result<(), String> { Ok(()) } + /// Whether another program's host holds the books now (an earlier + /// build's, or `wanderbooks serve`'s): asked when the start was + /// refused, to offer the person a button that closes it + /// (`serve_close_host`) beside the line that says what to type. + fn serve_host_holds(&self) -> bool { + false + } + /// Ask that host to close the books and wait until it has (what + /// `wanderbooks close` does, for a person with no command line on + /// their path): `Ok` says what came of it, `Err` why not. Blocks. + fn serve_close_host(&self) -> Result { + Err("not here".into()) + } /// Open the company `book` in the server (a tab opened): `Ok(None)` /// when it is open now. Blocks. fn serve_open(&self, _book: &str) -> Result, String> { diff --git a/crates/ledger-gui/src/serving.rs b/crates/ledger-gui/src/serving.rs index bdac225f..7fec415d 100644 --- a/crates/ledger-gui/src/serving.rs +++ b/crates/ledger-gui/src/serving.rs @@ -47,6 +47,11 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +/// What the person is told when the start was refused because a host +/// holds the books, and what to do: the button closes it for them, and the +/// command is there for a person who prefers a terminal. +pub const HOST_HOLDS: &str = "Assistants can't reach your companies: another program has these books open (an earlier Wanderbooks, or `wanderbooks serve`). \"Close it\" makes it let go of them and starts the books here; or, in a terminal, `wanderbooks close` does the same."; + /// Where the server's start stands (INVARIANT 3). #[derive(Clone, Copy, PartialEq, Eq)] enum Gate { @@ -82,6 +87,12 @@ struct State { report: Vec, /// The person has seen the report and chose to close anyway. report_seen: bool, + /// The start was refused because a host holds the books (an earlier + /// build's, or `wanderbooks serve`'s): the notice has a button that + /// closes it (INVARIANT 3). + host_blocks: bool, + /// That button was pressed and the host is being asked to close. + host_closing: bool, } struct Inner { @@ -207,7 +218,14 @@ impl Serving { // A window asked to close meanwhile has no use for // the word. if *lock(&starting.closing) == Closing::Not { - starting.note(format!("Assistants can't reach your companies: {why}")); + let host = starting.owner.serve_host_holds(); + lock(&starting.state).host_blocks = host; + if host { + starting.note(HOST_HOLDS.into()); + } else { + starting + .note(format!("Assistants can't reach your companies: {why}")); + } } Gate::Down } @@ -276,6 +294,57 @@ impl Serving { .is_some_and(|i| *lock(&i.gate) == Gate::Up && *lock(&i.closing) == Closing::Not) } + /// Whether the start was refused because a host holds the books, so + /// the notice offers to close it (INVARIANT 3): not while that is + /// being done. + pub fn host_blocks(&self) -> bool { + self.inner.as_ref().is_some_and(|i| { + let state = lock(&i.state); + *lock(&i.gate) == Gate::Down && state.host_blocks && !state.host_closing + }) + } + + /// Ask the host that holds the books to close them, and start the + /// server when it has (INVARIANT 3): on a thread of its own, the + /// answer a notice. False when nothing was started. + pub fn close_host(&self) -> bool { + let Some(inner) = self.inner.clone() else { + return false; + }; + if !self.host_blocks() { + return false; + } + lock(&inner.state).host_closing = true; + let asking = inner.clone(); + let started = std::thread::Builder::new() + .name("serving-close-host".into()) + .spawn(move || { + let said = asking.owner.serve_close_host(); + { + let mut state = lock(&asking.state); + state.host_closing = false; + if said.is_ok() { + state.host_blocks = false; + // The old words are of a refusal that is over. + state.notices.retain(|n| n != HOST_HOLDS); + } + } + match said { + Ok(_) => { + Self::restart(&asking); + } + Err(why) => asking.note(format!( + "Couldn't close it: {why}. In a terminal, `wanderbooks close` closes it." + )), + } + }) + .is_ok(); + if !started { + lock(&inner.state).host_closing = false; + } + started + } + /// Whether the start failed and a `retry` would try again. pub fn is_down(&self) -> bool { self.inner diff --git a/crates/ledger-gui/tests/host_holds.rs b/crates/ledger-gui/tests/host_holds.rs new file mode 100644 index 00000000..cdf44c94 --- /dev/null +++ b/crates/ledger-gui/tests/host_holds.rs @@ -0,0 +1,235 @@ +//! A start the app's server was refused because a host holds the books (an +//! earlier build's detached host, or `wanderbooks serve`'s): the notice +//! carries a button that closes it, and the line to type is its fallback +//! (serving.rs INVARIANT 3; WB-app-2). +//! +//! ```text +//! GOAL: a person with no command line on their path can let go of a +//! host that holds the books, from the notice, and the app then +//! starts its own server. +//! SOURCE: plan/p15-app-and-relay.md 3.1; WB-app-1 (a start is refused, +//! in words, when another program has the books), WB-app-2. +//! INVARIANTS: +//! 1. A start refused while a host holds the books is a notice that +//! says what will happen and what to type instead; the button is +//! offered (`host_blocks`). +//! 2. The button asks the host to close (`serve_close_host`) and, once +//! it has, starts the server and takes the notice away. +//! 3. A close that fails says why and offers the button again. +//! 4. A start refused for any other reason offers no such button. +//! ``` + +use ledger_core::Currency; +use ledger_gui::owner::{Agent, Owner, RestorePlan}; +use ledger_gui::serving::{HOST_HOLDS, Serving}; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +/// An owner whose start is refused while `host` holds the books. +struct Held { + host: AtomicBool, + /// Whether a host is what refused the start (else something else did). + host_is_why: bool, + close_says: Mutex>, + log: Mutex>, +} + +impl Held { + fn new(host_is_why: bool) -> Arc { + Arc::new(Held { + host: AtomicBool::new(true), + host_is_why, + close_says: Mutex::new(Ok("The other program let go of the books.".into())), + log: Mutex::new(Vec::new()), + }) + } + + fn said(&self) -> Vec { + self.log.lock().unwrap().clone() + } +} + +impl Owner for Held { + fn serves(&self) -> bool { + true + } + fn serve_start(&self, _open: &[String]) -> Result<(), String> { + self.log.lock().unwrap().push("start".into()); + if self.host.load(Ordering::SeqCst) { + Err("Another program has these books open: close it".into()) + } else { + Ok(()) + } + } + fn serve_host_holds(&self) -> bool { + self.host_is_why && self.host.load(Ordering::SeqCst) + } + fn serve_close_host(&self) -> Result { + self.log.lock().unwrap().push("close host".into()); + let said = self.close_says.lock().unwrap().clone(); + if said.is_ok() { + self.host.store(false, Ordering::SeqCst); + } + said + } + fn new_books(&self, _: &str, _: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _: &str) -> Result, String> { + Err("not here".into()) + } + fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + Err("not here".into()) + } + fn restore(&self, _: &RestorePlan) -> Result, String> { + Err("not here".into()) + } + fn connect(&self, _: Agent, _: &str) -> Result, String> { + Err("not here".into()) + } + fn upgrade_format(&self, _: &str, _: &str) -> Result, String> { + Err("not here".into()) + } +} + +fn until(what: &str, mut ok: impl FnMut() -> bool) { + let end = Instant::now() + Duration::from_secs(30); + while !ok() { + assert!(Instant::now() < end, "never: {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn started(owner: &Arc) -> Serving { + let _ = Currency::USD; + let serving = Serving::start(Some(owner.clone() as Arc), vec![]); + until("the first start came out", || !serving.is_starting()); + serving +} + +#[test] +fn a_start_refused_by_a_host_says_what_the_button_does_and_the_command_to_type() { + let owner = Held::new(true); + let serving = started(&owner); + assert!(serving.host_blocks()); + let notices = serving.take_notices(); + assert_eq!(notices, vec![HOST_HOLDS.to_string()]); + assert!( + HOST_HOLDS.contains("Close it") && HOST_HOLDS.contains("`wanderbooks close`"), + "{HOST_HOLDS}" + ); +} + +#[test] +fn the_button_closes_the_host_and_starts_the_server() { + let owner = Held::new(true); + let serving = started(&owner); + // Notices the window shows are kept by it: what it has not shown yet + // is read here, as it does. + let mut shown = serving.take_notices(); + assert!(serving.close_host()); + until("the server started after the host closed", || { + serving.is_up() + }); + assert_eq!(owner.said(), ["start", "close host", "start"]); + assert!(!serving.host_blocks()); + shown.extend(serving.take_notices()); + // The refusal is over, and the notice of it goes (a window that + // already shows it drops it as it learns the start came out). + assert!(!serving.is_down()); +} + +#[test] +fn a_close_that_fails_says_why_and_the_button_stays() { + let owner = Held::new(true); + *owner.close_says.lock().unwrap() = Err("the other program is still closing".into()); + let serving = started(&owner); + let _ = serving.take_notices(); + assert!(serving.close_host()); + until("the failure is said", || { + serving + .take_notices() + .iter() + .any(|n| n.contains("Couldn't close it: the other program is still closing")) + }); + until("the button is back", || serving.host_blocks()); + assert!(serving.is_down()); + assert_eq!(owner.said(), ["start", "close host"]); +} + +#[test] +fn a_start_refused_for_another_reason_offers_no_button() { + let owner = Held::new(false); + let serving = started(&owner); + assert!(!serving.host_blocks()); + assert!(!serving.close_host()); + let notices = serving.take_notices(); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with("Assistants can't reach your companies:")); + assert_eq!(owner.said(), ["start"]); +} + +/// The window itself: the notice shows the button, pressing it asks the +/// host to close, and the notice goes once the server has started. +#[test] +fn the_notice_in_the_window_has_the_button_and_it_goes_when_the_server_starts() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + use ledger_gui::{App, Start}; + use ledger_store::root::{BookId, Root}; + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let root = dir.path().join("root"); + Root::setup(&home, Some(&root), None).unwrap(); + let found = Root::find(Some(&root)).unwrap(); + drop( + found + .create_book(&BookId::parse("alpha").unwrap(), Currency::USD) + .unwrap(), + ); + let fallback = ledger_gui::data::Source { + data_dir: root.join("books").join("alpha"), + today: None, + }; + let owner = Held::new(true); + let for_app: Arc = owner.clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 700.0)) + .build_eframe(move |cc| { + App::start_with_owner( + &cc.egui_ctx, + &|_| None, + Start::Restore { root, fallback }, + Some(for_app), + ) + }); + until("the start was refused", || { + h.run_steps(2); + h.query_all_by_label_contains("`wanderbooks close`") + .next() + .is_some() + }); + h.query_all_by_label("Close it") + .next() + .expect("the button") + .click(); + until("the host was asked to close and the server started", || { + h.run_steps(2); + { + // (A tab opening after the refused start tried it again once.) + let said = owner.said(); + said.iter().filter(|s| *s == "close host").count() == 1 + && said.last().is_some_and(|s| s == "start") + } + }); + until("the notice goes", || { + h.run_steps(2); + h.query_all_by_label_contains("`wanderbooks close`") + .next() + .is_none() + && h.query_all_by_label("Close it").next().is_none() + }); +} diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 78611be3..8586503d 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -686,6 +686,54 @@ pub fn close( } } +/// Ask the host that holds the books (an earlier build's detached host, +/// or `wanderbooks serve`'s) to close them, and wait until they are +/// closed: what `wanderbooks close` does, for the app, whose person may +/// have no command line (the lease protocol to such a host is the same +/// as ever). `Ok` says what came of it, in words; `Err` says why not. +/// Blocks, at most `CLOSE_WAIT` and a few seconds. +pub fn close_the_host(root: Option<&Path>) -> Result { + let found = ledger_store::root::Root::find(root).map_err(|e| e.to_string())?; + let run = found.run_dir().map_err(|e| e.to_string())?; + let asked = crate::opener::ask_once_within(&run, Ask::Intent(Intent::Close), HOST_WAIT)?; + match asked { + None => Ok("No program has the books open now.".into()), + Some(HostMsg::Done { .. }) => { + let deadline = std::time::Instant::now() + CLOSE_WAIT; + loop { + let asked = crate::opener::ask_once_within(&run, Ask::Leases, HOST_WAIT); + match closing(&asked, || crate::opener::server_lock_held(&run)) { + Closing::Closed => return Ok("The other program let go of the books.".into()), + Closing::Reopened => { + return Err( + "something opened the books again as the other program let go".into(), + ); + } + Closing::Going => {} + } + if past(deadline, std::time::Instant::now()) { + return Err( + "the other program is still closing the books (a request is finishing)" + .into(), + ); + } + std::thread::sleep(Duration::from_millis(50)); + } + } + Some(HostMsg::Refused(why)) => Err(why), + Some(other) => Err(format!("the books' host answered oddly: {other:?}")), + } +} + +/// Whether a host holds the books of the root now (an earlier build's, or +/// `wanderbooks serve`'s): the one case the app's refused start can offer +/// to close for the person ([`close_the_host`]). +pub fn a_host_holds(root: Option<&Path>) -> bool { + ledger_store::root::Root::find(root) + .and_then(|found| found.run_dir()) + .is_ok_and(|run| crate::opener::host_lock_held(&run)) +} + fn books_usage(prog: &str) { eprintln!("usage: {prog} list"); eprintln!(" {prog} create ID [--currency CODE]"); From 2275c34e8646cb7b164fcc3f3447ce9996df9f57 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:19:58 -0700 Subject: [PATCH 09/11] fix(store,host): `books list` with nothing running says which books wait for a format upgrade Plan P15 unit A5, fix round. With nothing running, `books list` reads the folder and takes no lock (nothing is opened), so it stopped showing which companies wait for a format upgrade, which a server showed. It now reads what each journal declares (`ledger_store::declared_format`: no lock, nothing written, the hash chain not verified, so it says what the books declare and no more) and adds "; waiting for a format upgrade (`wanderbooks books upgrade ID`)"; a journal that cannot be read says why on its line. The listing no longer fails when a company's folder vanishes while it is made (a book put aside meanwhile): a vanished entry is skipped, not an error (`list_books_inner` used `entry?`). Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/format_upgrade.rs | 22 +++++++++ crates/ledger-host/src/commands.rs | 39 +++++++++++++--- crates/ledger-store/src/format.rs | 54 +++++++++++++++++++++++ crates/ledger-store/src/lib.rs | 2 +- crates/ledger-store/src/root.rs | 8 +++- 5 files changed, 115 insertions(+), 10 deletions(-) diff --git a/crates/ledger-cli/tests/format_upgrade.rs b/crates/ledger-cli/tests/format_upgrade.rs index a26aa078..b71f2aa8 100644 --- a/crates/ledger-cli/tests/format_upgrade.rs +++ b/crates/ledger-cli/tests/format_upgrade.rs @@ -1039,3 +1039,25 @@ fn shell_join(words: &[String]) -> String { .collect::>() .join(" ") } + +/// With nothing running, `books list` reads the folder and says which +/// companies wait for a format upgrade, from what their journals declare +/// (no lock, nothing written): it used to say so only through a server. +#[test] +fn a_list_with_nothing_running_says_which_books_wait_for_an_upgrade() { + let home = Home::new("list-upgrade"); + let dir = old_books(&home, "acme"); + let before = journal(&dir); + let out = home.books(&["list"]); + let said = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!(out.status.success(), "{out:?}"); + assert!( + said.contains("acme not open: Wanderbooks isn't running") + && said.contains("waiting for a format upgrade (`wanderbooks books upgrade acme`)"), + "{said}" + ); + // Reading it changed nothing and left nothing running. + assert_eq!(journal(&dir), before); + assert!(!ledger_host::opener::server_lock_held(&home.run_dir())); + assert!(!ledger_host::opener::host_lock_held(&home.run_dir())); +} diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 8586503d..69597c9c 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -829,13 +829,13 @@ pub fn books( common.ask_upgrades = !matches!(words.as_slice(), ["upgrade", ..]); let answer = match words.as_slice() { ["list"] => match listed_while_closed(&common) { - Ok(Some(ids)) => { - if ids.is_empty() { + Ok(Some(listed)) => { + if listed.is_empty() { println!("No books yet: `wanderbooks books create ID` starts some."); } - for id in ids { + for (id, upgrade) in listed { println!( - "{id} not open: Wanderbooks isn't running (start it, or run `wanderbooks serve`, to open it)" + "{id} not open: Wanderbooks isn't running (start it, or run `wanderbooks serve`, to open it){upgrade}" ); } return Ok(()); @@ -1032,8 +1032,13 @@ pub fn books( /// The books of the root by name, read from the folder and no more, when /// nothing runs: no host and no server holds the root, so there is no open /// or closed to tell, and nothing is changed or read of the books, which -/// is why it takes no lock (WB-app-5). `None` when something runs: ask it. -fn listed_while_closed(common: &Common) -> Result>, String> { +/// is why it takes no lock (WB-app-5), with what each waits for in words: +/// a format upgrade is read from what the journal declares +/// (`ledger_store::declared_format`: no lock, nothing written, the chain +/// not verified, so it says what the books declare and no more), and a +/// journal that can't be read says so and is not skipped. `None` when +/// something runs: ask it. +fn listed_while_closed(common: &Common) -> Result>, String> { let found = ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; let run = found.run_dir().map_err(|e| e.to_string())?; @@ -1041,7 +1046,27 @@ fn listed_while_closed(common: &Common) -> Result>, String> { return Ok(None); } let ids = found.list_books().map_err(|e| e.to_string())?; - Ok(Some(ids.iter().map(|id| id.to_string()).collect())) + Ok(Some( + ids.iter() + .filter_map(|id| { + let waits = match ledger_store::declared_format(&found.book_dir(id)) { + Ok(declared) if declared.upgrade().is_some() => { + format!("; waiting for a format upgrade (`wanderbooks books upgrade {id}`)") + } + Ok(_) => String::new(), + // A book that vanished since the list is not one of the + // books; one that can't be read says why. + Err(ledger_store::StoreError::Io(e)) + if e.kind() == std::io::ErrorKind::NotFound => + { + return None; + } + Err(e) => format!("; its format isn't known: {e}"), + }; + Some((id.to_string(), waits)) + }) + .collect(), + )) } fn book_line(b: &admin::BookStatus) -> String { diff --git a/crates/ledger-store/src/format.rs b/crates/ledger-store/src/format.rs index 764d9c37..48713b94 100644 --- a/crates/ledger-store/src/format.rs +++ b/crates/ledger-store/src/format.rs @@ -447,6 +447,35 @@ impl JournalFormat { } } +/// The format a book's journal declares, read without opening the book: +/// no lock is taken and nothing is written, and the hash chain is not +/// verified (this is what the journal says, for a program that only lists +/// the books while none is open: `wanderbooks books list`). It is the +/// last `journal.format_set` line, or format 1 for books that never +/// declared one; a line that can't be read is an `Err`, and so is a +/// format this version doesn't read. +pub fn declared_format(book_dir: &std::path::Path) -> Result { + use std::io::BufRead; + let file = std::fs::File::open(book_dir.join(crate::store::JOURNAL_FILE))?; + let mut format = JournalFormat::default(); + for raw in std::io::BufReader::new(file).split(b'\n') { + let raw = raw?; + // Only the declaration lines are read in full. + if !raw + .windows(FORMAT_SET.len()) + .any(|window| window == FORMAT_SET.as_bytes()) + { + continue; + } + if let Ok(line) = JournalLine::parse(&raw) + && line.line_type == FORMAT_SET + { + format = declared(&line)?; + } + } + Ok(format) +} + /// The journal format this version writes: the newest format it reads, /// with every feature it knows, sorted. New books declare it as they are /// created ([`crate::Store::create`]), and books in an older format move @@ -711,6 +740,31 @@ pub(crate) fn settle(refusal: StoreError, hash: &str, next: Option<&[u8]>) -> St #[cfg(test)] mod tests { + /// `declared_format` reads what a journal declares with no store open: + /// new books declare this version's, a journal that never declared one + /// is format 1 (and waits for an upgrade), and the file is untouched. + #[test] + fn a_format_is_read_from_the_journal_without_opening_it() { + let dir = tempfile::tempdir().unwrap(); + let book = dir.path().join("acme"); + drop(crate::Store::create(&book, ledger_core::Currency::USD).unwrap()); + let journal = book.join(crate::store::JOURNAL_FILE); + let before = std::fs::read(&journal).unwrap(); + let declared = super::declared_format(&book).unwrap(); + assert_eq!(declared, super::current()); + assert!(declared.upgrade().is_none()); + assert_eq!(std::fs::read(&journal).unwrap(), before, "nothing written"); + // Books written before the gate declared nothing: format 1. + let old = dir.path().join("old"); + std::fs::create_dir(&old).unwrap(); + std::fs::write(old.join(crate::store::JOURNAL_FILE), b"").unwrap(); + let declared = super::declared_format(&old).unwrap(); + assert_eq!(declared, super::JournalFormat::default()); + assert!(declared.upgrade().is_some()); + // No journal at all is an error, not format 1. + assert!(super::declared_format(&dir.path().join("nope")).is_err()); + } + use super::*; use crate::store::{Store, apply_line_to_sqlite, replay_line_into_ledger}; use ledger_core::{Currency, Ledger}; diff --git a/crates/ledger-store/src/lib.rs b/crates/ledger-store/src/lib.rs index 52cdfa2f..cac35f90 100644 --- a/crates/ledger-store/src/lib.rs +++ b/crates/ledger-store/src/lib.rs @@ -49,7 +49,7 @@ pub mod winsec; pub use blob::BlobStore; pub use error::StoreError; -pub use format::{FormatUpgrade, JournalFormat, SUPPORTED_JOURNAL_FORMAT}; +pub use format::{FormatUpgrade, JournalFormat, SUPPORTED_JOURNAL_FORMAT, declared_format}; pub use journal::{GENESIS_PREV, JournalLine, JournalWriter}; pub use snapshot::{DiskCheck, Snapshot}; pub use store::audit; diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index 19f81ef1..0353b74c 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -809,14 +809,18 @@ impl Root { let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let mut ids = Vec::new(); for entry in std::fs::read_dir(books)? { - let entry = entry?; + // A folder that vanishes while the list is made (a book put + // aside or removed meanwhile) is not one of the books. + let Ok(entry) = entry else { continue }; let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue; }; let Ok(id) = BookId::parse(&name) else { continue; }; - if entry.file_type()?.is_dir() && entry.path().join(JOURNAL_FILE).is_file() { + if entry.file_type().is_ok_and(|t| t.is_dir()) + && entry.path().join(JOURNAL_FILE).is_file() + { ids.push(id); } } From da0ed04bb31c9a8932eeb6c9b1894384460d4461 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:30:26 -0700 Subject: [PATCH 10/11] test(cli): what holds the books is known; the thinned tests say what their names say MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plan P15 unit A5, fix round. Each of these fails without its fix (checked by disabling the fix): a serve, a command and `close`/`doctor` meeting a closing server or a command's server (orphan of a killed host, another command's), a command's own server holding server.lock and books.lock while it works and refusing the app's start and making `serve` wait, a command's server holding none of the invoker's environment, pipes or folder, a command racing the app's start, two commands at once with nothing running, a bridge that held a host following the app that takes its place, the app asking a host to close, and server.info itself. Thinned tests, mended: the_host_starts_without_a_scope_when_systemd_run_fails drove `books create`, which never starts a host, and passed with the fallback broken; it now drives `serve` and fails with the fallback broken. with_nothing_running_a_command_runs_its_own_server… asserted `success || stderr contains "backup"`, which passes on a failure; it asserts the real outcome (exit 1, "No backups are set up"; a backup that is made is books_are_backed_up_now_from_the_command_line). the_bridge_reaches_the_books_serve_holds… has its close after the last lease back (serve let go, the books close). a_command_leaves_nothing_running_and_serve_closes… has "a lease arriving within the delay cancels the close" back (a second `serve` within `close_after` keeps the same host). books_commands_hold_the_books_while_they_run points to the test of a command's own server. Moved tests, one line each (what each still protects, read against the diff of e9a520138): a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder: nothing left by a command or a bridge, serve's delay and its cancel (restored). serve_and_the_bridges_share_one_host_and_one_server: one host, one server, two `serve`s racing, bridges and a command joining. the_bridge_answers_initialize_itself_during_a_slow_start, …gives_up_on_books_that_never_open, a_call_cancelled_at_once_is_never_made, a_signalled_bridge_goes_at_once, books_made_mid_session_and_bad_requests: still the bridge's waiting on a host whose server is slow (`serve` with `server_delay`), the same knobs. books_commands_hold_the_books_while_they_run: commands lease a host that serve holds. a_command_ends_at_its_deadline_during_a_restart: still a command ending at its deadline while update.lock is held (`token list`; `books list` reads the folder). a_bridge_started_without_stderr_keeps_its_descriptors_apart, the_commands_given_run_as_the_agents_own_token, an_agent_is_connected_and_reaches_the_books_by_what_it_was_given: unchanged bodies behind a `serve` that holds the books; the properties are the bridge's and the token's, not who started the host. doctor_says_whether_the_books_are_open_and_what_holds_them: asserts the new closed words. the_host_serve_starts_is_clean_from_a_hostile_serve: the host's scrub, from serve. the_viewers_new_books_are_made_by_the_server: new books through a server that runs. update.rs (9 moved): the diff is the harness only (`keep_host`, the request key); their subjects (restart onto a replaced program, update.lock, staging, verifying, applying before a host starts) are the host's, which `serve` starts the same way; read in full for the_host_stages_a_daily_update_and_the_next_start_applies_it (the next start is now serve's), the others by the diff and a green run. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/app_server.rs | 6 +- crates/ledger-cli/tests/open_while_held.rs | 677 ++++++++++++++++++++- 2 files changed, 674 insertions(+), 9 deletions(-) diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs index 555e3457..bed9e0dd 100644 --- a/crates/ledger-cli/tests/app_server.rs +++ b/crates/ledger-cli/tests/app_server.rs @@ -293,8 +293,12 @@ fn with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderboo let token = command(&["token", "create", "--book", BOOK]); assert!(token.status.success(), "{token:?}"); let backed = command(&["books", "back-up", BOOK]); + // The command's own server did the work, and said the true thing: no + // backup is set up in these books (a backup that is made is + // `books_are_backed_up_now_from_the_command_line`, open_while_held.rs). + assert_eq!(backed.status.code(), Some(1), "{backed:?}"); assert!( - backed.status.success() || String::from_utf8_lossy(&backed.stderr).contains("backup"), + String::from_utf8_lossy(&backed.stderr).contains("No backups are set up"), "{backed:?}" ); assert!(!server_lock_held(&run), "the command's server was left"); diff --git a/crates/ledger-cli/tests/open_while_held.rs b/crates/ledger-cli/tests/open_while_held.rs index 39c46ac1..8305be59 100644 --- a/crates/ledger-cli/tests/open_while_held.rs +++ b/crates/ledger-cli/tests/open_while_held.rs @@ -553,10 +553,22 @@ fn a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder() { // comes in time cancels nothing, and no second host starts. home.create("beta"); assert_eq!(home.pids("host").len(), 1, "one host"); + let host = home.host().expect("serve's host"); held.child.kill().unwrap(); held.child.wait().unwrap(); std::thread::sleep(Duration::from_millis(300)); assert!(home.host().is_some(), "closed before the delay"); + // A lease arriving within the delay cancels the close: the same host, + // still there well past the delay the last lease's end began. + let mut again = serve(&home); + std::thread::sleep(Duration::from_millis(3000)); + assert_eq!( + home.host(), + Some(host), + "closed though a lease came in time" + ); + again.child.kill().unwrap(); + again.child.wait().unwrap(); assert!(home.wait_closed(10), "never closed after the holder died"); // The last holder is an agent's bridge: serve lets go (Ctrl-C), the // host stays for the bridge past the close delay, and closes after the @@ -681,6 +693,14 @@ fn the_bridge_reaches_the_books_serve_holds_and_holds_them_for_the_session() { assert!(a.end().is_some_and(|s| s.success())); // The session's end leaves the host to `serve`, which still holds. assert!(home.host().is_some(), "serve's host went with a session"); + // And with `serve` let go too, nothing holds the books: the host closes + // after its delay, past the last lease (a bridge as the last holder is + // `a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder`). + drop(home.serving.lock().unwrap().take()); + assert!( + home.wait_closed(15), + "the books stayed open after the last lease ended" + ); // Unknown books: a plain error, no folder named. let mut a = Agent::start(&home, "nobody"); a.initialize(); @@ -1192,6 +1212,10 @@ fn a_restart_is_not_a_close() { assert!(a.call("books.get_entry", json!({"entry_id": 1})).is_ok()); } +/// (What a command holds while it works with nothing running, its own +/// server's `server.lock` and `books.lock`, and the refusal of a second +/// program, is +/// `a_commands_own_server_holds_the_books_while_it_works_and_others_are_refused`.) #[test] fn books_commands_hold_the_books_while_they_run() { let home = Home::new("cmds"); @@ -1588,20 +1612,25 @@ fn the_host_starts_without_a_scope_when_systemd_run_fails() { std::fs::create_dir(&runtime).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&runtime, std::fs::Permissions::from_mode(0o700)).unwrap(); + // `serve` is what starts a host (WB-app-5), so it is what is driven: + // with no scope to be made, the host starts directly and is held. let started = Instant::now(); - let out = home - .cmd("books") - .args(["create", "acme"]) - .env("XDG_RUNTIME_DIR", &runtime) - .stdin(Stdio::null()) - .output() - .unwrap(); - assert!(out.status.success(), "{out:?}"); + let mut serving = Running::start({ + let mut c = home.cmd("serve"); + c.env("XDG_RUNTIME_DIR", &runtime); + c + }); + serving.expect("The books are open", 30); assert!( started.elapsed() < Duration::from_secs(10), "{:?}", started.elapsed() ); + assert!(home.host().is_some(), "no host was started without a scope"); + // Let go: serve ends, the host closes after its delay. + serving.signal(libc::SIGINT); + assert!(serving.wait(10).is_some_and(|s| s.success())); + assert!(home.wait_closed(15)); } /// Review round 5, findings 2 and 3: a malformed byte is answered and the @@ -3094,3 +3123,635 @@ fn shell_join(words: &[String]) -> String { .collect::>() .join(" ") } + +// What holds the books is known and not guessed (opener.rs INVARIANT 6a, +// ledger-mcp local.rs INVARIANT 16; WB-app-5): a server says what started +// it and whether it is closing, and a holder or a command that finds a +// command's server or a closing one waits for it, in words, and goes on. + +/// A real books server, started by hand (`wanderbooks server`, its admin +/// socket answering), whose word about itself the test chooses: what a +/// killed host's server still finishing (`host`, closing), another +/// command's server (`command`) or the app's closing server (`app`, +/// closing) say in `run/server.info`. +struct StandIn { + child: Child, + run: PathBuf, +} + +impl StandIn { + fn start(home: &Home, says: (&str, bool)) -> Self { + let child = Command::new(&home.exe) + .args(["server", "--open", "none", "--root"]) + .arg(home.root()) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", home.dir.path()) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let run = home.run_dir(); + assert!( + wait_for(30, || ledger_host::opener::admin_answers(&run) == Ok(true)), + "the stand-in server never answered" + ); + std::fs::write( + run.join("server.info"), + json!({"by": says.0, "pid": child.id(), "closing": says.1}).to_string(), + ) + .unwrap(); + Self { child, run } + } + + /// The server ends (its input closes), and takes its word with it. + fn finish(mut self) { + drop(self.child.stdin.take()); + self.child.wait().unwrap(); + let _ = std::fs::remove_file(self.run.join("server.info")); + } +} + +impl Drop for StandIn { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// A program run with its output in a file, so a test reads what it has +/// said so far while it is still running. +struct Logged { + child: Child, + log: PathBuf, +} + +impl Logged { + fn start(mut c: Command, log: PathBuf) -> Self { + let file = std::fs::File::create(&log).unwrap(); + let child = c + .stdin(Stdio::piped()) + .stdout(file.try_clone().unwrap()) + .stderr(file) + .spawn() + .unwrap(); + Self { child, log } + } + + fn said(&self) -> String { + std::fs::read_to_string(&self.log).unwrap_or_default() + } + + fn says(&self, text: &str, secs: u64) -> bool { + wait_for(secs, || self.said().contains(text)) + } + + fn running(&mut self) -> bool { + self.child.try_wait().unwrap().is_none() + } + + fn done(&mut self, secs: u64) -> Option { + let deadline = Instant::now() + Duration::from_secs(secs); + while Instant::now() < deadline { + if let Some(status) = self.child.try_wait().unwrap() { + return Some(status); + } + std::thread::sleep(Duration::from_millis(20)); + } + None + } +} + +impl Drop for Logged { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// What a holder or command says while it waits for a command's server, +/// and for a server that is closing. +const WAITS_FOR_COMMAND: &str = "command has the books open for a moment: waiting for it"; +const WAITS_FOR_CLOSE: &str = "is closing the books (a last backup is being made): waiting"; + +/// A `serve` started while a killed host's server is still finishing (its +/// admin socket still answering, no host holding the root) was told "the +/// app has these books open" and exited. It waits, in words, for the +/// server to be gone, and then holds the books. +#[test] +fn serve_waits_in_words_for_a_server_that_is_closing_and_then_holds_the_books() { + let home = Home::new("serve-closing"); + home.create("acme"); + let orphan = StandIn::start(&home, ("host", true)); + let mut serving = Logged::start(home.cmd("serve"), home.dir.path().join("serve.log")); + assert!(serving.says(WAITS_FOR_CLOSE, 20), "{}", serving.said()); + assert!(serving.running(), "serve gave up: {}", serving.said()); + assert!(!serving.said().contains("has these books open")); + assert!(home.host().is_none(), "a host started beside a closing one"); + orphan.finish(); + assert!( + serving.says("The books are open", 40), + "serve never took the books: {}", + serving.said() + ); + assert!(home.host().is_some()); +} + +/// A command, `close` and `doctor` that find the app's server closing say +/// so, and a command goes on once it is gone; none says "the app has them". +#[test] +fn a_command_and_the_words_of_close_and_doctor_know_a_server_is_closing() { + let home = Home::new("cmd-closing"); + home.create("acme"); + let closing = StandIn::start(&home, ("app", true)); + let doctor = home.cmd("doctor").stdin(Stdio::null()).output().unwrap(); + let said = String::from_utf8_lossy(&doctor.stdout).into_owned(); + assert!( + said.contains("The books are closing") && !said.contains("(the app)"), + "{said}" + ); + let close = home.cmd("close").stdin(Stdio::null()).output().unwrap(); + let said = String::from_utf8_lossy(&close.stdout).into_owned(); + assert!( + said.contains("The books are closing") && !said.contains("the app"), + "{said}" + ); + let mut list = Logged::start( + { + let mut c = home.cmd("token"); + c.arg("list"); + c + }, + home.dir.path().join("token.log"), + ); + assert!(list.says(WAITS_FOR_CLOSE, 20), "{}", list.said()); + assert!(list.running(), "{}", list.said()); + closing.finish(); + assert!( + list.done(40).is_some_and(|s| s.success()), + "{}", + list.said() + ); + assert!(!list.said().contains("has these books open")); +} + +/// A command that finds another command's server is not the app's: it +/// waits for that server to finish, in words, bounded by `open_wait`, and +/// does its own work after. It neither attaches to it (a company that the +/// other has not open was "not open: open it in Wanderbooks") nor closes +/// it under the other. +#[test] +fn a_command_waits_for_another_commands_server_and_does_not_attach_to_it() { + let home = Home::new("cmd-cmd"); + home.create("acme"); + let other = StandIn::start(&home, ("command", false)); + // Out of patience: the wait ends at its bound, in words, and the + // other's server is untouched. + let short = home + .cmd("books") + .args([ + "back-up", + "acme", + "--test-knobs", + &format!("{KNOBS},open_wait=1500"), + ]) + .stdin(Stdio::null()) + .output() + .unwrap(); + let err = String::from_utf8_lossy(&short.stderr).into_owned(); + assert_eq!(short.status.code(), Some(1), "{err}"); + assert!( + err.contains(WAITS_FOR_COMMAND) && err.contains("still has the books open"), + "{err}" + ); + assert!(!err.contains("isn't open"), "attached to it: {err}"); + assert!(ledger_host::opener::server_lock_held(&home.run_dir())); + // Patient: it waits, and goes on when the other is done. + let mut list = Logged::start( + { + let mut c = home.cmd("token"); + c.arg("list"); + c + }, + home.dir.path().join("token.log"), + ); + assert!(list.says(WAITS_FOR_COMMAND, 20), "{}", list.said()); + assert!(list.running(), "{}", list.said()); + other.finish(); + assert!( + list.done(40).is_some_and(|s| s.success()), + "{}", + list.said() + ); + assert!(!ledger_host::opener::server_lock_held(&home.run_dir())); +} + +/// A second `wanderbooks serve` started while a command's server is up +/// was told "the app has these books open". It waits for the command, in +/// words, and holds the books after. +#[test] +fn a_serve_waits_for_a_commands_server_and_then_holds_the_books() { + let home = Home::new("serve-cmd"); + home.create("acme"); + let other = StandIn::start(&home, ("command", false)); + let mut serving = Logged::start(home.cmd("serve"), home.dir.path().join("serve.log")); + assert!(serving.says(WAITS_FOR_COMMAND, 20), "{}", serving.said()); + assert!(serving.running(), "{}", serving.said()); + assert!(!serving.said().contains("(the app)")); + other.finish(); + assert!(serving.says("The books are open", 40), "{}", serving.said()); +} + +/// The server says what started it and when it closes, in +/// `run/server.info`, and removes it as it lets go (local.rs INVARIANT 16). +#[test] +fn a_server_says_what_started_it_and_when_it_closes() { + let home = Home::new("info"); + let run = home.run_dir(); + let mut server = Command::new(&home.exe) + .args([ + "server", + "--open", + "none", + "--started-by", + "command", + "--root", + ]) + .arg(home.root()) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let pid = server.id(); + assert!(wait_for(30, || { + ledger_mcp::local::read_server_info(&run).is_some() + && ledger_host::opener::admin_answers(&run) == Ok(true) + })); + let info = ledger_mcp::local::read_server_info(&run).unwrap(); + assert_eq!( + (info.by, info.pid, info.closing), + (ledger_mcp::local::StartedBy::Command, pid, false) + ); + assert_eq!( + ledger_host::opener::what_holds(&run), + Ok(ledger_host::opener::Holder::Command) + ); + // Told to close: it says so while it is still closing (its door stays + // open for a moment after the last request), and then it is gone, and + // its word with it. + drop(server.stdin.take()); + assert!( + wait_for(20, || { + ledger_mcp::local::read_server_info(&run).is_some_and(|i| i.closing) + }), + "it never said it was closing" + ); + server.wait().unwrap(); + assert!(!run.join("server.info").exists(), "its word was left"); +} + +/// While a command works, its own server holds the books' locks, says it +/// is a command's, and every other program is turned away or waits: the +/// app's start is refused, and `serve` waits (WB-app-5). +#[test] +fn a_commands_own_server_holds_the_books_while_it_works_and_others_are_refused() { + use ledger_host::app_server::{ANOTHER_HAS_THEM, AppServer}; + let home = Home::new("cmd-holds"); + let run = home.run_dir(); + std::fs::write(run.join("timer-hold"), "create:start").unwrap(); + let mut create = Logged::start( + { + let mut c = home.cmd("books"); + c.args([ + "create", + "zed", + "--test-knobs", + &format!("{KNOBS},timer_hold=1"), + ]); + c + }, + home.dir.path().join("create.log"), + ); + assert!( + wait_for(30, || { + std::fs::read_to_string(run.join("timer-held")) + .is_ok_and(|held| held.lines().any(|l| l == "create:start")) + }), + "the command's server never reached its work: {}", + create.said() + ); + // It holds the books, and says whose they are. + assert!(ledger_host::opener::server_lock_held(&run)); + assert!(!ledger_host::opener::host_lock_held(&run)); + let info = ledger_mcp::local::read_server_info(&run).expect("it says what it is"); + assert_eq!(info.by, ledger_mcp::local::StartedBy::Command); + assert!(!info.closing); + assert!(home.pids("server").contains(&info.pid)); + let books_lock = std::fs::OpenOptions::new() + .write(true) + .open(run.join("books.lock")) + .expect("the books lock exists"); + assert!( + matches!( + books_lock.try_lock(), + Err(std::fs::TryLockError::WouldBlock) + ), + "the books' lock is not held while the command works" + ); + // The app's start is refused, and nothing is touched by it. + let dir = home.dir.path().to_path_buf(); + let refused = AppServer::start_in(&home.exe, Some(&home.root()), &[], move |c| { + common::clean_env(c, &dir); + }) + .err() + .expect("a start beside a command's server"); + assert_eq!(refused, ANOTHER_HAS_THEM); + // `serve` waits for it, in words, and does not start a host beside it. + let serving = Logged::start(home.cmd("serve"), home.dir.path().join("serve.log")); + assert!(serving.says(WAITS_FOR_COMMAND, 20), "{}", serving.said()); + assert!(home.host().is_none()); + // The work goes on when it is let go, and succeeds. + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert!( + create.done(40).is_some_and(|s| s.success()), + "{}", + create.said() + ); + assert!(home.root().join("books/zed").is_dir()); + assert!(serving.says("The books are open", 40), "{}", serving.said()); +} + +/// A command whose server is slow to take the books, while the app starts +/// in between its look and its server's start, joins the app: it neither +/// fails with advice to close what is not its to close, nor waits silently +/// for the full time for a server that has lost; one bounded wait, in +/// words. The app's server is left as it was. +#[test] +fn a_command_racing_the_apps_start_joins_the_app() { + use ledger_host::app_server::AppServer; + let home = Home::new("cmd-race"); + home.create("acme"); + let run = home.run_dir(); + let mut list = Logged::start( + { + let mut c = home.cmd("token"); + c.args([ + "list", + "--test-knobs", + &format!("{KNOBS},server_delay=4000"), + ]); + c + }, + home.dir.path().join("token.log"), + ); + // Its own server is started (and delaying its take of the lock). + assert!( + wait_for(30, || !home.pids("server").is_empty()), + "the command never started its server: {}", + list.said() + ); + // The app starts now, and gets the books first. + let dir = home.dir.path().to_path_buf(); + let app = AppServer::start_in(&home.exe, Some(&home.root()), &[], move |c| { + common::clean_env(c, &dir); + }) + .unwrap(); + app.wait_ready(Duration::from_secs(60)).unwrap(); + let began = Instant::now(); + assert!( + list.done(60).is_some_and(|s| s.success()), + "{}", + list.said() + ); + assert!( + list.said() + .contains("Another program started the books just now"), + "{}", + list.said() + ); + assert!(!list.said().contains("Close it"), "{}", list.said()); + assert!( + began.elapsed() < Duration::from_secs(30), + "it waited for its own server: {:?}", + began.elapsed() + ); + // The app's server is the one left, and still the app's. + assert_eq!(app.exited(), None); + assert!(ledger_host::opener::server_lock_held(&run)); + assert!(wait_for(20, || home.pids("server").len() == 1)); + assert_eq!( + ledger_mcp::local::read_server_info(&run).map(|i| i.by), + Some(ledger_mcp::local::StartedBy::App) + ); + assert_eq!( + app.stop(Duration::from_secs(60)), + ledger_host::app_server::Stopped::Closed + ); +} + +/// Two commands at once with nothing running: each is done, neither is +/// told to close anything, neither loses its work, and nothing is left. +#[test] +fn two_commands_at_once_with_nothing_running_both_do_their_work() { + let home = Home::new("two-cmds"); + let make = |id: &str| { + Logged::start( + { + let mut c = home.cmd("books"); + c.args(["create", id]); + c + }, + home.dir.path().join(format!("{id}.log")), + ) + }; + let (mut a, mut b) = (make("alpha"), make("beta")); + for (who, run) in [("alpha", &mut a), ("beta", &mut b)] { + assert!( + run.done(60).is_some_and(|s| s.success()), + "{who}: {}", + run.said() + ); + assert!(!run.said().contains("Close it"), "{who}: {}", run.said()); + assert!( + !run.said().contains("has these books open"), + "{who}: {}", + run.said() + ); + } + let listed = home.books(&["list"]); + let text = String::from_utf8_lossy(&listed.stdout).into_owned(); + for id in ["alpha", "beta"] { + assert!(text.contains(&format!("{id} not open")), "{text}"); + } + assert!(!ledger_host::opener::server_lock_held(&home.run_dir())); + assert!(home.host().is_none()); +} + +/// A bridge that began under a `serve` host, when that host is gone and +/// the app has started in its place, follows what runs as a bridge that +/// began without a host does: when the app is closed, the assistant is +/// told "Wanderbooks isn't running", and not left to a timeout. +#[test] +fn a_bridge_that_held_a_host_follows_the_app_that_takes_its_place() { + use ledger_host::app_server::AppServer; + let home = Home::new("bridge-app"); + home.create("acme"); + home.keep_host(); + let mut bridge = Command::new(&home.exe); + bridge + .args(["mcp", "--book", "acme", "--root"]) + .arg(home.root()) + .args(["--test-knobs", &format!("{KNOBS},backoff=3000")]) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", home.dir.path()); + let mut a = Agent::from(bridge); + a.initialize(); + assert!(a.call("books.start", json!({})).is_ok()); + // `serve` and its host go (killed: nothing closes in order), and the + // app takes the books while the bridge waits to try again. + drop(home.serving.lock().unwrap().take()); + for pid in home.pids("host") { + // SAFETY: a host of this test's own root. + unsafe { libc::kill(pid as i32, libc::SIGKILL) }; + } + assert!(wait_for(30, || { + !ledger_host::opener::host_lock_held(&home.run_dir()) + && !ledger_host::opener::server_lock_held(&home.run_dir()) + })); + let dir = home.dir.path().to_path_buf(); + let app = AppServer::start_in( + &home.exe, + Some(&home.root()), + &["acme".to_string()], + move |c| common::clean_env(c, &dir), + ) + .unwrap(); + app.wait_ready(Duration::from_secs(60)).unwrap(); + // The bridge reaches the app's company. + assert!( + wait_for(30, || a.call("books.start", json!({})).is_ok()), + "the bridge never reached the app" + ); + // The app closes: the next call says what is so. + assert_eq!( + app.stop(Duration::from_secs(60)), + ledger_host::app_server::Stopped::Closed + ); + let said = a.call("books.start", json!({})).unwrap_err(); + assert!(said.starts_with("Wanderbooks isn't running"), "{said}"); +} + +/// A command's own server is started clean, as a host is (start.rs +/// INVARIANT 1, local.rs run): it may outlive its command (still closing +/// after 90 s), so it holds nothing of the invoker's: not its environment, +/// not a pipe it handed down, not its folder. +#[test] +fn a_commands_own_server_holds_none_of_the_invokers_environment_or_pipes() { + use std::os::unix::process::CommandExt; + let home = Home::new("cmd-clean"); + let run = home.run_dir(); + std::fs::write(run.join("timer-hold"), "create:start").unwrap(); + // A pipe the invoker holds and hands down on descriptor 9 (left open + // across exec, as a careless launcher leaves one). + let mut fds = [0i32; 2]; + // SAFETY: pipe fills two descriptors. + assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0); + let link = |fd: i32| { + std::fs::read_link(format!("/proc/self/fd/{fd}")) + .unwrap() + .to_string_lossy() + .into_owned() + }; + let (pipe_read, pipe_write) = (link(fds[0]), link(fds[1])); + let mut c = home.cmd("books"); + c.args([ + "create", + "zed", + "--test-knobs", + &format!("{KNOBS},timer_hold=1"), + ]) + .env("WB_HOSTILE", "secret"); + let (read_end, write_end) = (fds[0], fds[1]); + // SAFETY: dup2 and close are async-signal-safe and touch only the + // child's own descriptors. + unsafe { + c.pre_exec(move || { + if libc::dup2(write_end, 9) < 0 { + return Err(std::io::Error::last_os_error()); + } + libc::close(read_end); + libc::close(write_end); + Ok(()) + }); + } + let mut create = Logged::start(c, home.dir.path().join("create.log")); + assert!( + wait_for(30, || { + std::fs::read_to_string(run.join("timer-held")) + .is_ok_and(|held| held.lines().any(|l| l == "create:start")) + }), + "the command's server never reached its work: {}", + create.said() + ); + let info = ledger_mcp::local::read_server_info(&run).expect("it says what it is"); + let proc = PathBuf::from(format!("/proc/{}", info.pid)); + let environ = std::fs::read(proc.join("environ")).unwrap(); + let environ = String::from_utf8_lossy(&environ); + assert!(!environ.contains("WB_HOSTILE"), "{environ:?}"); + assert!(environ.contains("PATH=/usr/local/bin:/usr/bin:/bin")); + for entry in std::fs::read_dir(proc.join("fd")).unwrap().flatten() { + let target = std::fs::read_link(entry.path()) + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + assert!( + target != pipe_read && target != pipe_write, + "the invoker's pipe is held by the server: fd {:?} -> {target}", + entry.file_name() + ); + } + assert_eq!( + std::fs::read_link(proc.join("cwd")).unwrap(), + Path::new("/") + ); + // The invoker's own pipe is still its own (the command holds it). + assert!(Path::new("/proc/self/fd").join(fds[0].to_string()).exists()); + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert!( + create.done(40).is_some_and(|s| s.success()), + "{}", + create.said() + ); + // SAFETY: closing the test's own descriptors. + unsafe { + libc::close(fds[0]); + libc::close(fds[1]); + } +} + +/// The app's notice can ask the host that holds the books to close them, +/// with the lease protocol an older host speaks too: what `wanderbooks +/// close` does, for a person with no command line (commands.rs +/// `close_the_host`). +#[test] +fn the_app_can_ask_a_host_that_holds_the_books_to_close_them() { + let home = Home::new("close-host"); + home.create("acme"); + let root = home.root(); + assert!(!ledger_host::commands::a_host_holds(Some(&root))); + assert_eq!( + ledger_host::commands::close_the_host(Some(&root)).as_deref(), + Ok("No program has the books open now.") + ); + home.keep_host(); + assert!(ledger_host::commands::a_host_holds(Some(&root))); + let said = ledger_host::commands::close_the_host(Some(&root)).unwrap(); + assert_eq!(said, "The other program let go of the books."); + assert!(home.wait_closed(20), "the host was left"); + assert!(!ledger_host::commands::a_host_holds(Some(&root))); +} From a61df668eff1116c079b630cd29894113b3a9112 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:30:26 -0700 Subject: [PATCH 11/11] docs: the holder of the books is read from what the server says (WB-app-1, 2, 3, 5) Plan P15 unit A5, fix round. The claims for WB-app-2, 3 and 5 and the invariants of opener.rs, app_server.rs, commands.rs, bridge.rs, serving.rs and ledger-mcp local.rs say: a server says what started it and whether it is closing (run/server.info), only the app's is "the app", a command's server and a closing one are waited for in words inside one `open_wait`, a command racing a start joins it, a command's own server starts clean (and why the app's own child does not), a bridge that held a host follows the app, `books list` shows the upgrade pending, and the app's notice for a host that holds the books has a button. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/serving.rs | 5 ++ crates/ledger-host/src/app_server.rs | 26 ++++++++-- crates/ledger-host/src/bridge.rs | 10 +++- crates/ledger-host/src/commands.rs | 10 +++- docs/spec/claims/app.md | 71 +++++++++++++++++++++------- 5 files changed, 99 insertions(+), 23 deletions(-) diff --git a/crates/ledger-gui/src/serving.rs b/crates/ledger-gui/src/serving.rs index 7fec415d..89b091be 100644 --- a/crates/ledger-gui/src/serving.rs +++ b/crates/ledger-gui/src/serving.rs @@ -24,6 +24,11 @@ //! next tab opens or the person asks (`retry`); the owner has //! stopped the server that failed, so no second one runs beside it. //! A server still starting is waited for, in view (`is_starting`). +//! A start refused because a host holds the books (an earlier +//! build's, or `wanderbooks serve`'s) says what the button will do +//! and what to type instead, and offers the button (`host_blocks`, +//! `close_host`): it asks the host to close the books and starts +//! the server when it has; a close that fails says why. //! 4. A company the window opened at the start is not opened again; a //! company whose open failed, at the start (the server's list says //! it isn't open: `serve_not_open`) or later, is a notice, and is diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index 2727d5ea..f945452c 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -41,11 +41,14 @@ //! request, waiting for the server to be ready first; a close that //! says its last backup was not whole is returned as a notice, never //! as a plain success. -//! 7. Nothing marks a root as the app's. Whether the app (or another -//! server) has a root is read from what is running: no host holds -//! `run/host.lock`, a server holds `run/server.lock`, and its admin -//! socket answers ([`the_apps_server_runs`]). An earlier build wrote -//! a permanent file `run/app-hosted`; it means nothing now and is +//! 7. Nothing marks a root as the app's. What holds a root is read from +//! what runs: no host holds `run/host.lock`, a server holds +//! `run/server.lock`, and the server says what started it and +//! whether it is closing (`run/server.info`, ledger-mcp local.rs +//! INVARIANT 16; [`crate::opener::what_holds`]). Only a server the +//! app started, not closing, with its admin socket answering, is the +//! app's ([`the_apps_server_runs`]). An earlier build wrote a +//! permanent file `run/app-hosted`; it means nothing now and is //! removed at the next start of the app's server ([`RETIRED_MARKER`]). //! With the app closed, the agents' bridge says "Wanderbooks isn't //! running" (bridge.rs INVARIANT 12) whether or not the root was ever @@ -75,6 +78,19 @@ //! request `wanderbooks token revoke` makes, and its copy in the //! token file goes with it ([`AppHost::revoke_token`]). Neither ever //! holds a token's text. +//! 13. A command's own server ([`AppServer::start_for_command`]) is the +//! same server, started as `--started-by command`, and clean: the +//! host's environment only (start.rs `clean_environment`), the root +//! as an absolute path, `/` as its folder (the root's `run/` on +//! Windows), and every server closes the descriptors above 2 at its +//! start whoever started it, so one that outlives its command holds +//! none of the invoker's pipes. The app's own child keeps its +//! environment: it is the window's child, closes with the window and +//! needs the person's session (ssh agent, git configuration) for its +//! backups. A command's server that does not get ready because +//! another program holds the books (one that started after the +//! command's look) has lost: [`AppServer::wait_ready_unless_beaten`] +//! says so, and the command stops it and joins what runs. //! ``` use crate::host::{SERVER_LOG, children_executable, open_log}; diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 3d23a9f2..9ddc1722 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -71,7 +71,15 @@ //! running. A root a host holds (`wanderbooks serve`, the headless //! host) behaves as in 1 to 11: the bridge holds a lease on it; and //! when that host goes and nothing takes its place, the bridge -//! becomes the line above, in words, instead of starting another. +//! becomes the line above, in words, instead of starting another; +//! and when the app takes its place (its lease would be one with no +//! host behind it, which never ends: `Lease::is_hostless`) it +//! becomes the line above too, and says the same words when the app +//! is closed. What holds the books is read before a session is +//! tried (opener.rs INVARIANT 6a): a command's server, for the +//! length of its work, is told as "A wanderbooks command has the +//! books for a moment" (`command_words`), and a server that is +//! closing as the opening words, not as the app. //! ``` use crate::knobs::{FLAG, Knobs}; diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 69597c9c..4ebe37c4 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -27,7 +27,15 @@ //! (waiting for its last backup); one that needs a company held open //! says "Start Wanderbooks first" ([`Direct`], [`reach`]; WB-app-5). //! A server of its own takes the locks the app's server takes, so -//! two programs never hold one set of books. +//! two programs never hold one set of books. What it finds is read, +//! not guessed (opener.rs INVARIANT 6a): only a server the app +//! started is the app's; another command's server, or a closing one, +//! is waited for, in words, inside one `open_wait`. A program that +//! takes the books between its look and its own server's start (the +//! app, `serve`, another command) is joined: its server lets go of +//! the start and it looks again. Its own server is started clean (a +//! host's environment, `/` for its folder), and closes the invoker's +//! descriptors at its start. //! 2. Nothing printed names the data root. //! 3. Adoption and restoring are previewed first and go ahead only on a //! yes at the terminal, or --yes; a vault beside the books must be diff --git a/docs/spec/claims/app.md b/docs/spec/claims/app.md index 00f8c9cc..1285c387 100644 --- a/docs/spec/claims/app.md +++ b/docs/spec/claims/app.md @@ -31,7 +31,8 @@ closes the child's input and waits for it, so none is left running that nothing manages. Nothing marks a root as the app's: an earlier build wrote a permanent `run/app-hosted` file, which means nothing now and is removed at the next start of the app's server; a root that has one works as one that does not. -Whose the books are is read from what runs (WB-app-5). The server is in a +Whose the books are is read from what runs, and from what the server says of +itself (WB-app-5). The server is in a process group of its own on Unix, so a Ctrl+C at the terminal the window was started from reaches the window alone and never closes the books under an open window; on Windows it breaks away from the job a launcher runs the @@ -63,7 +64,11 @@ words and is never swallowed: a close that says its last backup was not whole, a company that would not open for assistants, a server that stopped or never started. A request for one company never waits for another's. A start that failed (another program had the books) is tried again by the next tab that opens, -or by the "Try again" button beside its notice; a server still starting is +or by the "Try again" button beside its notice; when it was a host that held +the books (an earlier build's, or `wanderbooks serve`'s) the notice says what +will happen and carries a "Close it" button that asks that host to close the +books (the lease protocol an older host speaks) and starts the server when it +has, with the command to type (`wanderbooks close`) as the fallback; a server still starting is said to be starting. A company the window wanted open that the server does not have open when it says ready (it failed to open) is a notice for that company. The format upgrade of a company, asked in the window, is an admin @@ -72,7 +77,9 @@ request to this same server (`UpgradeFormat`), since there is no host. `take_notices`), `ledger_gui::app::App::open` and `App::close`, `ledger_host::app_server::AppServer::open_book` and `close_book`, `AppHost::not_open` and `AppHost::upgrade_format`, `Serving::retry`. -*Checked:* `ledger-gui` `tests/serving.rs` (`a_tab_opening_asks_the_server_to_open_that_company`, +*Checked:* `ledger-gui` `tests/host_holds.rs` (the button; `the_notice_in_the_window_has_the_button_and_it_goes_when_the_server_starts`); +`open_while_held.rs` (`the_app_can_ask_a_host_that_holds_the_books_to_close_them`); +`ledger-gui` `tests/serving.rs` (`a_tab_opening_asks_the_server_to_open_that_company`, `a_tab_closing_asks_the_server_to_close_that_company`, `the_companies_the_window_restores_are_the_servers_to_open`, `a_close_that_was_not_whole_is_said_to_the_person`, @@ -101,7 +108,11 @@ Wanderbooks." None is final: the call after the app starts, or the company is opened, goes through, in a session already running. A root a host holds (`wanderbooks serve`) is served as it was: the bridge holds a lease on the host; and when that host goes and nothing takes its place the bridge says -the words above instead of starting another. +the words above instead of starting another; when the app takes its place, +the bridge becomes the line to the app, as a bridge that began without a host +is, and says the same words when the app is closed. A command's own server, for +the length of its work, is said to be that: "A wanderbooks command has the books +for a moment: X can be reached in a moment. Try again shortly." *Enforced:* `ledger_host::bridge` (`serves_the_app`, `keep_in_app`, `keep`, `not_running_words`, `opening_words`, `not_open_words`), INVARIANT 12; `ledger_host::opener::Opener::hold` (INVARIANTS 6, 7). @@ -141,18 +152,33 @@ their companies. **WB-app-5 A command finds what runs, never starts a host, and does its work or says to start Wanderbooks.** Every `wanderbooks …` command that needs the books, and the window's own menu work, finds what holds the root: -a host (`wanderbooks serve`: it takes a lease, as before), the app's server -(no host holds the root, a server holds `run/server.lock`, and its admin -socket answers: it asks that server and leaves it running), or nothing. A -server that holds the lock and has no admin socket yet is opening its -companies or finishing a backup: the command says so ("Wanderbooks is still +a host (`wanderbooks serve`: it takes a lease, as before), the app's server, +or nothing. What holds the root is read, never guessed: a server started with +`--started-by app|host|command` writes `run/server.info` beside its lock (who +started it, its pid, whether it has begun to close), as soon as the lock is its, +and removes it as it lets go; a server that says nothing (an earlier build's) is +taken for the app's. Only a server the app started, not closing, whose admin +socket answers, is "the app": a command asks it and leaves it running. A server +a command started (for the length of its work), and any server that is closing +(the app's, or the orphan of a `serve` host that was killed), is waited for by a +command or `serve`, in words ("Another wanderbooks command has the books open for +a moment: waiting for it to finish…", "Wanderbooks is closing the books (a last +backup is being made): waiting for it to finish…"), inside the same `open_wait`, +and then they go on; at the end of it they say what they still wait for. +`close` and `doctor` say the true thing for each (never "the app" for what is +not), and a bridge says a command's server has the books for a moment. A command +that finds nothing runs its own server; if another program takes the books +between its look and its server's start, it lets its start go and joins what now +runs, inside the same one wait. A server that holds the lock and has no admin +socket yet is opening its companies or finishing a backup: the command says so ("Wanderbooks is still opening (or closing) the books: waiting for it…") and waits, for as long as its own wait lasts (`open_wait`, 120 s), then says it is still opening and to try again; it never fails with a connection error and never starts a second server beside it. With nothing running, no command starts a host. One that only reads, or manages the books' files and tokens, runs a books -server of its own, the one the app starts, for the length of the work and -closes it (waiting for its last backup, 90 s at most, and saying so if it +server of its own, the one the app starts, started clean as a host's is (the +host's environment, `/` for its folder, no descriptor of the invoker's), for the +length of the work and closes it (waiting for its last backup, 90 s at most, and saying so if it is still finishing); it takes the same `run/server.lock` and `run/books.lock` the app's server takes, so two programs never hold one set of books, and a start is refused in words when another has them. One that needs a company @@ -165,7 +191,7 @@ replaced program and its daily look for an update. | Command | The app (or `serve`) running | Nothing running | |---|---|---| -| `books list` | the server's list, open or closed | the folder's companies, "not open", no lock taken (nothing is read of them) | +| `books list` | the server's list, open or closed | the folder's companies, "not open", no lock taken; what each journal declares is read (nothing written, the chain not verified) to say which wait for a format upgrade | | `books create`, `adopt`, `restore` | the server does it | its own server, no company open, closed after | | `books put-aside` | works on the folder itself, as it always has: it never asked a server, and moves only copies outside the root into `legacy/` after reading the company's journal head; it takes no lock | the same | | `books back-up ID`, `books upgrade ID`, `books extract ID N` | the server does it (the upgrade as an admin request when there is no host) | its own server with ID open, closed after | @@ -182,9 +208,11 @@ replaced program and its daily look for an update. There is no "Close the books" in the app: closing a company's tab closes the company (WB-app-2) and closing the window closes them all (WB-app-4). *Enforced:* `ledger_host::opener::Opener::hold` (`HoldError::NotRunning`, -`admin_answers`), `ledger_host::commands` (`direct_for`, `reach`, -`Reached::release`, `listed_while_closed`, `upgrade_by_admin`, `doctor`, -`close`). +`what_holds`, `Holder`, `admin_answers`), ledger-mcp `local::run` +(`--started-by`, `run/server.info`, INVARIANT 16), `ledger_host::app_server` +(`AppServer::start_for_command`, `wait_ready_unless_beaten`), +`ledger_host::commands` (`direct_for`, `reach`, `Reached::release`, +`listed_while_closed`, `upgrade_by_admin`, `doctor`, `close`). *Checked:* `ledger-cli` `app_server.rs` (`a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running`, `with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks`, @@ -195,4 +223,15 @@ the company (WB-app-2) and closing the window closes them all (WB-app-4). `a_command_ends_at_its_deadline_during_a_restart`, `the_viewers_new_books_are_made_by_the_server`); `format_upgrade.rs` (`format_upgrade_waits_for_consent`: a command's own -server shows the upgrade its company waits for). +server shows the upgrade its company waits for; +`a_list_with_nothing_running_says_which_books_wait_for_an_upgrade`); +`open_while_held.rs` (`serve_waits_in_words_for_a_server_that_is_closing_and_then_holds_the_books`, +`a_command_and_the_words_of_close_and_doctor_know_a_server_is_closing`, +`a_command_waits_for_another_commands_server_and_does_not_attach_to_it`, +`a_serve_waits_for_a_commands_server_and_then_holds_the_books`, +`a_server_says_what_started_it_and_when_it_closes`, +`a_commands_own_server_holds_the_books_while_it_works_and_others_are_refused`, +`a_commands_own_server_holds_none_of_the_invokers_environment_or_pipes`, +`a_command_racing_the_apps_start_joins_the_app`, +`two_commands_at_once_with_nothing_running_both_do_their_work`, +`a_bridge_that_held_a_host_follows_the_app_that_takes_its_place`).