feat(mcp): open and close one book while the server runs, and say who is connected

The desktop app is a window with a tab per company (plan/p15-app-and-relay.md
3.1, D-77, D-78): a company must be reachable by agents exactly while its tab
is open, so the books server can now open and close ONE book at run time
instead of opening every book at start and closing only with the process.

Close is ordered so that a call either ran completely (and is in the journal)
or was refused unrun: the book's door (a per-book gate every route enters
before it touches the book, its access log included) is shut and the book is
listed closed, so no new call gets in; SharedStore::close stops tools
starting and waits for those that did; the gate is waited empty for the
upload, download, export and MCP handlers inside; sessions end; the last
backup of the server's own close runs; and the store is let go, releasing
its writer lock. Only then is 'closed' answered. Another book's door, store
and sessions are never touched or waited on.

A closed book is a state of its own (not a problem): listed closed, and a
call for it is told apart from one for a book that does not exist, on the MCP,
upload, download and export routes, in words an agent can relay. Start gains
--open all|none|IDS (default all).

Sessions: a small in-memory board per book (sessions.rs) keeps what the
client said at initialize, the agent's self-report, calls running and the
last call, joined with the sessions the server already binds to tokens; the
admin 'sessions' request lists the token's NAME, never its text or hash, and
doctor prints it. Backups of a book let go push and record nothing more.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 09:02:02 -07:00
1 parent 526c27233e
commit f7f75fb380
10 files changed
+1414 -97

No files matched your search

+127 -1
View File
@@ -474,10 +474,18 @@ fn books_usage(prog: &str) {
eprintln!(" {prog} back-up ID [--new-disk]");
eprintln!(" {prog} upgrade ID");
eprintln!(" {prog} extract BOOK ATTACHMENT");
eprintln!(" {prog} open ID");
eprintln!(" {prog} close ID");
eprintln!(
" {prog} put-aside ID DATA-DIR [--vault DIR --vault-key FILE] [PATH...] [--yes]"
);
eprintln!(" list the books, and whether each is open");
eprintln!(" list the books, and whether each is open or closed");
eprintln!(
" open open one closed book while the server runs, checked as at its start (agents can reach it from then)"
);
eprintln!(
" close close one book while the server runs: its running calls finish, its sessions end, it is backed up and let go; the others keep serving"
);
eprintln!(" create start new, empty books (base currency USD unless given)");
eprintln!(" adopt copy existing books in, verified; the original is left as it was");
eprintln!(
@@ -604,6 +612,18 @@ pub fn books(
};
return put_aside(&common, book, old, yes);
}
["open", book] => with_server(
&common,
Request::OpenBook {
id: (*book).to_string(),
},
),
["close", book] => with_server(
&common,
Request::CloseBook {
id: (*book).to_string(),
},
),
["back-up", book] => {
return match back_up_now(&common, book, new_disk) {
Ok(lines) => {
@@ -666,6 +686,44 @@ pub fn books(
}
Ok(())
}
Ok(Response::OpenBook { id, outcome }) => match outcome {
admin::OpenOutcome::Opened => {
println!("Opened the books \"{id}\": agents can reach them now.");
Ok(())
}
admin::OpenOutcome::AlreadyOpen => {
println!("The books \"{id}\" are open already.");
Ok(())
}
admin::OpenOutcome::NoSuchBook => {
eprintln!(
"error: there are no books called \"{id}\": `wanderbooks books list` lists them"
);
Err(exit(1))
}
admin::OpenOutcome::CouldNotOpen(why) => {
eprintln!("error: the books \"{id}\" couldn't be opened: {why}");
Err(exit(1))
}
},
Ok(Response::CloseBook { id, outcome }) => match outcome {
admin::CloseOutcome::Closed => {
println!(
"Closed the books \"{id}\": nothing is running on them, their sessions ended, and they are let go."
);
Ok(())
}
admin::CloseOutcome::WasNotOpen => {
println!("The books \"{id}\" weren't open.");
Ok(())
}
admin::CloseOutcome::NoSuchBook => {
eprintln!(
"error: there are no books called \"{id}\": `wanderbooks books list` lists them"
);
Err(exit(1))
}
},
Ok(Response::Refused(why)) | Err(why) => {
eprintln!("error: {why}");
Err(exit(1))
@@ -679,6 +737,12 @@ pub fn books(
/// One book, as `books list` and `doctor` show it.
fn book_line(b: &admin::BookStatus) -> String {
if b.closed {
return format!(
"{} closed (`wanderbooks books open {}` opens it)",
b.id, b.id
);
}
match (&b.problem, &b.format_upgrade) {
(Some(why), _) => format!("{} didn't open: {why}", b.id),
(None, Some(_)) => format!(
@@ -689,6 +753,54 @@ fn book_line(b: &admin::BookStatus) -> String {
}
}
/// `doctor`'s lines for who is connected to each open book: the token's
/// name, the client and agent as they said, when it connected, the calls
/// running and the last call.
fn session_lines(open: &[admin::BookSessions]) -> Vec<String> {
let mut lines = Vec::new();
if open.iter().all(|b| b.sessions.is_empty()) {
lines.push("Assistants connected: none.".to_string());
return lines;
}
lines.push("Assistants connected:".to_string());
for b in open {
if b.sessions.is_empty() {
lines.push(format!(" {}: none", b.book));
continue;
}
lines.push(format!(" {}:", b.book));
for s in &b.sessions {
let client = match (&s.client_name, &s.client_version) {
(Some(n), Some(v)) => format!("{n} {v}"),
(Some(n), None) => n.clone(),
_ => "a client that hasn't said who it is".to_string(),
};
let mut line = format!(" token {:?}, {client}", s.token);
if let Some(a) = &s.agent {
let said: Vec<&str> = [&a.model, &a.reasoning_effort, &a.harness]
.into_iter()
.filter_map(|v| v.as_deref())
.collect();
if !said.is_empty() {
line.push_str(&format!(" (says: {})", said.join(", ")));
}
}
line.push_str(&format!(", connected {}", s.connected_at));
line.push_str(&match s.running {
0 => ", no call running".to_string(),
1 => ", 1 call running".to_string(),
n => format!(", {n} calls running"),
});
match &s.last {
Some(l) => line.push_str(&format!(", last {} ({}) at {}", l.tool, l.outcome, l.at)),
None => line.push_str(", no call yet"),
}
lines.push(line);
}
}
lines
}
/// The projection database a book uses, and the other schemas' files
/// beside it (left as they are for the versions that wrote them, never
/// deleted), as `doctor` says them; None when it didn't open.
@@ -2499,6 +2611,18 @@ pub fn doctor(
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(_) => {}
}
}
} else {
println!("The books are opening (the books server isn't ready yet).");
@@ -3516,6 +3640,7 @@ mod tests {
|problem: Option<&str>, waiting: Option<admin::FormatWaiting>| admin::BookStatus {
id: "acme".into(),
open: problem.is_none(),
closed: false,
problem: problem.map(str::to_string),
format_upgrade: waiting,
database: None,
@@ -3566,6 +3691,7 @@ mod tests {
let mut b = admin::BookStatus {
id: "acme".into(),
open: true,
closed: false,
problem: None,
format_upgrade: None,
database: Some("wanderbooks.v13.db".into()),
+35 -1
View File
@@ -61,6 +61,17 @@ pub fn caller(context: &RequestContext<RoleServer>) -> Option<Caller> {
.cloned()
}
/// The MCP session a request belongs to (its `mcp-session-id`), as the
/// door left the request's parts in `extensions`; None for a request that
/// came another way.
pub(crate) fn session_of(extensions: &rmcp::model::Extensions) -> Option<String> {
extensions
.get::<axum::http::request::Parts>()
.and_then(|parts| parts.headers.get(crate::local::SESSION_HEADER))
.and_then(|v| v.to_str().ok())
.map(str::to_string)
}
/// The client program, as it named itself at `initialize`.
fn client(context: &RequestContext<RoleServer>) -> Option<Client> {
context.peer.peer_info().map(|info| Client {
@@ -87,6 +98,12 @@ pub(crate) struct Call {
subject: String,
args_digest: Option<String>,
agent: Option<ledger_store::access::Agent>,
/// The book's board of live sessions, and the session this call is
/// in: it counts as running there until the call ends, and is what
/// the session last did once recorded (sessions.rs).
board: Arc<crate::sessions::Board>,
session: Option<String>,
_live: Option<Arc<crate::sessions::Live>>,
}
/// Why a call wasn't run, for its record and its answer.
@@ -113,11 +130,16 @@ impl Call {
/// close beginning meanwhile waits for it.
pub(crate) fn new(
log: &Arc<AccessLog>,
board: &Arc<crate::sessions::Board>,
context: &RequestContext<RoleServer>,
action: &'static str,
subject: &str,
) -> Self {
let session = session_of(&context.extensions);
Self {
board: board.clone(),
_live: session.as_deref().map(|sid| Arc::new(board.begin(sid))),
session,
log: log.clone(),
caller: caller(context),
client: client(context),
@@ -187,7 +209,19 @@ impl Call {
agent: self.agent.clone(),
};
match self.log.record(&access) {
Ok(_) => Ok(()),
Ok(_) => {
if let Some(sid) = &self.session {
self.board.finished(
sid,
&access.subject,
&access.result,
access.client.as_ref(),
access.agent.as_ref(),
chrono::Utc::now().timestamp(),
);
}
Ok(())
}
Err(e) => {
eprintln!("wanderbooks server: an access record couldn't be written: {e}");
Err(())
+144 -2
View File
@@ -8,7 +8,8 @@
//! the data root itself: the server, its sole writer, does it.
//! SOURCE: plan/served.md 3.1 (the CLI "talks to run/admin.sock ... it can
//! create or adopt books"), 5.5 (adoption), 3.9 (protocol versions
//! N and N-1).
//! N and N-1); plan/p15-app-and-relay.md 3.1 (open and close one
//! book at run time; who is connected), D-77, D-78.
//! INVARIANTS:
//! 1. One request per connection, one JSON line each way, at most
//! MAX_LINE bytes; anything else is refused with a plain reason.
@@ -30,6 +31,15 @@
//! 7. A format upgrade is asked with the owner passphrase, which the
//! server checks before anything is done (plan 3.9, D-39); no answer
//! carries it, and Debug never shows it.
//! 8. Opening and closing ONE book (`open_book`, `close_book`) are
//! admin requests (plan/p15-app-and-relay.md 3.1; D-77, D-78): each
//! answers what happened in a word (opened, already open, closed,
//! was not open, no such book, could not open with why), and a book
//! that is closed is listed as closed, which is not a problem.
//! 9. `sessions` says, for each open book, who is connected: a token's
//! NAME (never its text, nor its hash), what the client and the agent
//! said of themselves, when it connected, how many of its calls are
//! running, and its last call. A session that ended is not listed.
//! ```
use serde::{Deserialize, Serialize};
@@ -174,6 +184,22 @@ pub enum Request {
/// The attachment to read.
attachment_id: u64,
},
/// Open one book that is not open (INVARIANT 8): checked and verified
/// exactly as at the server's start.
OpenBook {
/// The books.
id: String,
},
/// Close one book while the server runs (INVARIANT 8): new calls on it
/// are refused from the moment this begins, the calls running on it
/// finish, its sessions end, and it is let go of as at the server's
/// close (a last backup, its writer lock released).
CloseBook {
/// The books.
id: String,
},
/// Who is connected to each open book (INVARIANT 9).
Sessions,
/// End a token.
TokenRevoke {
/// Its books.
@@ -298,6 +324,11 @@ pub struct BookStatus {
pub id: String,
/// Whether it is open and served.
pub open: bool,
/// Whether it was closed (at the server's start, or by `close_book`):
/// not open, and no problem. A book that failed to open is not closed:
/// it has a `problem`.
#[serde(default)]
pub closed: bool,
/// Why it couldn't be opened, if it couldn't.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub problem: Option<String>,
@@ -314,6 +345,93 @@ pub struct BookStatus {
pub other_databases: Vec<String>,
}
/// What `open_book` came to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenOutcome {
/// It was closed (or had failed to open) and is open now.
Opened,
/// It was open already: nothing was done.
AlreadyOpen,
/// There are no such books in the data root.
NoSuchBook,
/// It could not be opened, and why (it stays listed, with this
/// `problem`).
CouldNotOpen(String),
}
/// What `close_book` came to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CloseOutcome {
/// It was open and is closed now: no call on it is running, its
/// sessions ended, and another process could open it.
Closed,
/// It was not open (closed already, or it never opened): nothing was
/// done.
WasNotOpen,
/// There are no such books in the data root.
NoSuchBook,
}
/// What an agent said about itself (`books.start`'s `agent`): asserted,
/// never checked.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionAgent {
/// The model's name.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
/// The reasoning effort it ran at.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<String>,
/// The program driving it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub harness: Option<String>,
}
/// A session's last call.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastCall {
/// The tool (or the resource's address).
pub tool: String,
/// "ok", "error", or "refused: CODE".
pub outcome: String,
/// When it finished (UTC, RFC 3339).
pub at: String,
}
/// One live MCP session (INVARIANT 9).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionInfo {
/// The NAME of the token it was opened with: never the token.
pub token: String,
/// The client program's name, as it said at `initialize`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_name: Option<String>,
/// Its version.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_version: Option<String>,
/// What the agent said about itself, if it has.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub agent: Option<SessionAgent>,
/// When it connected (UTC, RFC 3339).
pub connected_at: String,
/// Calls of it running now.
pub running: u32,
/// The last call it made, if it has made one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last: Option<LastCall>,
}
/// An open book's live sessions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BookSessions {
/// The books.
pub book: String,
/// Its live sessions, the longest connected first.
pub sessions: Vec<SessionInfo>,
}
/// A setting an adoption would move in.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SettingChange {
@@ -486,6 +604,22 @@ pub enum Response {
},
/// A format upgrade made (or none needed).
FormatUpgraded(FormatUpgraded),
/// What `open_book` came to.
OpenBook {
/// The books.
id: String,
/// What happened.
outcome: OpenOutcome,
},
/// What `close_book` came to.
CloseBook {
/// The books.
id: String,
/// What happened.
outcome: CloseOutcome,
},
/// Who is connected, for each open book (INVARIANT 9).
Sessions(Vec<BookSessions>),
/// An attachment's text read and journaled (plan P6 step 2).
Extracted {
/// The attachment.
@@ -536,7 +670,13 @@ pub fn call_within(
let not_sent = |why: String| CallError::NotSent(why);
// A list changes nothing: its only question is whether it answered.
let look = match request {
Request::List | Request::TokenList | Request::TokenCheck { .. } => None,
Request::List
| Request::TokenList
| Request::TokenCheck { .. }
| Request::Sessions => None,
Request::OpenBook { .. } | Request::CloseBook { .. } => {
Some("`wanderbooks books list` says whether the books are open")
}
Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => {
Some("`wanderbooks books list` shows the books there are")
}
@@ -699,6 +839,7 @@ mod tests {
for r in [
Response::Books(vec![
BookStatus {
closed: false,
id: "acme".into(),
open: false,
problem: Some("damaged".into()),
@@ -707,6 +848,7 @@ mod tests {
other_databases: Vec::new(),
},
BookStatus {
closed: false,
id: "beta".into(),
open: true,
problem: None,
+8
View File
@@ -354,6 +354,11 @@ impl Backups {
/// says it is a new disk).
pub async fn run_with(&self, why: &str, new_disk: bool) -> Result<Status, String> {
let _one = self.running.lock().await;
// Books let go of (closed, or replaced by a restore) push nothing
// more, and leave no record of a run that never began.
if self.store.is_stopped() {
return Err(crate::server::STOPPED.to_string());
}
if self.named().await.is_empty() {
return Ok(self.status().await);
}
@@ -558,6 +563,9 @@ impl Backups {
/// Drill each target whose drill is due (INVARIANT 5), each recorded.
pub async fn drill(&self) {
let _one = self.running.lock().await;
if self.store.is_stopped() {
return;
}
let records = self.records();
let now = chrono::Utc::now();
for n in self.named().await {
+1
View File
@@ -15,6 +15,7 @@ pub mod opening;
mod policy;
pub mod scopes;
mod server;
mod sessions;
mod settings;
mod tin_files;
mod types;
File diff suppressed because it is too large. Load diff
+5 -15
View File
@@ -28,22 +28,12 @@ impl FuzzDoor {
let home = tempfile::tempdir().expect("a folder");
let (root, _) =
Root::setup(home.path(), Some(&home.path().join("root")), None).expect("a data root");
let books = Arc::new(Books {
let books = Arc::new(Books::new(
root,
held: RwLock::new(BTreeMap::new()),
sessions: CancellationToken::new(),
closing: CancellationToken::new(),
in_flight: AtomicUsize::new(0),
finished: tokio::sync::Notify::new(),
last_arrival: std::sync::atomic::AtomicU64::new(0),
started: Instant::now(),
principals: RwLock::new(Err(String::new())),
session_tokens: Mutex::new(BTreeMap::new()),
backup_quiet: BACKUP_QUIET,
drill_first: DRILL_FIRST,
restoring: Mutex::new(()),
isolation: Isolation::SameUser,
});
BACKUP_QUIET,
DRILL_FIRST,
Isolation::SameUser,
));
let loaded = books.load_principals();
*books.principals.write().unwrap() = loaded;
match books.admin(Request::Create {
+25 -2
View File
@@ -74,6 +74,8 @@ pub struct BooksServer {
exports: ledger_store::exports::Exports,
/// The books' backups (backup.rs).
backups: Arc<crate::backup::Backups>,
/// Who is connected, and what each is doing (sessions.rs).
board: Arc<crate::sessions::Board>,
/// How these books are kept from agents (plan 3.8, P9a): what
/// `books.start` reports.
isolation: Isolation,
@@ -128,6 +130,8 @@ pub(crate) struct Served {
pub(crate) uploads: ledger_store::uploads::Uploads,
pub(crate) exports: ledger_store::exports::Exports,
pub(crate) backups: Arc<crate::backup::Backups>,
/// Its live sessions' board (sessions.rs), read by the admin socket.
pub(crate) board: Arc<crate::sessions::Board>,
pub(crate) isolation: Isolation,
}
@@ -178,6 +182,7 @@ impl Served {
uploads,
exports,
backups,
board: Arc::default(),
isolation,
})
}
@@ -547,6 +552,7 @@ impl BooksServer {
uploads: served.uploads.clone(),
exports: served.exports.clone(),
backups: served.backups.clone(),
board: served.board.clone(),
isolation: served.isolation,
}
}
@@ -1744,7 +1750,7 @@ impl ServerHandler for BooksServer {
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
use crate::access::{self, Call};
use ledger_store::access::Outcome;
let mut call = Call::new(&self.access, &context, "tool", &request.name);
let mut call = Call::new(&self.access, &self.board, &context, "tool", &request.name);
let outcome_of = |out: &Result<rmcp::model::CallToolResponse, rmcp::ErrorData>| match out {
Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => {
Outcome::Ok
@@ -1944,6 +1950,23 @@ impl ServerHandler for BooksServer {
})
}
/// The client has said who it is: the session's board (sessions.rs)
/// knows it before the session's first call.
async fn on_initialized(&self, context: rmcp::service::NotificationContext<RoleServer>) {
if let (Some(sid), Some(info)) = (
crate::access::session_of(&context.extensions),
context.peer.peer_info(),
) {
self.board.initialized(
&sid,
ledger_store::access::Client {
name: info.client_info.name.clone(),
version: info.client_info.version.clone(),
},
);
}
}
fn get_info(&self) -> ServerConfig {
// A client connecting after a settings change sees the change
// (never waiting for the books here; a request holding them syncs
@@ -2011,7 +2034,7 @@ impl ServerHandler for BooksServer {
use ledger_store::access::Outcome;
// Reading a resource is reading the books: books:read, recorded
// (access.rs).
let call = Call::new(&self.access, &context, "resource", &request.uri);
let call = Call::new(&self.access, &self.board, &context, "resource", &request.uri);
let result = self.resource(request, &call).await;
{
let outcome = match &result {
+1
View File
@@ -1454,6 +1454,7 @@ fn an_access_record_that_cant_be_written_stops_the_books_and_says_so() {
let (server, _books) = unwritable("unrecorded-refusal");
let call = crate::access::Call::new(
&server.access,
&server.board,
&context(&s.peer, Some(ALL)),
"tool",
"books.chart",
+217
View File
@@ -0,0 +1,217 @@
//! Who is connected to a book right now: the in-memory board of one
//! book's live MCP sessions (plan/p15-app-and-relay.md 3.1, D-77).
//!
//! ```text
//! GOAL: the app can say, for each open book, which assistants are
//! connected and what each is doing, without reading the access log
//! back and without ever holding a token.
//! SOURCE: plan/p15-app-and-relay.md 3.1 (the sessions request: client name
//! and version, the token's name, in-flight calls, the last tool
//! and when); D-77 (the app is the host); D-78 (one tab per
//! company: a connection names its company).
//! INVARIANTS:
//! 1. The board holds what the client and the agent SAID of themselves
//! (asserted, never checked), each masked of any full TIN and cut to
//! the access log's own limit (ledger_store::access::asserted); never
//! a token, its text or its hash.
//! 2. A call is counted as running from the moment it is made until its
//! blocking work and its record are done, even if its client hung
//! up (the count rides in the call, as the store's own does).
//! 3. A session that ended is not listed: the board is read only for
//! the sessions the server still binds (local.rs `session_tokens`),
//! and a note for another is dropped.
//! 4. Nothing here is durable: a restarted server knows no session, as
//! its clients know theirs ended.
//! ```
use ledger_store::access::{Agent, Client, Outcome, asserted};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
/// What one session has said and done.
#[derive(Clone, Debug, Default)]
pub(crate) struct Note {
/// The client program, as it named itself at `initialize`.
pub client: Option<Client>,
/// What the agent said about itself, the latest time it did.
pub agent: Option<Agent>,
/// Calls running now (INVARIANT 2).
pub running: usize,
/// The last call that finished: its tool (or resource), what came of
/// it, and when (seconds since the epoch, UTC).
pub last: Option<Last>,
}
/// A call that finished.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Last {
/// The tool's name, or the resource's address.
pub subject: String,
/// What came of it.
pub outcome: Outcome,
/// When (seconds since the epoch, UTC).
pub at: i64,
}
/// One book's live sessions' notes, by MCP session id.
#[derive(Default)]
pub(crate) struct Board {
notes: Mutex<HashMap<String, Note>>,
}
/// A call running (INVARIANT 2): counted while it lives.
pub(crate) struct Live {
board: Arc<Board>,
sid: String,
}
impl Drop for Live {
fn drop(&mut self) {
let mut notes = self.board.notes();
if let Some(note) = notes.get_mut(&self.sid) {
note.running = note.running.saturating_sub(1);
}
}
}
fn client_of(client: Client) -> Client {
Client {
name: asserted(&client.name),
version: asserted(&client.version),
}
}
fn agent_of(agent: Agent) -> Agent {
Agent {
model: agent.model.as_deref().map(asserted),
reasoning_effort: agent.reasoning_effort.as_deref().map(asserted),
harness: agent.harness.as_deref().map(asserted),
}
}
impl Board {
fn notes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Note>> {
self.notes.lock().unwrap_or_else(|e| e.into_inner())
}
/// The session `sid` said who its client is (`initialize`).
pub fn initialized(&self, sid: &str, client: Client) {
self.notes().entry(sid.to_string()).or_default().client = Some(client_of(client));
}
/// A call of `sid` began (INVARIANT 2).
pub fn begin(self: &Arc<Self>, sid: &str) -> Live {
self.notes().entry(sid.to_string()).or_default().running += 1;
Live {
board: self.clone(),
sid: sid.to_string(),
}
}
/// A call of `sid` is done and recorded: what it was, what came of
/// it, and what its client and agent said, if they did.
pub fn finished(
&self,
sid: &str,
subject: &str,
outcome: &Outcome,
client: Option<&Client>,
agent: Option<&Agent>,
at: i64,
) {
let mut notes = self.notes();
let note = notes.entry(sid.to_string()).or_default();
if let Some(client) = client {
note.client = Some(client_of(client.clone()));
}
if let Some(agent) = agent {
note.agent = Some(agent_of(agent.clone()));
}
note.last = Some(Last {
subject: asserted(subject),
outcome: outcome.clone(),
at,
});
}
/// The session `sid` ended.
pub fn forget(&self, sid: &str) {
self.notes().remove(sid);
}
/// The notes of the sessions `live` still names, and no other
/// (INVARIANT 3): the others are dropped.
pub fn snapshot(&self, live: &[String]) -> HashMap<String, Note> {
let mut notes = self.notes();
notes.retain(|sid, note| note.running > 0 || live.contains(sid));
live.iter()
.map(|sid| (sid.clone(), notes.get(sid).cloned().unwrap_or_default()))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn client(name: &str) -> Client {
Client {
name: name.into(),
version: "1.2".into(),
}
}
#[test]
fn a_call_counts_as_running_until_its_guard_is_dropped() {
let board = Arc::new(Board::default());
let (a, b) = (board.begin("s1"), board.begin("s1"));
assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 2);
drop(a);
assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 1);
drop(b);
assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 0);
}
#[test]
fn the_last_call_and_what_the_client_said_are_kept_and_masked() {
let board = Board::default();
board.initialized("s1", client("Claude Code"));
board.finished(
"s1",
"books.chart",
&Outcome::Ok,
Some(&client("Claude Code 123-45-6789")),
Some(&Agent {
model: Some("m".into()),
reasoning_effort: None,
harness: Some("h".into()),
}),
100,
);
board.finished("s1", "books.trial_balance", &Outcome::Error, None, None, 200);
let note = &board.snapshot(&["s1".into()])["s1"];
let said = note.client.as_ref().unwrap();
assert!(!said.name.contains("6789"), "a TIN is masked: {said:?}");
assert_eq!(note.agent.as_ref().unwrap().model.as_deref(), Some("m"));
assert_eq!(
note.last,
Some(Last {
subject: "books.trial_balance".into(),
outcome: Outcome::Error,
at: 200
})
);
}
#[test]
fn a_session_that_ended_is_not_listed_and_its_note_is_dropped() {
let board = Board::default();
board.initialized("gone", client("x"));
board.initialized("kept", client("y"));
let listed = board.snapshot(&["kept".into()]);
assert_eq!(listed.keys().collect::<Vec<_>>(), vec!["kept"]);
assert!(board.notes().get("gone").is_none());
board.forget("kept");
assert!(board.notes().is_empty());
}
}