Skip to main content

agentmux_srv_core/backend/transcript/
damage.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A zone of the shared transcript store that SQLite reports as corrupt
5//! (`SQLITE_CORRUPT`, "database disk image is malformed").
6//!
7//! Until now that was a WARN line per failed append: on one machine a single
8//! agent's zone logged 218,133 of them over thirteen days while nothing told the
9//! user and every line kept being sent to the damaged pages
10//! (docs/analysis/RCA_UPGRADE_0_59_30_TO_0_59_34_ISSUES_2026_10_19.md §6). Now
11//! the first corrupt error on a zone, from an append, a tail read or an index
12//! rebuild:
13//!
14//! - marks the zone damaged for the rest of the process: appends to it skip the
15//!   shared store (the block's own copy keeps being written) and readers use the
16//!   block's own copy instead;
17//! - records one incident for the user and tells the agent once.
18//!
19//! Only the shared store's zones are marked: a block's own store is a
20//! per-channel file and is not touched by this.
21
22use std::path::Path;
23use std::sync::Mutex;
24
25use crate::backend::storage::error::StoreError;
26
27/// The broker event that shows a recorded incident in every open window now; the window shows
28/// what is in `incidents.jsonl` again when it starts.
29pub const EVENT_INCIDENT_RECORDED: &str = "incident:recorded";
30
31static BROKER: std::sync::OnceLock<std::sync::Arc<crate::backend::mps::Broker>> = std::sync::OnceLock::new();
32
33/// Attach the broker (bootstrap), so an incident reaches the open windows when it is recorded.
34pub fn install_broker(broker: std::sync::Arc<crate::backend::mps::Broker>) {
35    let _ = BROKER.set(broker);
36}
37
38/// The `kind` of the incident (`agentmux_common::incidents::Incident::kind`).
39pub const INCIDENT_KIND: &str = "transcript_damaged";
40
41/// Whether `e` is SQLite saying the database file is corrupt.
42pub fn is_corrupt(e: &StoreError) -> bool {
43    matches!(e, StoreError::Sqlite(rusqlite::Error::SqliteFailure(f, _)) if f.code == rusqlite::ErrorCode::DatabaseCorrupt)
44}
45
46/// The zones found damaged, in the order they were found.
47pub struct Damaged {
48    zones: Mutex<Vec<String>>,
49}
50
51impl Damaged {
52    pub const fn new() -> Self {
53        Damaged { zones: Mutex::new(Vec::new()) }
54    }
55
56    /// Marks `zone`; true the first time, false when it was already marked.
57    pub fn mark(&self, zone: &str) -> bool {
58        let mut zones = self.zones.lock().unwrap_or_else(|e| e.into_inner());
59        if zones.iter().any(|z| z == zone) {
60            return false;
61        }
62        zones.push(zone.to_string());
63        true
64    }
65
66    pub fn contains(&self, zone: &str) -> bool {
67        self.zones.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|z| z == zone)
68    }
69
70    /// How many zones are marked: a reader compares it before and after a read to
71    /// see that the read found one.
72    pub fn count(&self) -> usize {
73        self.zones.lock().unwrap_or_else(|e| e.into_inner()).len()
74    }
75}
76
77static DAMAGED: Damaged = Damaged::new();
78
79/// Whether `zone` of the shared store was found corrupt in this process.
80pub fn is_damaged(zone: &str) -> bool {
81    DAMAGED.contains(zone)
82}
83
84/// How many zones have been found damaged in this process.
85pub fn damaged_count() -> usize {
86    DAMAGED.count()
87}
88
89/// If `e` is a corrupt-database error from `op` on `zone` of the shared store,
90/// marks the zone damaged and, the first time, records the incident and tells
91/// the agent. Returns whether `e` was one, so a caller can fall back to the
92/// block's own copy instead of treating it as a transient failure.
93pub fn note_corrupt(zone: &str, op: &str, e: &StoreError) -> bool {
94    if !is_corrupt(e) {
95        return false;
96    }
97    if DAMAGED.mark(zone) {
98        tracing::error!(
99            zone = %zone,
100            op = %op,
101            error = %e,
102            "shared transcript store: SQLITE_CORRUPT; no more writes to this zone and its readers use the block's own copy for the rest of this process"
103        );
104        announce(zone, op);
105    }
106    true
107}
108
109/// [`note_corrupt`] for a reader that has already turned the error into text
110/// (the segment log, the archive and snapshot code return `String` errors): SQLite's
111/// own wording for a corrupt file is what is looked for.
112pub fn note_corrupt_text(zone: &str, op: &str, text: &str) -> bool {
113    if !(text.contains("database disk image is malformed") || text.contains("malformed database schema")) {
114        return false;
115    }
116    if DAMAGED.mark(zone) {
117        tracing::error!(
118            zone = %zone,
119            op = %op,
120            error = %text,
121            "shared transcript store: SQLITE_CORRUPT; no more writes to this zone and its readers use the block's own copy for the rest of this process"
122        );
123        announce(zone, op);
124    }
125    true
126}
127
128/// The shared transcript store, unless `zone` of it was found corrupt in this process: a
129/// reader with a copy of its own to fall back to asks this instead of
130/// `agent_session::global_transcript_store()`.
131pub fn global_for(zone: &str) -> Option<std::sync::Arc<crate::backend::storage::filestore::FileStore>> {
132    if is_damaged(zone) {
133        return None;
134    }
135    #[cfg(any(test, feature = "test-support"))]
136    {
137        if let Some(fs) = test_support::global_override() {
138            return Some(fs);
139        }
140    }
141    crate::backend::agent_session::global_transcript_store().cloned()
142}
143
144/// The key under which an agent's memory record in the shared store is marked. The record spans several
145/// zones (its files, its bundle, its claims), none with a copy of its own to fall back to, so it is marked as a whole.
146pub fn memory_zone(uid: &str) -> String {
147    format!("agent-uid:{uid}:memory")
148}
149
150/// The key under which Global Memory's record in the shared store is marked.
151pub const GLOBAL_MEMORY_ZONE: &str = "global-memory";
152
153/// The key under which damage to the frame table is marked. It is found by a sum over the whole
154/// table (`history.usage`), not by a read of one zone, so it belongs to no agent: a zone's own
155/// read finds it only when that zone's frames are on the damaged pages.
156pub const FRAMES_ZONE: &str = "store:frames";
157
158/// What a marked zone is, which decides what the user and the agent are told.
159enum Kind<'a> {
160    /// The compressed-frame table as a whole ([`FRAMES_ZONE`]).
161    Frames,
162    /// A transcript, its summary, archive or segment log: the agent's saved history.
163    History(&'a str),
164    /// An agent's memory record.
165    Memory(&'a str),
166    GlobalMemory,
167    Other,
168}
169
170fn kind_of(zone: &str) -> Kind<'_> {
171    if zone == GLOBAL_MEMORY_ZONE {
172        return Kind::GlobalMemory;
173    }
174    if zone == FRAMES_ZONE {
175        return Kind::Frames;
176    }
177    if let Some(id) = zone.strip_prefix("agent-uid:").and_then(|z| z.strip_suffix(":memory")) {
178        return Kind::Memory(id);
179    }
180    agent_of(zone).map_or(Kind::Other, Kind::History)
181}
182
183/// [`note_corrupt`] when `fs` is the shared store itself, which a reader of
184/// either store (the index code takes a store and a zone) cannot tell otherwise;
185/// false, and nothing marked, for any other store.
186pub fn note_if_shared(fs: &crate::backend::storage::filestore::FileStore, zone: &str, op: &str, e: &StoreError) -> bool {
187    is_shared(fs) && note_corrupt(zone, op, e)
188}
189
190fn is_shared(fs: &crate::backend::storage::filestore::FileStore) -> bool {
191    #[cfg(any(test, feature = "test-support"))]
192    {
193        if test_support::registered(fs) {
194            return true;
195        }
196    }
197    crate::backend::agent_session::global_transcript_store().is_some_and(|g| std::ptr::eq(g.as_ref(), fs))
198}
199
200/// The agent's id in an `agent:<id>:current` (or `:archive:`) zone.
201///
202/// A transcript zone is keyed by the agent's id (`agentId` in the block's meta, the
203/// agent's own `definition_id`) and a segment log by its `AGENTMUX_AGENT_UID`
204/// (`db_agents.id`, see `Controller::stable_agent_uid`). The code names both as the
205/// agent's own id; if they ever differ for an agent, it gets a notice for each.
206fn agent_of(zone: &str) -> Option<&str> {
207    zone.strip_prefix("agent:")
208        .or_else(|| zone.strip_prefix("agent-uid:"))?
209        .split(':')
210        .next()
211        .filter(|id| !id.is_empty())
212}
213
214fn short(id: &str) -> &str {
215    id.char_indices().nth(8).map_or(id, |(i, _)| &id[..i])
216}
217
218/// The incident for a damaged zone, as the user is told about it.
219pub fn incident_for(zone: &str, op: &str) -> agentmux_common::incidents::Incident {
220    const REPAIR: &str = "AgentMux rebuilds the shared database from the pages it can still read the next time it starts with no other AgentMux running, so quit every AgentMux window and start it again. The damaged file is kept beside the new one (filestore.db.damaged-…), never deleted; do not delete or move anything in shared/agents/transcripts.";
221    let (what, did, lost): (String, Vec<String>, Vec<String>) = match kind_of(zone) {
222        Kind::History(id) => (
223            format!("Saved history for agent {} is damaged", short(id)),
224            vec![
225                "AgentMux stopped writing this history to the shared database and keeps saving it in this version's own copy, so nothing new is lost.".to_string(),
226                "Its history views read that copy instead.".to_string(),
227                REPAIR.to_string(),
228            ],
229            vec!["Lines the shared database failed to take, and what was on its damaged pages.".to_string()],
230        ),
231        Kind::Memory(id) => (
232            format!("The saved memory record for agent {} is damaged", short(id)),
233            vec![
234                "AgentMux stopped using the shared memory record for this agent for now. Its memory files in its own folder are not changed and are used as they are.".to_string(),
235                REPAIR.to_string(),
236            ],
237            vec!["Changes to its memory files since the damage began are not in the shared record, and what was on its damaged pages.".to_string()],
238        ),
239        Kind::GlobalMemory => (
240            "The saved history of Global Memory is damaged".to_string(),
241            vec![
242                "AgentMux stopped using the shared Global Memory record for now. Global Memory itself, in this version's own store, is not changed.".to_string(),
243                REPAIR.to_string(),
244            ],
245            vec!["Changes to Global Memory since the damage began are not in the shared record, and what was on its damaged pages.".to_string()],
246        ),
247        Kind::Frames => (
248            "The shared history database has damaged pages".to_string(),
249            vec![
250                "AgentMux has not changed the database: every agent whose history is not on the damaged pages carries on as before.".to_string(),
251                "The Storage numbers in History cannot be summed until it is repaired.".to_string(),
252                REPAIR.to_string(),
253            ],
254            vec!["The history stored on the damaged pages (compressed frames of some agents' earlier conversation). A version's own copy of it, where there is one, is what a repair restores it from.".to_string()],
255        ),
256        Kind::Other => (
257            format!("Saved data in the shared database ({zone}) is damaged"),
258            vec!["AgentMux stopped using that part of the shared database for now.".to_string(), REPAIR.to_string()],
259            vec!["What was on its damaged pages.".to_string()],
260        ),
261    };
262    let mut i = agentmux_common::incidents::Incident::new(INCIDENT_KIND, what, "srv");
263    i.cause = Some(format!("The shared transcript database reported corruption ({op})."));
264    i.did = did;
265    i.lost = lost;
266    // The full agent id, which `what` shortens: a restart finds the same damage by it.
267    i.evidence = i.evidence.map(|e| format!("{e}, {}", zone_tag(zone)));
268    i
269}
270
271/// What a restart finds the same damage by: the agent, as one notice covers all of its zones
272/// (its transcript, segment log and archives), else the zone.
273fn zone_tag(zone: &str) -> String {
274    match kind_of(zone) {
275        Kind::History(id) => format!("agent {id}"),
276        Kind::Memory(id) => format!("memory {id}"),
277        Kind::GlobalMemory => "global memory".to_string(),
278        Kind::Frames => "frame table".to_string(),
279        Kind::Other => format!("zone {zone}"),
280    }
281}
282
283static TOLD: Mutex<Vec<String>> = Mutex::new(Vec::new());
284
285/// True the first time `tag` is asked: the agent is told once for all of its zones.
286fn first_to_tell(tag: &str) -> bool {
287    let mut told = TOLD.lock().unwrap_or_else(|e| e.into_inner());
288    if told.iter().any(|t| t == tag) {
289        return false;
290    }
291    told.push(tag.to_string());
292    true
293}
294
295/// What the agent is told, once.
296pub fn agent_note() -> String {
297    "[AgentMux] The saved copy of your conversation history in the shared transcript database is damaged (the database reported corruption). \
298     AgentMux has stopped writing it there and keeps saving it in its own copy, so nothing new is lost; your own session context is not affected. \
299     You need not do anything. AgentMux rebuilds the shared database the next time it starts with no other AgentMux running: if the user asks, tell them to quit every AgentMux window and start it again, and not to delete the shared transcripts folder."
300        .to_string()
301}
302
303/// Writes the incident to `incidents.jsonl` in `dir` unless an unacknowledged one
304/// for the same agent is already there (a restart finds the same damage again).
305pub fn write_incident(dir: &Path, zone: &str, op: &str) -> Option<agentmux_common::incidents::Incident> {
306    let path = dir.join(agentmux_common::incidents::FILE_NAME);
307    let incident = incident_for(zone, op);
308    let seen = agentmux_common::incidents::read(&path, 200)
309        .iter()
310        .any(|i| i.kind == INCIDENT_KIND && i.acknowledged_at_ms.is_none() && i.evidence.as_deref().is_some_and(|e| e.ends_with(&zone_tag(zone))));
311    if seen {
312        return None;
313    }
314    if let Err(e) = agentmux_common::incidents::append(&path, &incident) {
315        tracing::warn!(error = %e, zone = %zone, "shared transcript store: couldn't record the damage as an incident");
316        return None;
317    }
318    Some(incident)
319}
320
321/// Shows `incident` in every open window now. One not published here (already open from an
322/// earlier start, or no window yet) is shown from the file when a window starts.
323fn publish(incident: &agentmux_common::incidents::Incident) {
324    if let Some(broker) = BROKER.get() {
325        publish_to(broker, incident);
326    }
327}
328
329fn publish_to(broker: &crate::backend::mps::Broker, incident: &agentmux_common::incidents::Incident) {
330    broker.publish_event::<crate::backend::mps_events::IncidentRecorded>(&incident.into(), vec![], 0);
331}
332
333/// Ask for the shared store to be rebuilt at the next start that finds no other srv running
334/// (`filestore::repair`). Not from a unit test: it would write beside the real store.
335fn request_repair(zone: &str, op: &str) {
336    #[cfg(not(any(test, feature = "test-support")))]
337    if let Some(dir) = crate::registry::resolve_shared_transcripts_dir() {
338        let zone = (zone != FRAMES_ZONE).then_some(zone);
339        if let Err(e) = crate::backend::storage::filestore::repair::request(&dir.join("filestore.db"), op, zone, agentmux_common::time::now_ms_u64()) {
340            tracing::warn!(error = %e, "shared transcript store: couldn't ask for a repair");
341        }
342    }
343    #[cfg(any(test, feature = "test-support"))]
344    let _ = (zone, op);
345}
346
347fn announce(zone: &str, op: &str) {
348    request_repair(zone, op);
349    match std::env::var_os("AGENTMUX_DATA_DIR").filter(|d| !d.is_empty()) {
350        Some(dir) => {
351            if let Some(incident) = write_incident(Path::new(&dir), zone, op) {
352                publish(&incident);
353            }
354        }
355        None => tracing::warn!(zone = %zone, "shared transcript store: no data folder to record the damage in"),
356    }
357    // Only the agent's saved history is news to the agent; a memory record is not.
358    let Kind::History(id) = kind_of(zone) else { return };
359    let id = id.to_string();
360    if !first_to_tell(&zone_tag(zone)) {
361        return;
362    }
363    let text = agent_note();
364    let tell = move || {
365        let handler = crate::backend::reactive::get_global_handler();
366        // It asks nothing of the agent, so it waits for its next turn.
367        if let Err(e) = handler.hold_system_note(&id, "transcript-damage", &text) {
368            // Not running, or not registered yet: the incident has told the user.
369            tracing::info!(agent = %id, error = %e, "shared transcript store: the agent wasn't told about the damage");
370        }
371    };
372    // The caller may hold a lock of the transcript path: tell from a thread of its own.
373    if let Err(e) = std::thread::Builder::new().name("transcript-damage-note".into()).spawn(tell) {
374        tracing::warn!(error = %e, "shared transcript store: couldn't start the note to the agent");
375    }
376}
377
378#[cfg(any(test, feature = "test-support"))]
379pub mod test_support {
380    use crate::backend::storage::filestore::FileStore;
381    use std::sync::Mutex;
382
383    /// Makes every access to the store fail with SQLite's own `SQLITE_CORRUPT`, as
384    /// in a process that starts on a damaged file: the schema's root pages are
385    /// pointed past the end of the file, which is what a damaged page looks like
386    /// to a query that walks it.
387    pub fn corrupt(fs: &FileStore) {
388        fs.drop_cache_for_test();
389        break_tables(fs);
390    }
391
392    /// [`corrupt`] for a process that already holds the zone's file in its cache
393    /// (`stat` answers from it): the damage shows on the first read of the database.
394    pub fn corrupt_behind_the_cache(fs: &FileStore) {
395        break_tables(fs);
396    }
397
398    fn break_tables(fs: &FileStore) {
399        let conn = fs.conn().lock().unwrap();
400        let version: i64 = conn.query_row("PRAGMA schema_version", [], |r| r.get(0)).unwrap();
401        // A new schema version makes the connection read the schema again, with the
402        // changed root pages; without it the parsed one stays in use.
403        conn.execute_batch(&format!(
404            "PRAGMA writable_schema=ON;
405             UPDATE sqlite_master SET rootpage=99999 WHERE type='table' AND name IN ('db_wave_file','db_file_data');
406             PRAGMA schema_version={};
407             PRAGMA writable_schema=OFF;",
408            version + 1
409        ))
410        .unwrap();
411    }
412
413    thread_local! {
414        static GLOBAL: std::cell::RefCell<Option<std::sync::Arc<FileStore>>> = const { std::cell::RefCell::new(None) };
415    }
416
417    pub(crate) fn global_override() -> Option<std::sync::Arc<FileStore>> {
418        GLOBAL.with(|g| g.borrow().clone())
419    }
420
421    /// Makes `fs` the shared store for [`super::global_for`] on this thread while the guard lives,
422    /// and recognised as the shared one by [`super::note_if_shared`].
423    pub(crate) struct UseGlobal(Shared);
424
425    pub(crate) fn use_global(fs: &std::sync::Arc<FileStore>) -> UseGlobal {
426        GLOBAL.with(|g| *g.borrow_mut() = Some(fs.clone()));
427        UseGlobal(register(fs))
428    }
429
430    impl Drop for UseGlobal {
431        fn drop(&mut self) {
432            GLOBAL.with(|g| *g.borrow_mut() = None);
433        }
434    }
435
436    /// SQLite's `SQLITE_CORRUPT`, as a store error.
437    pub(crate) fn corrupt_error() -> crate::backend::storage::error::StoreError {
438        crate::backend::storage::error::StoreError::Sqlite(rusqlite::Error::SqliteFailure(
439            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CORRUPT),
440            Some("database disk image is malformed".into()),
441        ))
442    }
443
444    static SHARED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
445
446    /// Stands in for the process-global shared store while it lives: stores the
447    /// index code is given are recognised as the shared one by address.
448    pub struct Shared(usize);
449
450    pub fn register(fs: &FileStore) -> Shared {
451        let addr = fs as *const FileStore as usize;
452        SHARED.lock().unwrap().push(addr);
453        Shared(addr)
454    }
455
456    pub(crate) fn registered(fs: &FileStore) -> bool {
457        SHARED.lock().unwrap().contains(&(fs as *const FileStore as usize))
458    }
459
460    impl Drop for Shared {
461        fn drop(&mut self) {
462            SHARED.lock().unwrap().retain(|a| *a != self.0);
463        }
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::backend::storage::filestore::FileStore;
471
472    fn corrupt_error() -> StoreError {
473        StoreError::Sqlite(rusqlite::Error::SqliteFailure(
474            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CORRUPT),
475            Some("database disk image is malformed".into()),
476        ))
477    }
478
479    #[test]
480    fn only_a_corrupt_database_is_corrupt() {
481        assert!(is_corrupt(&corrupt_error()));
482        assert!(!is_corrupt(&StoreError::NotFound));
483        assert!(!is_corrupt(&StoreError::Other("database disk image is malformed".into())));
484        let busy = StoreError::Sqlite(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_BUSY), None));
485        assert!(!is_corrupt(&busy));
486    }
487
488    #[test]
489    fn a_zone_is_marked_once() {
490        let d = Damaged::new();
491        assert!(!d.contains("agent:a:current"));
492        assert!(d.mark("agent:a:current"));
493        assert!(!d.mark("agent:a:current"));
494        assert!(d.contains("agent:a:current") && !d.contains("agent:b:current"));
495        assert_eq!(d.count(), 1);
496        assert!(d.mark("agent:b:current"));
497        assert_eq!(d.count(), 2);
498    }
499
500    #[test]
501    fn a_corrupt_error_marks_the_zone_and_other_errors_do_not() {
502        let zone = "agent:note-corrupt-1:current";
503        assert!(!note_corrupt(zone, "append", &StoreError::NotFound));
504        assert!(!is_damaged(zone));
505        assert!(note_corrupt(zone, "append", &corrupt_error()));
506        assert!(is_damaged(zone));
507        let n = damaged_count();
508        assert!(note_corrupt(zone, "tail read", &corrupt_error()), "still reported as corrupt");
509        assert_eq!(damaged_count(), n, "a zone already marked is not marked again");
510    }
511
512    #[test]
513    fn the_incident_names_the_agent_and_what_was_done() {
514        let i = incident_for("agent:4775c42b-aaaa-bbbb:current", "append");
515        assert_eq!(i.kind, INCIDENT_KIND);
516        assert_eq!(i.what, "Saved history for agent 4775c42b is damaged");
517        assert!(i.cause.as_deref().unwrap().contains("append"));
518        let did = i.did.join(" ");
519        assert!(did.contains("stopped writing") && did.contains("own copy") && did.contains("quit every AgentMux window"), "{did}");
520        assert!(!i.lost.is_empty());
521    }
522
523    #[test]
524    fn the_incident_is_written_once_until_it_is_acknowledged() {
525        let dir = tempfile::tempdir().unwrap();
526        let zone = "agent:incident-once-1:current";
527        write_incident(dir.path(), zone, "append");
528        write_incident(dir.path(), zone, "tail read");
529        let path = dir.path().join(agentmux_common::incidents::FILE_NAME);
530        let all = agentmux_common::incidents::read(&path, 50);
531        assert_eq!(all.len(), 1, "a second start finds the same damage: no second notice");
532        write_incident(dir.path(), "agent:incident-once-2:current", "append");
533        assert_eq!(agentmux_common::incidents::read(&path, 50).len(), 2, "another agent's damage is its own incident");
534        agentmux_common::incidents::append_ack(&path, &all[0].id, 1).unwrap();
535        write_incident(dir.path(), zone, "append");
536        assert_eq!(agentmux_common::incidents::read(&path, 50).len(), 3, "after the user closed it, new damage is told again");
537    }
538
539    #[test]
540    fn the_agent_note_is_a_system_note_that_says_what_to_do() {
541        let t = agent_note();
542        assert!(t.starts_with("[AgentMux] "));
543        assert!(t.contains("own copy") && t.contains("quit every AgentMux window") && t.contains("not to delete"));
544    }
545
546    #[test]
547    fn sqlite_reports_the_injected_damage_as_corrupt() {
548        // The helpers the path tests rely on: a real SQLITE_CORRUPT from a real query.
549        let fs = FileStore::open_in_memory().unwrap();
550        fs.make_file("z", "output", Default::default(), Default::default()).unwrap();
551        fs.append_lines("z", "output", b"{\"a\":1}
552").unwrap();
553        test_support::corrupt_behind_the_cache(&fs);
554        assert!(fs.stat("z", "output").unwrap().is_some(), "answered from the cache");
555        let e = fs.read_bytes_db("z", "output", 0, 8).unwrap_err();
556        assert!(is_corrupt(&e), "{e:?}");
557
558        let fs = FileStore::open_in_memory().unwrap();
559        fs.make_file("z", "output", Default::default(), Default::default()).unwrap();
560        test_support::corrupt(&fs);
561        let e = fs.stat("z", "output").unwrap_err();
562        assert!(is_corrupt(&e), "{e:?}");
563    }
564
565    #[test]
566    fn only_the_shared_store_marks_a_zone_from_a_reader_that_takes_any_store() {
567        let own = FileStore::open_in_memory().unwrap();
568        let shared = FileStore::open_in_memory().unwrap();
569        let _guard = test_support::register(&shared);
570        assert!(!note_if_shared(&own, "agent:shared-only-1:current", "index read", &corrupt_error()));
571        assert!(!is_damaged("agent:shared-only-1:current"), "a block's own store is not the shared one");
572        assert!(note_if_shared(&shared, "agent:shared-only-1:current", "index read", &corrupt_error()));
573        assert!(is_damaged("agent:shared-only-1:current"));
574    }
575
576    #[test]
577    fn an_index_rebuild_that_hits_a_corrupt_part_marks_the_zone() {
578        use crate::backend::storage::filestore::{FileMeta, FileOpts};
579        let zone = "agent:index-corrupt-1:current";
580        let gfs = FileStore::open_in_memory().unwrap();
581        gfs.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
582        gfs.append_lines(zone, "output", b"{\"a\":1}
583{\"b\":2}
584").unwrap();
585        let _guard = test_support::register(&gfs);
586        test_support::corrupt(&gfs);
587        assert_eq!(crate::backend::blockcontroller::shell::extend_output_idx(&gfs, zone), None);
588        assert!(is_damaged(zone), "the rebuild's read error is the corruption");
589    }
590
591    #[test]
592    fn a_rebuild_on_a_store_that_is_not_the_shared_one_marks_nothing() {
593        use crate::backend::storage::filestore::{FileMeta, FileOpts};
594        let zone = "agent:index-corrupt-own-1:current";
595        let own = FileStore::open_in_memory().unwrap();
596        own.make_file(zone, "output", FileMeta::default(), FileOpts::default()).unwrap();
597        own.append_lines(zone, "output", b"{\"a\":1}
598").unwrap();
599        test_support::corrupt(&own);
600        assert_eq!(crate::backend::blockcontroller::shell::extend_output_idx(&own, zone), None);
601        assert!(!is_damaged(zone));
602    }
603
604    #[test]
605    fn a_recorded_incident_goes_to_the_open_windows_as_a_typed_event() {
606        use crate::backend::mps::{Broker, MuxEvent};
607        let broker = Broker::new();
608        let seen = std::sync::Arc::new(Mutex::new(Vec::<MuxEvent>::new()));
609        let s2 = seen.clone();
610        broker.add_observer(std::sync::Arc::new(move |e: &MuxEvent| s2.lock().unwrap().push(e.clone())));
611        let incident = incident_for("agent:live-toast-1:current", "append");
612        publish_to(&broker, &incident);
613        let seen = seen.lock().unwrap();
614        assert_eq!(seen.len(), 1);
615        assert_eq!(seen[0].event, EVENT_INCIDENT_RECORDED);
616        assert!(seen[0].scopes.is_empty(), "to every window, not one pane's");
617        let data = seen[0].data.clone().unwrap();
618        assert_eq!(data["id"], incident.id);
619        assert_eq!(data["kind"], INCIDENT_KIND);
620        assert_eq!(data["what"], incident.what);
621        assert_eq!(data["did"].as_array().unwrap().len(), incident.did.len());
622        assert!(data.get("acknowledged_at_ms").is_none(), "{data}");
623    }
624
625    #[test]
626    fn a_memory_record_and_global_memory_are_told_in_their_own_words() {
627        let h = incident_for("agent:kinds-1:current", "append");
628        let m = incident_for(&memory_zone("kinds-1"), "bundle record");
629        let g = incident_for(GLOBAL_MEMORY_ZONE, "global memory import");
630        assert_eq!(h.what, "Saved history for agent kinds-1 is damaged");
631        assert_eq!(m.what, "The saved memory record for agent kinds-1 is damaged");
632        assert_eq!(g.what, "The saved history of Global Memory is damaged");
633        for i in [&m, &g] {
634            let did = i.did.join(" ");
635            assert!(did.contains("stopped using") && did.contains("quit every AgentMux window"), "{did}");
636            assert!(!did.contains("own copy"), "a memory record has no copy of its own to read: {did}");
637        }
638        // Three notices for one agent that is hurt three ways: none hides another.
639        let tags = [zone_tag("agent:kinds-1:current"), zone_tag(&memory_zone("kinds-1")), zone_tag(GLOBAL_MEMORY_ZONE)];
640        assert_eq!(tags.iter().collect::<std::collections::HashSet<_>>().len(), 3, "{tags:?}");
641    }
642
643    #[test]
644    fn an_agent_is_told_once_for_all_of_its_zones() {
645        assert!(first_to_tell(&zone_tag("agent:told-once-1:current")));
646        assert!(!first_to_tell(&zone_tag("agent:told-once-1:archive:17")), "its archive zone: same agent");
647        assert!(!first_to_tell(&zone_tag("agent-uid:told-once-1:segments")), "its segment log: same agent id");
648        assert!(first_to_tell(&zone_tag("agent:told-once-2:current")), "another agent is told");
649    }
650
651    #[test]
652    fn only_an_incident_that_was_written_is_published() {
653        let dir = tempfile::tempdir().unwrap();
654        let zone = "agent:live-toast-2:current";
655        assert!(write_incident(dir.path(), zone, "append").is_some());
656        assert!(write_incident(dir.path(), zone, "tail read").is_none(), "already open: shown from the file, not again");
657    }
658}