Skip to main content

agentmux_srv_core/backend/agent_session/
archive.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Archive lifecycle, browsing, and previews for agent session zones.
5
6use crate::backend::storage::filestore::FileStore;
7
8use super::global_store::global_transcript_store;
9use super::helpers::{now_ms, write_zone_file};
10use super::session_io::{OUTPUT_FILE, OWNER_FILE, SNAPSHOT_FILE, TSIDX_FILE};
11use super::zone_naming::{agent_archive_zone, agent_current_zone, is_valid_definition_id, validate_and_current};
12
13/// Archive `agent:<defId>:current` to `agent:<defId>:archive:<now_ms>`.
14///
15/// Atomicity contract:
16/// - We write the archive zone first, then clear the current zone.
17/// - A crash between those two steps leaves both zones populated;
18///   replay-time behaviour is "current wins" so this is safe.
19/// - We never clear `:current` before the archive write has been
20///   acked by FileStore, so the archive-missing case can't happen
21///   without a FileStore I/O failure on the write itself (which is
22///   surfaced as `Err` and aborts the clear step).
23///
24/// Returns:
25/// - `Ok(Some((archive_zoneid, archived_at_ms)))` on successful
26///   archive (current zone had content).
27/// - `Ok(None)` when there was nothing to archive (no
28///   `output.state.json` in :current, OR it was zero-byte). The
29///   caller should treat this as "session was empty, nothing to do"
30///   — we explicitly do NOT create an empty archive zone.
31pub fn archive_session(
32    filestore: &FileStore,
33    definition_id: &str,
34) -> Result<Option<(String, i64)>, String> {
35    archive_session_in(filestore, global_transcript_store().map(|g| g.as_ref()), definition_id)
36}
37
38/// [`archive_session`] with the global transcript store passed in (`None`
39/// when there is none). The archive is written to the global store whenever
40/// there is one: the agent's record (`history/record.rs`, behind
41/// SearchHistory and the Agent History view) and the history summary read
42/// archives only there, so an archive written to the per-channel store drops
43/// out of the agent's history.
44pub(crate) fn archive_session_in(
45    filestore: &FileStore,
46    global: Option<&FileStore>,
47    definition_id: &str,
48) -> Result<Option<(String, i64)>, String> {
49    use crate::backend::transcript::damage;
50    let zone = validate_and_current(definition_id)?;
51    // A zone found corrupt is archived from this channel's copy, the path of an install with no
52    // shared store. A failure that is the corruption is not retried here: the move may have
53    // cleared this channel's current already, so the next call is the one that takes the other path.
54    let global = global.filter(|_| !damage::is_damaged(&zone));
55    let archived = archive_session_with(filestore, global, definition_id)?;
56    if archived.is_some() {
57        // The History pane's agent list gains an archived conversation.
58        crate::backend::history_changed::mark();
59    }
60    Ok(archived)
61}
62
63fn archive_session_with(
64    filestore: &FileStore,
65    global: Option<&FileStore>,
66    definition_id: &str,
67) -> Result<Option<(String, i64)>, String> {
68    let current_zone = validate_and_current(definition_id)?;
69
70    // Prefer the GLOBAL current zone as the archive source. It is the complete
71    // cross-channel accumulation — and (via the hot-path mirror) the place the
72    // `output` NDJSON is fully gathered — so the per-channel `:current` is at
73    // most a subset (often just this channel's snapshot). Archiving from the
74    // global store therefore preserves the full history in *every* case:
75    //   - cross-channel viewer (empty local), AND
76    //   - cross-channel session that also ran locally (non-empty local) —
77    // both previously risked discarding global-only history.
78    // We then clear BOTH currents so the read fallback can't resurrect the
79    // just-archived conversation. Falls through to the per-channel path below
80    // only when there's no global store or it holds nothing for this agent
81    // (pure pre-global / same-channel-only data). (codex + reagent P1/P2 #1399.)
82    if let Some(gfs) = global {
83        // This channel's current is at most a subset of the global one, so it
84        // is cleared first: a crash before the move leaves the conversation
85        // current and readable from the global store, never a stale local copy
86        // with no global current to win over it.
87        // Only what the shared store answered is looked at for corruption: an error of this
88        // channel's own store, further down, says nothing about the shared zone.
89        let archived = archive_global_current(gfs, definition_id, || clear_local_current_zone(filestore, &current_zone)).inspect_err(|e| {
90            crate::backend::transcript::damage::note_corrupt_text(&current_zone, "archive", e);
91        })?;
92        match archived {
93            GlobalArchive::Archived(zone, ts) => {
94                clear_global_current_zone_in(gfs, definition_id);
95                return Ok(Some((zone, ts)));
96            }
97            // Another instance archived and cleared it first.
98            GlobalArchive::ArchivedElsewhere => return Ok(None),
99            GlobalArchive::Nothing => {}
100        }
101    }
102
103    // Determine whether there's anything worth archiving.
104    let state_stat = filestore
105        .stat(&current_zone, SNAPSHOT_FILE)
106        .map_err(|e| format!("stat current: {e}"))?;
107    let has_state = match &state_stat {
108        Some(f) => f.size > 0,
109        None => false,
110    };
111    let output_stat = filestore
112        .stat(&current_zone, OUTPUT_FILE)
113        .map_err(|e| format!("stat current output: {e}"))?;
114    let has_output = match &output_stat {
115        Some(f) => f.size > 0,
116        None => false,
117    };
118    if !has_state && !has_output {
119        return Ok(None);
120    }
121
122    // Per-channel content is archived into the global store too, when there is
123    // one. It is written to a staging zone of this call's own and then moved
124    // under a free archive name in one transaction, so two instances archiving
125    // at once can't write into the same archive.
126    let target = global.unwrap_or(filestore);
127    let staging = format!("agent:{definition_id}:archiving:{}", uuid::Uuid::new_v4());
128
129    // Copy snapshot first (the canonical "history" file).
130    if has_state {
131        let snapshot_bytes = filestore
132            .read_file(&current_zone, SNAPSHOT_FILE)
133            .map_err(|e| format!("read current snapshot: {e}"))?
134            .unwrap_or_default();
135        write_zone_file(target, &staging, SNAPSHOT_FILE, &snapshot_bytes)?;
136    }
137    // Copy NDJSON output if present.
138    if has_output {
139        let output_bytes = filestore
140            .read_file(&current_zone, OUTPUT_FILE)
141            .map_err(|e| format!("read current output: {e}"))?
142            .unwrap_or_default();
143        if !output_bytes.is_empty() {
144            write_zone_file(target, &staging, OUTPUT_FILE, &output_bytes)?;
145        }
146        // The tsidx sidecar travels with output (codex P2 on PR #2508):
147        // without it, archived history loses its receive-time stamps and —
148        // worse — a stale sidecar left in :current would mis-time the NEXT
149        // session (fresh output restarts at offset 0 under old entries).
150        // Best-effort: the sidecar is auxiliary and must never abort an
151        // archive.
152        copy_tsidx_best_effort(filestore, &current_zone, target, &staging);
153    }
154    let (archive_zone, ts) = claim_archive_zone(target, &staging, definition_id)?;
155
156    // Archive write succeeded. Now safe to clear the current zone: the files
157    // that were archived, and both sidecars with `output` — a stale tsidx
158    // under a fresh (offset-0) output would mis-time the next session's lines
159    // (codex P2 on PR #2508), and a stale output.idx could pass
160    // blockfile:read_range's covered_size check by coincidence (reagent P1 on
161    // #2701). One transaction (5a-2b): a crash can't leave a sidecar
162    // describing an `output` that is gone.
163    let mut clear: Vec<&str> = Vec::with_capacity(4);
164    if state_stat.is_some() {
165        clear.push(SNAPSHOT_FILE);
166    }
167    if output_stat.is_some() {
168        clear.push(OUTPUT_FILE);
169    }
170    clear.extend([TSIDX_FILE, "output.idx"]);
171    if let Err(e) = filestore.delete_files(&current_zone, &clear) {
172        tracing::warn!(
173            definition_id = %definition_id,
174            error = %e,
175            "agent_session: failed to clear current zone after archive (archive already persisted)"
176        );
177    }
178
179    // Clear the GLOBAL current zone in the same lifecycle. Without this, the
180    // cross-channel read fallback (`read_session_state` / `blockfile:read_range`
181    // / `blockfile:line_count`) would treat the intentionally-cleared local
182    // `:current` as a cross-channel miss and resurrect the just-archived
183    // conversation on the next open — so a "new session" for this definition
184    // would inherit stale history. Best-effort, same as the per-channel clear.
185    // (codex P1 on PR #1399.)
186    if let Some(gfs) = global {
187        clear_global_current_zone_in(gfs, definition_id);
188    }
189
190    tracing::info!(
191        definition_id = %definition_id,
192        archive_zoneid = %archive_zone,
193        archived_at_ms = ts,
194        "agent_session: archived current session"
195    );
196
197    Ok(Some((archive_zone, ts as i64)))
198}
199
200/// Archive the agent's GLOBAL `agent:<defId>:current` into a global
201/// `agent:<defId>:archive:<ms>` zone, where the agent's record reads it.
202///
203/// The files are moved (renamed) inside the database, in one transaction: a
204/// conversation of any size never passes through memory, and only one
205/// archive can take it. The output's timestamps and the running summary go
206/// with it. `before_move` runs once there is something to archive.
207fn archive_global_current(gfs: &FileStore, definition_id: &str, before_move: impl FnOnce()) -> Result<GlobalArchive, String> {
208    let current_zone = validate_and_current(definition_id)?;
209    let seen = |op: &str, e: crate::backend::storage::error::StoreError| {
210        crate::backend::transcript::damage::note_if_shared(gfs, &current_zone, "archive", &e);
211        format!("{op}: {e}")
212    };
213    let has = |name: &str| -> Result<bool, String> {
214        Ok(gfs.stat(&current_zone, name).map_err(|e| seen("stat", e))?.is_some_and(|f| f.size > 0))
215    };
216    // A snapshot written through the cache may not be in the database yet.
217    gfs.flush_cache().map_err(|e| seen("flush before archive", e))?;
218    if !has(SNAPSHOT_FILE)? && !has(OUTPUT_FILE)? {
219        return Ok(GlobalArchive::Nothing);
220    }
221    // What a kill left in the live file belongs to this conversation, not the next one.
222    let settled = crate::backend::transcript::live::settle(gfs, &current_zone);
223    before_move();
224
225    let mut files = vec![SNAPSHOT_FILE, OUTPUT_FILE, TSIDX_FILE, crate::backend::continuity_state::STATE_FILE];
226    if !settled {
227        // The leftover could not be put in the conversation: it goes to the archive with it, not to the next one.
228        files.push(crate::backend::transcript::live::LIVE_FILE);
229    }
230    // The store is shared by every instance on the machine. The files are
231    // moved, not copied, so only one archive can take them; another instance
232    // can still take the free name between the check and the move.
233    for _ in 0..8 {
234        let (archive_zone, ts) = free_archive_zone(gfs, definition_id)?;
235        match gfs
236            .move_files_to_zone(&current_zone, &archive_zone, &files)
237            .map_err(|e| format!("move to archive: {e}"))?
238        {
239            // The name was taken in between: try the next one.
240            None => continue,
241            // Nothing left to move: another instance archived it first.
242            Some(0) => return Ok(GlobalArchive::ArchivedElsewhere),
243            Some(_) => {
244                tracing::info!(
245                    definition_id = %definition_id,
246                    archive_zoneid = %archive_zone,
247                    archived_at_ms = ts,
248                    "agent_session: archived the global session"
249                );
250                return Ok(GlobalArchive::Archived(archive_zone, ts as i64));
251            }
252        }
253    }
254    Err(format!("no free archive zone for {definition_id}"))
255}
256
257/// What [`archive_global_current`] did.
258enum GlobalArchive {
259    Archived(String, i64),
260    /// The global current held nothing to archive.
261    Nothing,
262    /// Another instance archived and cleared the global current first.
263    ArchivedElsewhere,
264}
265
266/// Move what [`archive_session_in`] staged in `staging` under a free archive
267/// name. The move fails, and the next name is tried, when another instance
268/// took the name first.
269fn claim_archive_zone(store: &FileStore, staging: &str, definition_id: &str) -> Result<(String, u64), String> {
270    // The staged files were written through the cache; the move reads the database.
271    store.flush_cache().map_err(|e| format!("flush before archive: {e}"))?;
272    for _ in 0..8 {
273        let (zone, ts) = free_archive_zone(store, definition_id)?;
274        let moved = store
275            .move_files_to_zone(staging, &zone, &[SNAPSHOT_FILE, OUTPUT_FILE, TSIDX_FILE, OWNER_FILE])
276            .map_err(|e| format!("move to archive: {e}"))?;
277        if moved.is_some() {
278            return Ok((zone, ts));
279        }
280    }
281    Err(format!("no free archive zone for {definition_id}; the conversation stays in {staging}"))
282}
283
284/// Puts `output` (whole NDJSON lines) in a new archive zone of the agent, which the agent's record lists
285/// as a conversation of its own. Staged in a zone of this call's own and moved under a free archive
286/// name, as an archive is.
287pub(crate) fn archive_lines(store: &FileStore, definition_id: &str, output: &[u8], tsidx: &[u8], owner: Option<&str>) -> Result<String, String> {
288    let staging = format!("agent:{definition_id}:archiving:{}", uuid::Uuid::new_v4());
289    write_zone_file(store, &staging, OUTPUT_FILE, output)?;
290    if !tsidx.is_empty() {
291        write_zone_file(store, &staging, TSIDX_FILE, tsidx)?;
292    }
293    if let Some(session) = owner {
294        write_zone_file(store, &staging, OWNER_FILE, session.as_bytes())?;
295    }
296    let (zone, _) = claim_archive_zone(store, &staging, definition_id)?;
297    crate::backend::history_changed::mark();
298    Ok(zone)
299}
300
301/// An archive zone for now that holds nothing yet in `store`. Two archives in
302/// the same millisecond would otherwise share a name, and the second would
303/// overwrite the first.
304fn free_archive_zone(store: &FileStore, definition_id: &str) -> Result<(String, u64), String> {
305    let mut ts = now_ms();
306    for _ in 0..1000 {
307        let zone = agent_archive_zone(definition_id, ts);
308        if store.zone_ids_with_prefix(&zone).map_err(|e| format!("zone_ids_with_prefix: {e}"))?.iter().all(|z| *z != zone) {
309            return Ok((zone, ts));
310        }
311        ts += 1;
312    }
313    Err(format!("no free archive zone for {definition_id}"))
314}
315
316/// Copy the `output.tsidx` sidecar from `src` zone to `dst` zone,
317/// best-effort: absence is normal (pre-sidecar history), and no failure
318/// here may abort the surrounding archive — the sidecar is auxiliary
319/// timing data, not conversation content.
320fn copy_tsidx_best_effort(src_store: &FileStore, src_zone: &str, dst_store: &FileStore, dst_zone: &str) {
321    let bytes = match src_store.stat(src_zone, TSIDX_FILE) {
322        Ok(Some(f)) if f.size > 0 => match src_store.read_file(src_zone, TSIDX_FILE) {
323            Ok(Some(b)) if !b.is_empty() => b,
324            _ => return,
325        },
326        _ => return,
327    };
328    if let Err(e) = write_zone_file(dst_store, dst_zone, TSIDX_FILE, &bytes) {
329        tracing::warn!(src = %src_zone, dst = %dst_zone, error = %e, "agent_session: tsidx sidecar copy failed (archive content unaffected)");
330    }
331}
332
333/// Delete `output.state.json` + `output` from a per-channel `:current` zone,
334/// only for files that are present (so absence isn't logged as an error).
335/// Best-effort — used after the global-preferred archive has persisted the
336/// content, to retire this channel's (subset) copy.
337///
338/// Also clears `output.idx` (#2701): an index left behind after `output` is
339/// deleted and rewritten could otherwise be accepted for a new output of the
340/// same byte size, serving the old session's line count/offsets. Since #3634
341/// the index also carries the output generation it was built for, which
342/// catches that too; deleting it here keeps the zone clean regardless.
343pub fn clear_local_current_zone(filestore: &FileStore, zone: &str) {
344    // One transaction (5a-2b); absent files are not an error.
345    if let Err(e) = filestore.delete_files(zone, &[SNAPSHOT_FILE, OUTPUT_FILE, TSIDX_FILE, "output.idx"]) {
346        tracing::warn!(zone = %zone, error = %e, "agent_session: failed to clear local current after global archive");
347    }
348}
349
350/// Delete `output.state.json` + `output` from the agent's GLOBAL
351/// `agent:<defId>:current` zone in `gfs`. Best-effort:
352/// a missing file is the expected "agent never mirrored" case (silent), other
353/// errors are logged but never propagated. Keeps the global zone in lockstep
354/// with the per-channel `:current` clear in [`archive_session`].
355///
356/// Also clears `output.idx` (#2701): an index left behind after `output` is
357/// deleted and rewritten could otherwise be accepted for a new output of the
358/// same byte size. Since #3634 the index also carries the output generation it
359/// was built for, which catches that too; deleting it here forces a rebuild
360/// against the new content regardless.
361fn clear_global_current_zone_in(gfs: &FileStore, definition_id: &str) {
362    let Ok(zone) = validate_and_current(definition_id) else {
363        return;
364    };
365    // One transaction (5a-2b); absent files are not an error.
366    if let Err(e) = gfs.delete_files(
367        &zone,
368        &[
369            SNAPSHOT_FILE,
370            OUTPUT_FILE,
371            TSIDX_FILE,
372            "output.idx",
373            // The running summary describes the conversation being archived.
374            crate::backend::continuity_state::STATE_FILE,
375        ],
376    ) {
377        tracing::warn!(
378            zone = %zone, error = %e,
379            "global transcripts: failed to clear current zone on archive"
380        );
381    }
382    // The next conversation reuses this zone: what was counted in the old one is not a floor for it.
383    crate::backend::transcript::images::forget(&zone);
384}
385
386/// List archive zones for `definition_id`, newest first.
387///
388/// Returns up to `limit` rows. `limit = 0` means "default 20"; caller
389/// must clamp upper bounds. Each row carries a small preview lifted
390/// from the archive's `output.state.json`.
391pub fn list_archives(
392    filestore: &FileStore,
393    definition_id: &str,
394    limit: usize,
395) -> Result<Vec<ArchiveSummary>, String> {
396    list_archives_in(filestore, global_transcript_store().map(|g| g.as_ref()), definition_id, limit)
397}
398
399/// [`list_archives`] over the global store, where archives are written, and
400/// the per-channel store, which holds archives written before that.
401pub(crate) fn list_archives_in(
402    filestore: &FileStore,
403    global: Option<&FileStore>,
404    definition_id: &str,
405    limit: usize,
406) -> Result<Vec<ArchiveSummary>, String> {
407    if !is_valid_definition_id(definition_id) {
408        return Err(format!(
409            "INVALID_DEFINITION_ID: must match [A-Za-z0-9_-]+, got {:?}",
410            definition_id
411        ));
412    }
413    let prefix = format!("agent:{}:archive:", definition_id);
414    let limit = if limit == 0 { 20 } else { limit.min(100) };
415    // A zone found corrupt is not listed from.
416    let global = global.filter(|_| !crate::backend::transcript::damage::is_damaged(&agent_current_zone(definition_id)));
417
418    let mut matches: Vec<(u64, String, &FileStore)> = Vec::new();
419    for store in global.into_iter().chain(std::iter::once(filestore)) {
420        let is_global = global.is_some_and(|g| std::ptr::eq(g, store));
421        let zones = match store.zone_ids_with_prefix(&prefix) {
422            Ok(zones) => zones,
423            // The shared store answers with a corrupt file: the archives it held are left out of the list,
424            // and the per-channel ones are listed.
425            Err(e) if is_global && crate::backend::transcript::damage::note_if_shared(store, &agent_current_zone(definition_id), "archive list", &e) => continue,
426            Err(e) => return Err(format!("zone_ids_with_prefix: {e}")),
427        };
428        for zone in zones {
429            let Some(Ok(ts)) = zone.strip_prefix(&prefix).map(str::parse::<u64>) else {
430                continue;
431            };
432            // The global copy wins when both stores hold the same archive.
433            if !matches.iter().any(|(_, z, _)| *z == zone) {
434                matches.push((ts, zone, store));
435            }
436        }
437    }
438    // Newest first.
439    matches.sort_by(|a, b| b.0.cmp(&a.0));
440    matches.truncate(limit);
441
442    let mut rows = Vec::with_capacity(matches.len());
443    for (ts, zone, store) in matches {
444        let (preview, node_count) = read_archive_preview(store, &zone);
445        rows.push(ArchiveSummary {
446            archive_zoneid: zone,
447            archived_at_ms: ts as i64,
448            preview,
449            node_count,
450        });
451    }
452    Ok(rows)
453}
454
455/// A single archive row. Mirrors the shape of `RecentSessionRow`'s
456/// preview fields so the frontend can reuse the same row component.
457#[derive(Debug, Clone)]
458pub struct ArchiveSummary {
459    pub archive_zoneid: String,
460    pub archived_at_ms: i64,
461    pub preview: String,
462    pub node_count: usize,
463}
464
465/// Pull a small preview + node_count out of an archive's
466/// `output.state.json`. Returns `("", 0)` on any error.
467fn read_archive_preview(filestore: &FileStore, zone: &str) -> (String, usize) {
468    let bytes = match filestore.read_file(zone, SNAPSHOT_FILE) {
469        Ok(Some(b)) => b,
470        _ => return (String::new(), 0),
471    };
472    if bytes.len() > MAX_PREVIEW_SNAPSHOT_BYTES {
473        return (String::new(), 0);
474    }
475    snapshot_preview(&bytes)
476}
477
478/// Snapshots larger than this are not parsed for a preview, so a corrupted one
479/// can't stall a listing.
480pub const MAX_PREVIEW_SNAPSHOT_BYTES: usize = 4 * 1024 * 1024;
481
482/// `(preview, node_count)` from an `output.state.json` snapshot's bytes, or
483/// `("", 0)` when they don't parse or have no `nodes` array. The preview is
484/// the first `user_message`, skipping a leading "# Session Context" bootstrap
485/// message when a later one exists, collapsed to one line of at most 240 chars.
486pub fn snapshot_preview(bytes: &[u8]) -> (String, usize) {
487    let json: serde_json::Value = match serde_json::from_slice(bytes) {
488        Ok(v) => v,
489        Err(_) => return (String::new(), 0),
490    };
491    let nodes = match json.get("nodes").and_then(|v| v.as_array()) {
492        Some(a) => a,
493        None => return (String::new(), 0),
494    };
495    let node_count = nodes.len();
496    let mut preview = String::new();
497    for node in nodes {
498        let ty = node.get("type").and_then(|v| v.as_str()).unwrap_or("");
499        if ty != "user_message" {
500            continue;
501        }
502        let msg = node
503            .get("message")
504            .and_then(|v| v.as_str())
505            .unwrap_or("")
506            .trim();
507        if msg.is_empty() {
508            continue;
509        }
510        if preview.is_empty() && msg.starts_with("# Session Context") {
511            // Stash as fallback in case there's no later user_message.
512            preview = collapse_preview(msg);
513            continue;
514        }
515        preview = collapse_preview(msg);
516        break;
517    }
518    (preview, node_count)
519}
520
521/// Collapse newlines + extra whitespace, cap at 240 chars. Output is
522/// safe to render inline in a single-line preview row.
523pub fn collapse_preview(s: &str) -> String {
524    const MAX_CHARS: usize = 240;
525    let mut buf = String::with_capacity(s.len().min(MAX_CHARS + 4));
526    let mut prev_space = false;
527    for ch in s.chars() {
528        if buf.chars().count() >= MAX_CHARS {
529            buf.push('\u{2026}'); // "…"
530            return buf;
531        }
532        if ch.is_whitespace() {
533            if !prev_space && !buf.is_empty() {
534                buf.push(' ');
535                prev_space = true;
536            }
537        } else {
538            buf.push(ch);
539            prev_space = false;
540        }
541    }
542    buf
543}
544
545#[cfg(test)]
546mod preview_tests {
547    use super::snapshot_preview;
548
549    #[test]
550    fn snapshot_preview_skips_a_leading_session_context_and_counts_nodes() {
551        let snap = serde_json::json!({ "nodes": [
552            { "type": "user_message", "message": "# Session Context\nboilerplate" },
553            { "type": "markdown", "content": "ack" },
554            { "type": "user_message", "message": "  fix the\n\nbug  " },
555        ]});
556        let bytes = serde_json::to_vec(&snap).unwrap();
557        assert_eq!(snapshot_preview(&bytes), ("fix the bug".to_string(), 3));
558        assert_eq!(snapshot_preview(b"not json"), (String::new(), 0));
559        assert_eq!(snapshot_preview(br#"{"nodes":{}}"#), (String::new(), 0));
560    }
561}
562
563#[cfg(test)]
564mod image_count_tests {
565    use super::*;
566    use crate::backend::transcript::images;
567
568    #[test]
569    fn clearing_the_current_zone_forgets_the_images_counted_in_it() {
570        let def = "def-arch-images-1";
571        let zone = agent_current_zone(def);
572        let gfs = FileStore::open_in_memory().unwrap();
573        let line = serde_json::json!({ "type": "user", "message": { "role": "user", "content":
574            "look\n\n<attached_files>\nThe user attached 1 files.\n1. a.png — /x/ab/0123.v1-e2000.send.png\n</attached_files>" } });
575        write_zone_file(&gfs, &zone, OUTPUT_FILE, format!("{line}\n").as_bytes()).unwrap();
576        assert_eq!(images::count_in_zone(&gfs, &zone).unwrap(), 1);
577        assert_eq!(images::counted(&zone), Some(1));
578
579        clear_global_current_zone_in(&gfs, def);
580
581        assert_eq!(images::counted(&zone), None, "the next conversation in this zone starts with no count");
582    }
583}
584
585#[cfg(test)]
586mod damage_tests {
587    use super::*;
588    use crate::backend::transcript::damage::{self, test_support};
589
590    fn snapshot(content: &str) -> Vec<u8> {
591        serde_json::to_vec(&serde_json::json!({ "nodes": [{ "type": "user_message", "message": content }] })).unwrap()
592    }
593
594    #[test]
595    fn an_archive_that_finds_the_shared_zone_corrupt_marks_it_and_the_next_one_uses_this_channels_copy() {
596        let def = "def-arch-damage-1";
597        let zone = agent_current_zone(def);
598        let (own, gfs) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap());
599        write_zone_file(&own, &zone, SNAPSHOT_FILE, &snapshot("asked")).unwrap();
600        let _shared = test_support::register(&gfs);
601        test_support::corrupt(&gfs);
602
603        // The first call meets the corruption: marked, and the failure is reported as before.
604        assert!(archive_session_in(&own, Some(&gfs), def).is_err());
605        assert!(damage::is_damaged(&zone));
606        // This channel's current was not cleared by a move that never started: the next call archives it, from this channel.
607        let (archive_zone, _) = archive_session_in(&own, Some(&gfs), def).unwrap().expect("archived from this channel's copy");
608        assert!(archive_zone.starts_with(&format!("agent:{def}:archive:")));
609        assert!(own.stat(&archive_zone, SNAPSHOT_FILE).unwrap().is_some_and(|f| f.size > 0), "the archive is in this channel's store");
610    }
611
612    #[test]
613    fn a_corrupt_channel_store_does_not_mark_a_healthy_shared_zone() {
614        let def = "def-arch-damage-3";
615        let zone = agent_current_zone(def);
616        let (own, gfs) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap());
617        let _shared = test_support::register(&gfs);
618        test_support::corrupt(&own);
619        // The shared store has nothing to archive; this channel's own store is what fails.
620        let err = archive_session_in(&own, Some(&gfs), def).unwrap_err();
621        assert!(err.contains("malformed"), "{err}");
622        assert!(!damage::is_damaged(&zone), "the failure was in the channel's store, not the shared zone");
623    }
624
625    #[test]
626    fn archives_are_listed_from_this_channel_when_the_shared_store_is_corrupt() {
627        let def = "def-arch-damage-2";
628        let archive = format!("agent:{def}:archive:1700000000000");
629        let (own, gfs) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap());
630        write_zone_file(&own, &archive, SNAPSHOT_FILE, &snapshot("older")).unwrap();
631        let _shared = test_support::register(&gfs);
632        test_support::corrupt(&gfs);
633        let rows = list_archives_in(&own, Some(&gfs), def, 10).expect("the list is answered from this channel");
634        assert_eq!(rows.len(), 1);
635        assert_eq!(rows[0].archive_zoneid, archive);
636        assert!(damage::is_damaged(&agent_current_zone(def)));
637        // Marked: the shared store is not asked again.
638        assert_eq!(list_archives_in(&own, Some(&gfs), def, 10).unwrap().len(), 1);
639    }
640}