1use std::io::{Read, Write};
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use flate2::Compression;
22use flate2::read::GzDecoder;
23use flate2::write::GzEncoder;
24
25use crate::backend::blockcontroller::session_stats::{
26 META_SESSION_LAST_ACTIVITY_MS, META_SESSION_LINE_COUNT,
27};
28use crate::backend::obj::{Block, MetaMapType};
29use crate::backend::storage::filestore::{FileStore, FileMeta, FileOpts};
30use crate::backend::storage::store::Store;
31use crate::backend::transcript::source::TranscriptSource;
32
33pub const META_SESSION_ARCHIVED_AT: &str = "session:archived_at";
37pub const META_SESSION_ARCHIVED_BYTES: &str = "session:archived_bytes";
39pub const META_SESSION_ARCHIVE_PATH: &str = "session:archive_path";
41
42const OUTPUT_FILENAME: &str = "output";
44const TSIDX_FILENAME: &str = crate::backend::agent_session::session_io::TSIDX_FILE;
50
51use agentmux_common::time::now_ms;
56
57fn write_gz(data: &[u8], dest_path: &Path) -> Result<(), String> {
59 let file = std::fs::File::create(dest_path)
60 .map_err(|e| format!("create archive file {}: {e}", dest_path.display()))?;
61 let mut encoder = GzEncoder::new(file, Compression::default());
62 encoder.write_all(data)
63 .map_err(|e| format!("compress: {e}"))?;
64 encoder.finish()
65 .map_err(|e| format!("gz finish: {e}"))?;
66 Ok(())
67}
68
69fn read_gz(src_path: &Path) -> Result<Vec<u8>, String> {
71 let file = std::fs::File::open(src_path)
72 .map_err(|e| format!("open archive {}: {e}", src_path.display()))?;
73 let mut decoder = GzDecoder::new(file);
74 let mut out = Vec::new();
75 decoder.read_to_end(&mut out)
76 .map_err(|e| format!("decompress: {e}"))?;
77 Ok(out)
78}
79
80fn ensure_archive_dir(archive_dir: &Path) -> Result<(), String> {
82 std::fs::create_dir_all(archive_dir)
83 .map_err(|e| format!("create archive dir {}: {e}", archive_dir.display()))
84}
85
86pub fn archive_session_output(
104 mstore: &Arc<Store>,
105 filestore: &Arc<FileStore>,
106 block_id: &str,
107 archive_dir: &Path,
108) -> Result<(u64, i64), String> {
109 let global = crate::backend::agent_session::global_transcript_store().map(|g| g.as_ref());
110 archive_session_output_with(mstore, filestore, global, block_id, archive_dir)
111}
112
113pub fn archive_session_output_with(
115 mstore: &Arc<Store>,
116 filestore: &Arc<FileStore>,
117 global: Option<&FileStore>,
118 block_id: &str,
119 archive_dir: &Path,
120) -> Result<(u64, i64), String> {
121 let source = TranscriptSource::resolve_with(filestore, global, mstore, block_id);
122 let raw_bytes = match source.fs.read_file(&source.zone, OUTPUT_FILENAME) {
124 Ok(Some(b)) if !b.is_empty() => b,
125 Ok(_) => {
126 return Ok((0, now_ms()));
128 }
129 Err(e) => return Err(format!("filestore read: {e}")),
130 };
131
132 let archived_bytes = raw_bytes.len() as u64;
133
134 ensure_archive_dir(archive_dir)?;
135
136 let archive_path = archive_dir.join(format!("{}.jsonl.gz", block_id));
137 write_gz(&raw_bytes, &archive_path)?;
138
139 let archived_at = now_ms();
140
141 let mut meta = MetaMapType::new();
146 meta.insert(META_SESSION_ARCHIVED_AT.to_string(), serde_json::json!(archived_at));
147 meta.insert(META_SESSION_ARCHIVED_BYTES.to_string(), serde_json::json!(archived_bytes));
148 meta.insert(
149 META_SESSION_ARCHIVE_PATH.to_string(),
150 serde_json::json!(archive_path.to_string_lossy().as_ref()),
151 );
152
153 let oref_str = format!("block:{}", block_id);
154 if let Err(e) = crate::backend::wcore::object_meta::update_object_meta(mstore, &oref_str, &meta) {
155 let _ = std::fs::remove_file(&archive_path);
157 return Err(format!("update_object_meta: {e}"));
158 }
159
160 if let Ok(Some(ts_bytes)) = source.fs.read_file(&source.zone, TSIDX_FILENAME) {
163 if !ts_bytes.is_empty() {
164 let ts_path = archive_dir.join(format!("{}.tsidx.gz", block_id));
165 if let Err(e) = write_gz(&ts_bytes, &ts_path) {
166 tracing::warn!(block_id = %block_id, error = %e, "session_archive: tsidx archive write failed (output archive unaffected)");
167 }
168 }
169 }
170 if let Err(e) = filestore.delete_files(block_id, &[OUTPUT_FILENAME, TSIDX_FILENAME, "output.idx"]) {
175 tracing::warn!(
176 block_id = %block_id,
177 error = %e,
178 "session_archive: failed to delete filestore entry after archiving (meta already updated)"
179 );
180 }
181
182 tracing::info!(
183 block_id = %block_id,
184 archived_bytes = archived_bytes,
185 archive_path = %archive_path.display(),
186 "session archived"
187 );
188
189 Ok((archived_bytes, archived_at))
190}
191
192pub fn restore_session_output(
201 mstore: &Arc<Store>,
202 filestore: &Arc<FileStore>,
203 block_id: &str,
204) -> Result<u64, String> {
205 let block: Block = mstore
207 .get(block_id)
208 .map_err(|e| format!("mstore.get: {e}"))?
209 .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", block_id))?;
210
211 let archive_path_str = block
212 .meta
213 .get(META_SESSION_ARCHIVE_PATH)
214 .and_then(|v| v.as_str())
215 .ok_or_else(|| format!("session:archive_path not set for block {}", block_id))?
216 .to_string();
217
218 let archive_path = PathBuf::from(&archive_path_str);
219 let raw_bytes = read_gz(&archive_path)?;
220 let restored_bytes = raw_bytes.len() as u64;
221
222 filestore
227 .replace_file(block_id, OUTPUT_FILENAME, &raw_bytes, &[TSIDX_FILENAME, "output.idx"])
228 .map_err(|e| format!("replace_file: {e}"))?;
229
230 let ts_path = archive_path
234 .parent()
235 .map(|d| d.join(format!("{}.tsidx.gz", block_id)))
236 .filter(|p| p.exists());
237 if let Some(ts_path) = ts_path {
238 match read_gz(&ts_path) {
239 Ok(ts_bytes) if !ts_bytes.is_empty() => {
240 let created = filestore
241 .make_file(block_id, TSIDX_FILENAME, FileMeta::default(), FileOpts::default());
242 if created.is_ok() {
243 if let Err(e) = filestore.append_data(block_id, TSIDX_FILENAME, &ts_bytes) {
244 tracing::warn!(block_id = %block_id, error = %e, "session_archive: tsidx restore append failed");
245 }
246 }
247 }
248 Ok(_) => {}
249 Err(e) => {
250 tracing::warn!(block_id = %block_id, error = %e, "session_archive: tsidx restore read failed");
251 }
252 }
253 }
254
255 let mut meta = MetaMapType::new();
257 meta.insert(META_SESSION_ARCHIVED_AT.to_string(), serde_json::Value::Null);
258 meta.insert(META_SESSION_ARCHIVED_BYTES.to_string(), serde_json::Value::Null);
259 meta.insert(META_SESSION_ARCHIVE_PATH.to_string(), serde_json::Value::Null);
260
261 let oref_str = format!("block:{}", block_id);
262 crate::backend::wcore::object_meta::update_object_meta(mstore, &oref_str, &meta)
263 .map_err(|e| format!("update_object_meta: {e}"))?;
264
265 tracing::info!(
266 block_id = %block_id,
267 restored_bytes = restored_bytes,
268 archive_path = %archive_path_str,
269 "session restored"
270 );
271
272 Ok(restored_bytes)
273}
274
275pub fn read_session_output(
285 mstore: &Arc<Store>,
286 filestore: &Arc<FileStore>,
287 block_id: &str,
288) -> Result<(Vec<u8>, u64), String> {
289 let global = crate::backend::agent_session::global_transcript_store().map(|g| g.as_ref());
290 read_session_output_with(mstore, filestore, global, block_id)
291}
292
293pub fn read_session_output_with(
295 mstore: &Arc<Store>,
296 filestore: &Arc<FileStore>,
297 global: Option<&FileStore>,
298 block_id: &str,
299) -> Result<(Vec<u8>, u64), String> {
300 let block: Block = mstore
302 .get(block_id)
303 .map_err(|e| format!("mstore.get: {e}"))?
304 .ok_or_else(|| format!("BLOCK_NOT_FOUND: {}", block_id))?;
305
306 let is_archived = block
307 .meta
308 .get(META_SESSION_ARCHIVED_AT)
309 .and_then(|v| v.as_i64())
310 .map(|v| v > 0)
311 .unwrap_or(false);
312
313 let raw_bytes = if is_archived {
314 let archive_path_str = block
315 .meta
316 .get(META_SESSION_ARCHIVE_PATH)
317 .and_then(|v| v.as_str())
318 .ok_or_else(|| "session:archive_path not set".to_string())?
319 .to_string();
320 read_gz(Path::new(&archive_path_str))?
321 } else {
322 let source = TranscriptSource::resolve_with(filestore, global, mstore, block_id);
323 source
324 .fs
325 .read_file(&source.zone, OUTPUT_FILENAME)
326 .map_err(|e| format!("filestore read: {e}"))?
327 .unwrap_or_default()
328 };
329
330 let line_count = bytecount_lines(&raw_bytes);
331 Ok((raw_bytes, line_count))
332}
333
334fn bytecount_lines(data: &[u8]) -> u64 {
336 let text = String::from_utf8_lossy(data);
337 text.lines().filter(|l| !l.trim().is_empty()).count() as u64
338}
339
340pub fn default_archive_dir() -> Option<PathBuf> {
346 crate::srv_info::agentmux_root().map(|root| root.join("archives"))
351}
352
353pub struct SessionArchiver {
359 mstore: Arc<Store>,
360 filestore: Arc<FileStore>,
361 pub inactive_days: u64,
363 pub archive_dir: PathBuf,
365}
366
367#[derive(Debug, Clone, Default)]
369pub struct SessionArchiverStats {
370 pub archived_count: u32,
371 pub bytes_freed: u64,
372}
373
374impl SessionArchiver {
375 pub fn new(
376 mstore: Arc<Store>,
377 filestore: Arc<FileStore>,
378 inactive_days: u64,
379 archive_dir: PathBuf,
380 ) -> Self {
381 Self { mstore, filestore, inactive_days, archive_dir }
382 }
383
384 pub async fn sweep(&self) -> Result<SessionArchiverStats, String> {
388 let mut stats = SessionArchiverStats::default();
389 let now = now_ms();
390 let cutoff_ms = self.inactive_days as i64 * 86_400_000;
391
392 let all_blocks: Vec<Block> = self
394 .mstore
395 .get_all::<Block>()
396 .map_err(|e| format!("get_all blocks: {e}"))?;
397
398 for block in &all_blocks {
399 let view = block.meta.get("view").and_then(|v| v.as_str()).unwrap_or("");
401 if view != "agent" {
402 continue;
403 }
404
405 let archived_at = block
407 .meta
408 .get(META_SESSION_ARCHIVED_AT)
409 .and_then(|v| v.as_i64())
410 .unwrap_or(0);
411 if archived_at > 0 {
412 continue;
413 }
414
415 let last_activity = match block
417 .meta
418 .get(META_SESSION_LAST_ACTIVITY_MS)
419 .and_then(|v| v.as_i64())
420 {
421 Some(v) if v > 0 => v,
422 _ => continue,
423 };
424
425 let line_count = block
427 .meta
428 .get(META_SESSION_LINE_COUNT)
429 .and_then(|v| v.as_u64())
430 .unwrap_or(0);
431 if line_count == 0 {
432 continue;
433 }
434
435 if now - last_activity < cutoff_ms {
437 continue;
438 }
439
440 match archive_session_output(
442 &self.mstore,
443 &self.filestore,
444 &block.oid,
445 &self.archive_dir,
446 ) {
447 Ok((bytes, _)) => {
448 stats.archived_count += 1;
449 stats.bytes_freed += bytes;
450 tracing::info!(
451 block_id = %block.oid,
452 bytes_freed = bytes,
453 "session archiver: auto-archived inactive session"
454 );
455 }
456 Err(e) => {
457 tracing::warn!(
458 block_id = %block.oid,
459 error = %e,
460 "session archiver: failed to archive session"
461 );
462 }
463 }
464 }
465
466 Ok(stats)
467 }
468}
469
470#[cfg(test)]
475mod tests {
476 use super::*;
477 use std::sync::Arc;
478 use crate::backend::storage::filestore::FileStore;
479 use crate::backend::storage::store::Store;
480
481 #[tokio::test]
484 async fn test_sweep_archives_inactive_session() {
485 let tmp_dir = tempfile::tempdir().expect("tempdir");
487 let archive_dir = tmp_dir.path().to_path_buf();
488
489 let filestore = Arc::new(
491 FileStore::open_in_memory().expect("filestore"),
492 );
493 let block_id_owned = uuid::Uuid::new_v4().to_string();
501 let block_id = block_id_owned.as_str();
502 filestore
503 .make_file(block_id, OUTPUT_FILENAME, FileMeta::default(), FileOpts::default())
504 .expect("make_file");
505 filestore
506 .append_data(block_id, OUTPUT_FILENAME, b"line1\nline2\n")
507 .expect("append_data");
508
509 let db_dir = tmp_dir.path().join("wdb");
511 std::fs::create_dir_all(&db_dir).unwrap();
512 let mstore = Arc::new(
513 Store::open(&db_dir.join("objects.db")).expect("mstore"),
514 );
515
516 use crate::backend::obj::{Block, MetaMapType};
518 let mut meta = MetaMapType::new();
519 meta.insert("view".to_string(), serde_json::json!("agent"));
520 let ten_days_ago = now_ms() - 10 * 86_400_000;
522 meta.insert(
523 META_SESSION_LAST_ACTIVITY_MS.to_string(),
524 serde_json::json!(ten_days_ago),
525 );
526 meta.insert(META_SESSION_LINE_COUNT.to_string(), serde_json::json!(2u64));
527
528 let mut block = Block {
529 oid: block_id.to_string(),
530 parentoref: String::new(),
531 version: 1,
532 runtimeopts: None,
533 stickers: None,
534 meta,
535 subblockids: None,
536 };
537 mstore.insert(&mut block).expect("mstore insert");
538
539 let archiver = SessionArchiver::new(
541 mstore.clone(),
542 filestore.clone(),
543 1, archive_dir.clone(),
545 );
546
547 let stats = archiver.sweep().await.expect("sweep");
548 assert_eq!(stats.archived_count, 1, "should archive 1 session");
549 assert!(stats.bytes_freed > 0, "should free bytes");
550
551 let remaining = filestore.stat(block_id, OUTPUT_FILENAME).unwrap();
553 assert!(remaining.is_none(), "filestore entry should be deleted after archive");
554
555 let gz_path = archive_dir.join(format!("{}.jsonl.gz", block_id));
557 assert!(gz_path.exists(), ".gz file should exist");
558
559 let updated_block: Option<Block> = mstore.get(block_id).unwrap();
561 let updated_block = updated_block.expect("block still in store");
562 let archived_at = updated_block
563 .meta
564 .get(META_SESSION_ARCHIVED_AT)
565 .and_then(|v| v.as_i64())
566 .unwrap_or(0);
567 assert!(archived_at > 0, "session:archived_at should be set");
568 }
569
570 #[test]
571 fn test_bytecount_lines() {
572 assert_eq!(bytecount_lines(b""), 0);
573 assert_eq!(bytecount_lines(b"line1\n"), 1);
574 assert_eq!(bytecount_lines(b"line1\nline2\n"), 2);
575 assert_eq!(bytecount_lines(b" \n\nline3\n"), 1); }
577
578 #[test]
579 fn test_gz_roundtrip() {
580 let tmp = tempfile::NamedTempFile::new().unwrap();
581 let data = b"hello compressed world\nline2\n";
582 write_gz(data, tmp.path()).unwrap();
583 let out = read_gz(tmp.path()).unwrap();
584 assert_eq!(out, data);
585 }
586
587 const SINGLE_DEF: &str = "def-single-copy";
590
591 struct Rig {
592 _dir: tempfile::TempDir,
593 mstore: Arc<Store>,
594 block_fs: Arc<FileStore>,
595 global: FileStore,
596 block_id: String,
597 }
598
599 fn rig() -> Rig {
601 use crate::backend::obj::{Block, MetaMapType};
602 let dir = tempfile::tempdir().expect("tempdir");
603 let mstore = Arc::new(Store::open(&dir.path().join("objects.db")).expect("mstore"));
604 let block_id = uuid::Uuid::new_v4().to_string();
605 let mut meta = MetaMapType::new();
606 meta.insert("agentId".to_string(), serde_json::json!(SINGLE_DEF));
607 let mut block = Block { oid: block_id.clone(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
608 mstore.insert(&mut block).expect("insert block");
609 Rig { _dir: dir, mstore, block_fs: Arc::new(FileStore::open_in_memory().unwrap()), global: FileStore::open_in_memory().unwrap(), block_id }
610 }
611
612 fn put(fs: &FileStore, zone: &str, name: &str, bytes: &[u8]) {
613 fs.make_file(zone, name, FileMeta::default(), FileOpts::default()).unwrap();
614 fs.append_data(zone, name, bytes).unwrap();
615 }
616
617 impl Rig {
618 fn zone(&self) -> String {
619 crate::backend::agent_session::agent_current_zone(SINGLE_DEF)
620 }
621 fn export(&self, with_global: bool) -> (Vec<u8>, u64) {
622 read_session_output_with(&self.mstore, &self.block_fs, with_global.then_some(&self.global), &self.block_id).unwrap()
623 }
624 }
625
626 #[test]
627 fn an_export_of_a_defined_agents_block_reads_the_single_copy_when_the_block_has_none() {
628 let r = rig();
629 put(&r.global, &r.zone(), OUTPUT_FILENAME, b"only
630in the zone
631");
632 assert_eq!(r.export(true), (b"only
633in the zone
634".to_vec(), 2));
635 }
636
637 #[test]
638 fn an_export_reads_the_block_copy_when_there_is_no_single_copy() {
639 let r = rig();
640 put(&r.block_fs, &r.block_id, OUTPUT_FILENAME, b"block
641copy
642");
643 assert_eq!(r.export(true), (b"block
644copy
645".to_vec(), 2), "an empty zone: the block's own copy");
646 assert_eq!(r.export(false), (b"block
647copy
648".to_vec(), 2), "no global store: the block's own copy");
649 }
650
651 #[test]
652 fn an_export_reads_the_single_copy_when_the_block_has_one_too() {
653 let r = rig();
654 put(&r.global, &r.zone(), OUTPUT_FILENAME, b"one
655two
656three
657");
658 put(&r.block_fs, &r.block_id, OUTPUT_FILENAME, b"one
659two
660");
661 assert_eq!(r.export(true), (b"one
662two
663three
664".to_vec(), 3), "the copy the pane reads");
665 assert_eq!(r.export(false).0, b"one
666two
667".to_vec(), "without a global store the block's own copy is all there is");
668 }
669
670 #[test]
671 fn a_block_that_is_not_a_defined_agents_reads_its_own_copy() {
672 use crate::backend::obj::{Block, MetaMapType};
673 let r = rig();
674 put(&r.global, &r.zone(), OUTPUT_FILENAME, b"the agent's record
675");
676 let mut meta = MetaMapType::new();
677 meta.insert("view".to_string(), serde_json::json!("term"));
678 let other = uuid::Uuid::new_v4().to_string();
679 let mut block = Block { oid: other.clone(), parentoref: String::new(), version: 1, runtimeopts: None, stickers: None, meta, subblockids: None };
680 r.mstore.insert(&mut block).unwrap();
681 put(&r.block_fs, &other, OUTPUT_FILENAME, b"its own
682");
683 let (bytes, _) = read_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &other).unwrap();
684 assert_eq!(bytes, b"its own
685".to_vec());
686 }
687
688 #[test]
689 fn an_archive_takes_the_single_copy_and_leaves_the_agents_zone_alone() {
690 let r = rig();
691 let record = b"line one
692line two
693";
694 put(&r.global, &r.zone(), OUTPUT_FILENAME, record);
695 put(&r.global, &r.zone(), TSIDX_FILENAME, b"stamps");
696 let archive_dir = tempfile::tempdir().unwrap();
697 let (bytes, at) = archive_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &r.block_id, archive_dir.path()).unwrap();
698 assert_eq!(bytes, record.len() as u64);
699 assert!(at > 0);
700 let gz = archive_dir.path().join(format!("{}.jsonl.gz", r.block_id));
701 assert_eq!(read_gz(&gz).unwrap(), record.to_vec(), "the archive holds the single copy");
702 let ts = archive_dir.path().join(format!("{}.tsidx.gz", r.block_id));
703 assert_eq!(read_gz(&ts).unwrap(), b"stamps".to_vec(), "and its receive times");
704 assert_eq!(r.global.read_file(&r.zone(), OUTPUT_FILENAME).unwrap().as_deref(), Some(&record[..]), "the agent's zone is not the block's to delete");
705 assert_eq!(r.export(true), (record.to_vec(), 2));
707 }
708
709 #[test]
710 fn an_archive_of_the_block_copy_is_as_it_was() {
711 let r = rig();
712 put(&r.block_fs, &r.block_id, OUTPUT_FILENAME, b"block
713copy
714");
715 let archive_dir = tempfile::tempdir().unwrap();
716 let (bytes, _) = archive_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &r.block_id, archive_dir.path()).unwrap();
717 assert_eq!(bytes, 11);
718 assert!(r.block_fs.stat(&r.block_id, OUTPUT_FILENAME).unwrap().is_none(), "the block's copy is deleted");
719 assert_eq!(archive_session_output_with(&r.mstore, &r.block_fs, Some(&r.global), &r.block_id, archive_dir.path()).unwrap().0, 0, "nothing left to archive");
720 }
721}