//! The documents seam — what these tools need of a pipeline they do not own.//!//! **THIS IS A SEAM, NOT AN IMPLEMENTATION.** The documents WORKER — text//! extraction, mupdf, the password loop, the profiling model, the run's//! statuses — is the worker slice's (2f). What the MCP tools need of it is the//! six operations below and nothing else, so they are declared here, as a//! trait, in exactly the shape agent L's `GoogleWorker` takes: a trait, an//! [`IdleDocuments`] that does nothing and DIALS NOTHING, and a//! [`ScriptedDocuments`] test double that lives beside the trait rather than in//! `tests/`.//!//! ABSENT IS A STATE, NOT A BUG. `ToolServices::documents` is `None` on a//! server with no object store, and every tool that needs bytes refuses BY NAME//! — "`get_document_bytes` needs document storage, which this server is not//! configured to reach. Reading, searching and listing still work." That is the//! TypeScript's own `documentServices(ctx, what)` sentence, and it is the//! difference between a tool that tells the truth and one that half-works.//!//! BLOCKING, for the reason every rail on `ToolServices` is: a handler is//! synchronous by design (S7 — nothing may await while holding the file's//! driver), so the async object store is bridged on the SERVER's side, on a//! thread that is already a blocking one.use std::sync::{Arc, Mutex};/// What a password run answered.#[derive(Debug, Clone, PartialEq, Eq)]pubenumRunOutcome {/// A password opened it and the pipeline finished.Ready,/// None of the candidates opened it.Locked,/// The run finished in some other status the pipeline writes.Other(String),}implRunOutcome {pubfn status(&self) -> &str {matchself {RunOutcome::Ready => "ready",RunOutcome::Locked => "locked",RunOutcome::Other(status) => status.as_str(), } }}/// Why a rail call could not be made — relayed to the caller verbatim.pubtypeRailResult<T> = Result<T, String>;/// The documents pipeline, as the MCP tools need it.////// Five operations, because five are all nine tools ask for. The upload URL is/// NOT one of them: `ToolServices::presign_put` is the shared signer every/// uploading tool goes through, and two rails able to sign one PUT would be two/// answers to "how long is a slot good for". `runDocumentPipeline` itself, the/// extractors, the profiler and the sweep are the worker's own surface and/// belong with the worker in 2f — a tool never calls any of them except through/// [`Self::run_password_candidates`].pubtraitDocumentsRail: Send + Sync + std::fmt::Debug {/// The bytes at one key, or `None` when the object is not there.////// A miss is a FACT, not an error: a document whose bytes were already/// deleted is a real state, and the tool answers "this document's file is/// missing".fn get(&self, key: &str) -> RailResult<Option<Vec<u8>>>;/// Server-side copy. A "move" is copy + delete, because S3 has no rename/// and pulling the bytes through the server for one is not a rename.fn copy(&self, from_key: &str, to_key: &str) -> RailResult<()>;/// Missing keys are NOT errors: a delete must be safe to retry after a/// partial failure, which is what lets "objects first, then the row" hold.fn delete(&self, keys: &[String]) -> RailResult<()>;/// Try to take the workspace's documents slot.////// `Ok(false)` means somebody else holds it — the caller says/// `SLOT_BUSY_NOTE` and stops rather than queueing, because chaining would/// hold an MCP call open for a whole pass. The slot is released when/// [`Self::release_slot`] is called; a tool that took it must always/// release it.fn take_slot(&self, workspace_id: &str) -> RailResult<bool>;fn release_slot(&self, workspace_id: &str);/// The password loop over one document, INSIDE a slot the caller holds.////// The SAME pipeline the worker and the app's route run: the hint is in the/// covering email ("your date of birth in DDMMYYYY"), so the guessing/// happens where the hint is and Cotton just tries them. A candidate that/// does not open the file is never stored, so there is nothing a worker/// could pick up later.////// The server's rail ANSWERS a run its dispatcher made before it took the/// file ([`crate::mcp::dispatch::BeforeTheFile::TryPasswords`]) and never/// runs one from here: the handler holds the file, and the pipeline/// writes it.fn run_password_candidates( &self, workspace_id: &str, document_id: &str, candidates: &[String], ) -> RailResult<RunOutcome>;}/// A rail that does nothing, holds no slot, and — the property the suite leans/// on — DIALS NOTHING and TOUCHES NO DISK.////// It is not a stub standing in for a missing answer. It is never mounted: a/// server with no object store carries `documents: None`, and the tools refuse/// by name. `IdleDocuments` exists so a harness can say "a rail is present and/// it can do nothing", which is a different failure from "there is no rail",/// and both have to be tellable apart.#[derive(Debug, Clone, Copy, Default)]pubstructIdleDocuments;implDocumentsRailforIdleDocuments {fn get(&self, _key: &str) -> RailResult<Option<Vec<u8>>> {Ok(None) }fn copy(&self, _from_key: &str, _to_key: &str) -> RailResult<()> {Err("this server has no object store to copy in".to_string()) }fn delete(&self, _keys: &[String]) -> RailResult<()> {Ok(()) }fn take_slot(&self, _workspace_id: &str) -> RailResult<bool> {Ok(true) }fn release_slot(&self, _workspace_id: &str) {}fn run_password_candidates( &self, _workspace_id: &str, _document_id: &str, _candidates: &[String], ) -> RailResult<RunOutcome> {Err("this server has no document pipeline to run".to_string()) }}/// What a suite scripts, and what it records having been asked.////// Beside the trait rather than in `tests/`, so every suite that needs a/// documents rail scripts it the same way and a change to the trait breaks the/// double in the same commit.#[derive(Debug, Default)]pubstructScriptedDocuments { inner: Mutex<ScriptedState>,}#[derive(Debug, Default)]structScriptedState {/// key → bytes. A key that is not here reads as "the object is not there". objects: Vec<(String, Vec<u8>)>,/// Workspaces whose slot is taken right now. held: Vec<String>,/// When true, `take_slot` answers `false` — the busy branch. slot_busy: bool,/// What the next password run answers. run_outcome: Option<RunOutcome>,/// When set, the password run REFUSES with this sentence — the state a/// server whose object store carries no pipeline behind it is really in. run_refusal: Option<String>,/// Every call, in order: `("copy", "from→to")` and friends. calls: Vec<(String, String)>,}implScriptedDocuments {pubfn new() -> Arc<ScriptedDocuments> {Arc::new(ScriptedDocuments::default()) }/// Put bytes at a key, as an upload would have.pubfn put(&self, key: &str, bytes: Vec<u8>) {letmut state = self.lock(); state.objects.retain(|(held, _)| held != key); state.objects.push((key.to_string(), bytes)); }pubfn has(&self, key: &str) -> bool {self.lock().objects.iter().any(|(held, _)| held == key) }/// The bytes at a key, or `None` — for a suite proving WHICH bytes moved/// where, not merely that something is there.pubfn bytes_at(&self, key: &str) -> Option<Vec<u8>> {self.lock() .objects .iter() .find(|(held, _)| held == key) .map(|(_, bytes)| bytes.clone()) }/// Make the next `take_slot` answer "busy".pubfn set_slot_busy(&self, busy: bool) {self.lock().slot_busy = busy; }/// Make the password run refuse with this sentence.////// A refusal is a STATE the tools have to answer for, not an absent/// answer: a server whose object store has no pipeline composed behind it/// refuses this one method by name while every other one works, and a/// double that could only succeed could not stand in for it.pubfn refuse_run_with(&self, sentence: &str) {self.lock().run_refusal = Some(sentence.to_string()); }/// Every call this rail was asked to make, in order.pubfn calls(&self) -> Vec<(String, String)> {self.lock().calls.clone() }fn lock(&self) -> std::sync::MutexGuard<'_, ScriptedState> {self.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) }fn record(&self, what: &str, detail: String) {self.lock().calls.push((what.to_string(), detail)); }}implDocumentsRailforScriptedDocuments {fn get(&self, key: &str) -> RailResult<Option<Vec<u8>>> {self.record("get", key.to_string());Ok(self .lock() .objects .iter() .find(|(held, _)| held == key) .map(|(_, bytes)| bytes.clone())) }fn copy(&self, from_key: &str, to_key: &str) -> RailResult<()> {self.record("copy", format!("{from_key}→{to_key}"));let bytes = self .lock() .objects .iter() .find(|(held, _)| held == from_key) .map(|(_, bytes)| bytes.clone());letSome(bytes) = bytes else {returnErr(format!("no object at {from_key}")); };self.put(to_key, bytes);Ok(()) }fn delete(&self, keys: &[String]) -> RailResult<()> {self.record("delete", keys.join(", "));letmut state = self.lock(); state.objects.retain(|(held, _)| !keys.contains(held));Ok(()) }fn take_slot(&self, workspace_id: &str) -> RailResult<bool> {self.record("take_slot", workspace_id.to_string());letmut state = self.lock();if state.slot_busy {returnOk(false); } state.held.push(workspace_id.to_string());Ok(true) }fn release_slot(&self, workspace_id: &str) {self.record("release_slot", workspace_id.to_string());letmut state = self.lock();ifletSome(index) = state.held.iter().position(|held| held == workspace_id) { state.held.remove(index); } }fn run_password_candidates( &self, _workspace_id: &str, document_id: &str, candidates: &[String], ) -> RailResult<RunOutcome> {self.record("run_password_candidates", format!("{document_id}:{}", candidates.len()), );ifletSome(sentence) = self.lock().run_refusal.clone() {returnErr(sentence); }Ok(self .lock() .run_outcome .clone() .unwrap_or(RunOutcome::Locked)) }}// The IMPLEMENTATION a server with an object store fills this seam with is// `cotton_server::documents::mcp_rail::ObjectStoreDocuments` (design P3): it// drives the async store to completion on the blocking thread a tool call// already holds, and it takes the pipeline's own slot when one is composed.// It cannot be here — this crate links neither a runtime nor an object store,// which is the whole reason the seam is a trait.