1use 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
13pub 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
38pub(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 let global = global.filter(|_| !damage::is_damaged(&zone));
55 let archived = archive_session_with(filestore, global, definition_id)?;
56 if archived.is_some() {
57 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 if let Some(gfs) = global {
83 let archived = archive_global_current(gfs, definition_id, || clear_local_current_zone(filestore, ¤t_zone)).inspect_err(|e| {
90 crate::backend::transcript::damage::note_corrupt_text(¤t_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 GlobalArchive::ArchivedElsewhere => return Ok(None),
99 GlobalArchive::Nothing => {}
100 }
101 }
102
103 let state_stat = filestore
105 .stat(¤t_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(¤t_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 let target = global.unwrap_or(filestore);
127 let staging = format!("agent:{definition_id}:archiving:{}", uuid::Uuid::new_v4());
128
129 if has_state {
131 let snapshot_bytes = filestore
132 .read_file(¤t_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 if has_output {
139 let output_bytes = filestore
140 .read_file(¤t_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 copy_tsidx_best_effort(filestore, ¤t_zone, target, &staging);
153 }
154 let (archive_zone, ts) = claim_archive_zone(target, &staging, definition_id)?;
155
156 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(¤t_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 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
200fn 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, ¤t_zone, "archive", &e);
211 format!("{op}: {e}")
212 };
213 let has = |name: &str| -> Result<bool, String> {
214 Ok(gfs.stat(¤t_zone, name).map_err(|e| seen("stat", e))?.is_some_and(|f| f.size > 0))
215 };
216 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 let settled = crate::backend::transcript::live::settle(gfs, ¤t_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 files.push(crate::backend::transcript::live::LIVE_FILE);
229 }
230 for _ in 0..8 {
234 let (archive_zone, ts) = free_archive_zone(gfs, definition_id)?;
235 match gfs
236 .move_files_to_zone(¤t_zone, &archive_zone, &files)
237 .map_err(|e| format!("move to archive: {e}"))?
238 {
239 None => continue,
241 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
257enum GlobalArchive {
259 Archived(String, i64),
260 Nothing,
262 ArchivedElsewhere,
264}
265
266fn claim_archive_zone(store: &FileStore, staging: &str, definition_id: &str) -> Result<(String, u64), String> {
270 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
284pub(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
301fn 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
316fn 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
333pub fn clear_local_current_zone(filestore: &FileStore, zone: &str) {
344 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
350fn clear_global_current_zone_in(gfs: &FileStore, definition_id: &str) {
362 let Ok(zone) = validate_and_current(definition_id) else {
363 return;
364 };
365 if let Err(e) = gfs.delete_files(
367 &zone,
368 &[
369 SNAPSHOT_FILE,
370 OUTPUT_FILE,
371 TSIDX_FILE,
372 "output.idx",
373 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 crate::backend::transcript::images::forget(&zone);
384}
385
386pub 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
399pub(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 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 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 if !matches.iter().any(|(_, z, _)| *z == zone) {
434 matches.push((ts, zone, store));
435 }
436 }
437 }
438 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#[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
465fn 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
478pub const MAX_PREVIEW_SNAPSHOT_BYTES: usize = 4 * 1024 * 1024;
481
482pub 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 preview = collapse_preview(msg);
513 continue;
514 }
515 preview = collapse_preview(msg);
516 break;
517 }
518 (preview, node_count)
519}
520
521pub 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}'); 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 assert!(archive_session_in(&own, Some(&gfs), def).is_err());
605 assert!(damage::is_damaged(&zone));
606 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 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 assert_eq!(list_archives_in(&own, Some(&gfs), def, 10).unwrap().len(), 1);
639 }
640}