1use std::collections::{BTreeMap, BTreeSet};
33use std::fs as stdfs;
34use std::path::{Component, Path, PathBuf};
35use std::rc::Rc;
36use std::sync::{Mutex, OnceLock};
37
38use harn_vm::VmValue;
39use serde::{Deserialize, Serialize};
40use sha2::{Digest, Sha256};
41
42use crate::error::HostlibError;
43use crate::registry::{BuiltinRegistry, HostlibCapability, RegisteredBuiltin, SyncHandler};
44use crate::tools::args::{
45 build_dict, dict_arg, optional_string, optional_string_list, require_string, str_value,
46};
47
48const SNAPSHOT_BUILTIN: &str = "hostlib_fs_snapshot";
49const RESTORE_BUILTIN: &str = "hostlib_fs_restore";
50const LIST_BUILTIN: &str = "hostlib_fs_list_snapshots";
51const DROP_BUILTIN: &str = "hostlib_fs_drop_snapshot";
52
53const MANIFEST_VERSION: u32 = 1;
54const STATE_REL: &[&str] = &[".harn", "state", "snapshots"];
55
56pub const DEFAULT_SESSION_BYTE_CAP: u64 = 1024 * 1024 * 1024;
60
61#[derive(Default)]
63pub struct FsSnapshotCapability;
64
65impl HostlibCapability for FsSnapshotCapability {
66 fn module_name(&self) -> &'static str {
67 "fs"
71 }
72
73 fn register_builtins(&self, registry: &mut BuiltinRegistry) {
74 register(registry, SNAPSHOT_BUILTIN, "snapshot", snapshot_builtin);
75 register(registry, RESTORE_BUILTIN, "restore", restore_builtin);
76 register(
77 registry,
78 LIST_BUILTIN,
79 "list_snapshots",
80 list_snapshots_builtin,
81 );
82 register(
83 registry,
84 DROP_BUILTIN,
85 "drop_snapshot",
86 drop_snapshot_builtin,
87 );
88 }
89}
90
91fn register(
92 registry: &mut BuiltinRegistry,
93 name: &'static str,
94 method: &'static str,
95 runner: fn(&[VmValue]) -> Result<VmValue, HostlibError>,
96) {
97 let handler: SyncHandler = std::sync::Arc::new(runner);
98 registry.register(RegisteredBuiltin {
99 name,
100 module: "fs",
101 method,
102 handler,
103 });
104}
105
106#[derive(Clone, Debug, Serialize, Deserialize)]
107#[serde(tag = "kind", rename_all = "snake_case")]
108enum SnapshotEntry {
109 File {
110 body_hash: String,
111 len: u64,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 mode: Option<u32>,
114 },
115 Absent,
116}
117
118#[derive(Clone, Debug, Serialize, Deserialize)]
119struct Manifest {
120 version: u32,
121 snapshot_id: String,
122 scope_id: String,
123 session_id: String,
124 root: String,
125 taken_at_ms: i64,
126 entries: BTreeMap<String, SnapshotEntry>,
127}
128
129#[derive(Clone, Debug)]
130struct SnapshotState {
131 snapshot_id: String,
132 scope_id: String,
133 session_id: String,
134 root: PathBuf,
135 taken_at_ms: i64,
136 entries: BTreeMap<PathBuf, SnapshotEntry>,
138}
139
140#[derive(Clone, Debug)]
142pub struct SnapshotSummary {
143 pub snapshot_id: String,
145 pub scope_id: String,
147 pub taken_at_ms: i64,
149 pub captured_paths: Vec<String>,
151 pub byte_count: u64,
153}
154
155#[derive(Clone, Debug)]
157pub struct SnapshotResult {
158 pub snapshot_id: String,
160 pub captured_paths: Vec<String>,
162 pub byte_count: u64,
164}
165
166#[derive(Clone, Debug)]
168pub struct RestoreResult {
169 pub snapshot_id: String,
171 pub restored_paths: Vec<String>,
173 pub skipped_paths_with_reasons: Vec<(String, String)>,
175}
176
177#[derive(Clone, Debug)]
179pub struct DropResult {
180 pub snapshot_id: String,
182 pub dropped: bool,
184}
185
186#[derive(Debug)]
187struct SessionSnapshots {
188 snapshots: Vec<SnapshotState>,
190 byte_count: u64,
194 byte_cap: u64,
197}
198
199impl Default for SessionSnapshots {
200 fn default() -> Self {
201 Self {
202 snapshots: Vec::new(),
203 byte_count: 0,
204 byte_cap: DEFAULT_SESSION_BYTE_CAP,
205 }
206 }
207}
208
209static SESSIONS: OnceLock<Mutex<BTreeMap<String, SessionSnapshots>>> = OnceLock::new();
210
211fn sessions() -> &'static Mutex<BTreeMap<String, SessionSnapshots>> {
212 SESSIONS.get_or_init(|| Mutex::new(BTreeMap::new()))
213}
214
215pub fn configure_session_byte_cap(session_id: &str, bytes: u64) -> u64 {
222 let mut guard = sessions()
223 .lock()
224 .expect("fs_snapshot session mutex poisoned");
225 let bundle = guard.entry(session_id.to_string()).or_default();
226 let previous = bundle.byte_cap;
227 bundle.byte_cap = bytes.max(1);
228 enforce_byte_cap(bundle, session_id);
229 previous
230}
231
232pub fn drop_session_snapshots(session_id: &str) -> usize {
239 let mut guard = sessions()
240 .lock()
241 .expect("fs_snapshot session mutex poisoned");
242 let Some(bundle) = guard.remove(session_id) else {
243 return 0;
244 };
245 let count = bundle.snapshots.len();
246 for snapshot in &bundle.snapshots {
247 remove_snapshot_dir(snapshot);
248 }
249 count
250}
251
252pub fn reset_all_sessions() -> usize {
261 let mut guard = sessions()
262 .lock()
263 .expect("fs_snapshot session mutex poisoned");
264 let session_count = guard.len();
265 for bundle in guard.values() {
266 for snapshot in &bundle.snapshots {
267 remove_snapshot_dir(snapshot);
268 }
269 }
270 guard.clear();
271 session_count
272}
273
274#[cfg(test)]
276pub fn session_count() -> usize {
277 sessions()
278 .lock()
279 .expect("fs_snapshot session mutex poisoned")
280 .len()
281}
282
283pub fn snapshot(
287 session_id: &str,
288 scope_id: &str,
289 paths: &[String],
290 root: Option<&Path>,
291) -> Result<SnapshotResult, HostlibError> {
292 validate_session_id(SNAPSHOT_BUILTIN, session_id)?;
293 validate_scope_id(SNAPSHOT_BUILTIN, scope_id)?;
294 let root = resolve_root(root);
295 let mut guard = sessions()
296 .lock()
297 .expect("fs_snapshot session mutex poisoned");
298 let bundle = guard.entry(session_id.to_string()).or_default();
299 upsert_snapshot(bundle, session_id, scope_id, &root)?;
300 let mut captured_paths = Vec::new();
301 let mut byte_count = 0u64;
302 for raw in paths {
303 let path = normalize_logical(Path::new(raw));
304 let added =
305 capture_path(bundle, session_id, scope_id, &path, &root).map_err(|message| {
306 HostlibError::Backend {
307 builtin: SNAPSHOT_BUILTIN,
308 message,
309 }
310 })?;
311 if let Some(bytes) = added {
312 byte_count = byte_count.saturating_add(bytes);
313 captured_paths.push(path.to_string_lossy().into_owned());
314 }
315 }
316 enforce_byte_cap(bundle, session_id);
317 let state = bundle
318 .snapshots
319 .iter()
320 .find(|snap| snap.snapshot_id == scope_id)
321 .expect("snapshot just upserted");
322 persist_manifest(state).map_err(|err| HostlibError::Backend {
323 builtin: SNAPSHOT_BUILTIN,
324 message: err,
325 })?;
326 Ok(SnapshotResult {
327 snapshot_id: state.snapshot_id.clone(),
328 captured_paths,
329 byte_count,
330 })
331}
332
333pub fn restore(
335 session_id: &str,
336 snapshot_id: &str,
337 paths: &[String],
338) -> Result<RestoreResult, HostlibError> {
339 validate_session_id(RESTORE_BUILTIN, session_id)?;
340 validate_scope_id(RESTORE_BUILTIN, snapshot_id)?;
341 let mut guard = sessions()
342 .lock()
343 .expect("fs_snapshot session mutex poisoned");
344 let bundle = guard
345 .get_mut(session_id)
346 .ok_or_else(|| HostlibError::Backend {
347 builtin: RESTORE_BUILTIN,
348 message: format!("no snapshots registered for session `{session_id}`"),
349 })?;
350 let state = bundle
351 .snapshots
352 .iter()
353 .find(|snap| snap.snapshot_id == snapshot_id)
354 .cloned()
355 .ok_or_else(|| HostlibError::Backend {
356 builtin: RESTORE_BUILTIN,
357 message: format!("unknown snapshot `{snapshot_id}` for session `{session_id}`"),
358 })?;
359 let selected = select_paths(&state, paths);
360 let mut restored_paths = Vec::new();
361 let mut skipped_paths_with_reasons = Vec::new();
362 for path in selected {
363 let Some(entry) = state.entries.get(&path) else {
364 continue;
365 };
366 let label = path.to_string_lossy().into_owned();
367 match restore_entry(&state, &path, entry) {
368 Ok(()) => restored_paths.push(label),
369 Err(reason) => skipped_paths_with_reasons.push((label, reason)),
370 }
371 }
372 Ok(RestoreResult {
373 snapshot_id: snapshot_id.to_string(),
374 restored_paths,
375 skipped_paths_with_reasons,
376 })
377}
378
379pub fn list_snapshots(session_id: &str) -> Result<Vec<SnapshotSummary>, HostlibError> {
381 validate_session_id(LIST_BUILTIN, session_id)?;
382 let guard = sessions()
383 .lock()
384 .expect("fs_snapshot session mutex poisoned");
385 let Some(bundle) = guard.get(session_id) else {
386 return Ok(Vec::new());
387 };
388 let mut summaries: Vec<SnapshotSummary> = bundle
389 .snapshots
390 .iter()
391 .map(|state| SnapshotSummary {
392 snapshot_id: state.snapshot_id.clone(),
393 scope_id: state.scope_id.clone(),
394 taken_at_ms: state.taken_at_ms,
395 captured_paths: state
396 .entries
397 .keys()
398 .map(|path| path.to_string_lossy().into_owned())
399 .collect(),
400 byte_count: entry_byte_count(state),
401 })
402 .collect();
403 summaries.sort_by_key(|summary| summary.taken_at_ms);
404 Ok(summaries)
405}
406
407pub fn drop_snapshot(session_id: &str, snapshot_id: &str) -> Result<DropResult, HostlibError> {
409 validate_session_id(DROP_BUILTIN, session_id)?;
410 validate_scope_id(DROP_BUILTIN, snapshot_id)?;
411 let mut guard = sessions()
412 .lock()
413 .expect("fs_snapshot session mutex poisoned");
414 let Some(bundle) = guard.get_mut(session_id) else {
415 return Ok(DropResult {
416 snapshot_id: snapshot_id.to_string(),
417 dropped: false,
418 });
419 };
420 let position = bundle
421 .snapshots
422 .iter()
423 .position(|snap| snap.snapshot_id == snapshot_id);
424 let dropped = match position {
425 Some(idx) => {
426 let removed = bundle.snapshots.remove(idx);
427 bundle.byte_count = bundle.byte_count.saturating_sub(entry_byte_count(&removed));
428 remove_snapshot_dir(&removed);
429 true
430 }
431 None => false,
432 };
433 Ok(DropResult {
434 snapshot_id: snapshot_id.to_string(),
435 dropped,
436 })
437}
438
439pub(crate) fn auto_capture_for_write(builtin: &'static str, path: &Path) {
448 let Some(session_id) = active_session_id() else {
449 return;
450 };
451 let Some(snapshot_id) = harn_vm::agent_sessions::current_tool_call_id() else {
452 return;
453 };
454 let mut guard = sessions()
455 .lock()
456 .expect("fs_snapshot session mutex poisoned");
457 let Some(bundle) = guard.get_mut(&session_id) else {
458 return;
459 };
460 let Some(snapshot) = bundle
461 .snapshots
462 .iter()
463 .find(|snap| snap.snapshot_id == snapshot_id)
464 else {
465 return;
466 };
467 let scope_id = snapshot.scope_id.clone();
468 let root = snapshot.root.clone();
469 let key = normalize_logical(path);
470 match capture_path(bundle, &session_id, &snapshot_id, &key, &root) {
471 Ok(_added) => {
472 if let Some(state) = bundle
473 .snapshots
474 .iter()
475 .find(|snap| snap.snapshot_id == snapshot_id)
476 {
477 if let Err(err) = persist_manifest(state) {
478 tracing::warn!(
479 "fs_snapshot: failed to persist manifest for snapshot {snapshot_id} in session {session_id} (scope_id={scope_id}, builtin={builtin}): {err}"
480 );
481 }
482 }
483 }
484 Err(err) => {
485 tracing::warn!(
486 "fs_snapshot: failed to auto-capture `{}` for snapshot {snapshot_id} in session {session_id} (scope_id={scope_id}, builtin={builtin}): {err}",
487 key.display()
488 );
489 }
490 }
491 enforce_byte_cap(bundle, &session_id);
492}
493
494fn snapshot_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
495 let raw = dict_arg(SNAPSHOT_BUILTIN, args)?;
496 let dict = raw.as_ref();
497 let session_id = require_string(SNAPSHOT_BUILTIN, dict, "session_id")?;
498 let scope_id = require_string(SNAPSHOT_BUILTIN, dict, "scope_id")?;
499 let paths = optional_string_list(SNAPSHOT_BUILTIN, dict, "paths")?;
500 let root = optional_string(SNAPSHOT_BUILTIN, dict, "root")?.map(PathBuf::from);
501 let result = snapshot(&session_id, &scope_id, &paths, root.as_deref())?;
502 Ok(build_dict([
503 ("snapshot_id", str_value(&result.snapshot_id)),
504 (
505 "captured_paths",
506 VmValue::List(Rc::new(
507 result
508 .captured_paths
509 .into_iter()
510 .map(|path| VmValue::String(Rc::from(path)))
511 .collect(),
512 )),
513 ),
514 ("byte_count", VmValue::Int(result.byte_count as i64)),
515 ]))
516}
517
518fn restore_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
519 let raw = dict_arg(RESTORE_BUILTIN, args)?;
520 let dict = raw.as_ref();
521 let session_id = require_string(RESTORE_BUILTIN, dict, "session_id")?;
522 let snapshot_id = require_string(RESTORE_BUILTIN, dict, "snapshot_id")?;
523 let paths = optional_string_list(RESTORE_BUILTIN, dict, "paths")?;
524 let result = restore(&session_id, &snapshot_id, &paths)?;
525 Ok(build_dict([
526 ("snapshot_id", str_value(&result.snapshot_id)),
527 (
528 "restored_paths",
529 VmValue::List(Rc::new(
530 result
531 .restored_paths
532 .into_iter()
533 .map(|path| VmValue::String(Rc::from(path)))
534 .collect(),
535 )),
536 ),
537 (
538 "skipped_paths_with_reasons",
539 VmValue::List(Rc::new(
540 result
541 .skipped_paths_with_reasons
542 .into_iter()
543 .map(|(path, reason)| {
544 build_dict([("path", str_value(&path)), ("reason", str_value(&reason))])
545 })
546 .collect(),
547 )),
548 ),
549 ]))
550}
551
552fn list_snapshots_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
553 let raw = dict_arg(LIST_BUILTIN, args)?;
554 let dict = raw.as_ref();
555 let session_id = require_string(LIST_BUILTIN, dict, "session_id")?;
556 let summaries = list_snapshots(&session_id)?;
557 Ok(build_dict([(
558 "snapshots",
559 VmValue::List(Rc::new(
560 summaries.into_iter().map(snapshot_summary_value).collect(),
561 )),
562 )]))
563}
564
565fn drop_snapshot_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
566 let raw = dict_arg(DROP_BUILTIN, args)?;
567 let dict = raw.as_ref();
568 let session_id = require_string(DROP_BUILTIN, dict, "session_id")?;
569 let snapshot_id = require_string(DROP_BUILTIN, dict, "snapshot_id")?;
570 let result = drop_snapshot(&session_id, &snapshot_id)?;
571 Ok(build_dict([
572 ("snapshot_id", str_value(&result.snapshot_id)),
573 ("dropped", VmValue::Bool(result.dropped)),
574 ]))
575}
576
577fn snapshot_summary_value(summary: SnapshotSummary) -> VmValue {
578 build_dict([
579 ("snapshot_id", str_value(&summary.snapshot_id)),
580 ("scope_id", str_value(&summary.scope_id)),
581 ("taken_at_ms", VmValue::Int(summary.taken_at_ms)),
582 (
583 "captured_paths",
584 VmValue::List(Rc::new(
585 summary
586 .captured_paths
587 .into_iter()
588 .map(|path| VmValue::String(Rc::from(path)))
589 .collect(),
590 )),
591 ),
592 ("byte_count", VmValue::Int(summary.byte_count as i64)),
593 ])
594}
595
596fn upsert_snapshot(
597 bundle: &mut SessionSnapshots,
598 session_id: &str,
599 scope_id: &str,
600 root: &Path,
601) -> Result<(), HostlibError> {
602 if bundle
603 .snapshots
604 .iter()
605 .any(|snap| snap.snapshot_id == scope_id)
606 {
607 return Ok(());
608 }
609 let state = SnapshotState {
610 snapshot_id: scope_id.to_string(),
611 scope_id: scope_id.to_string(),
612 session_id: session_id.to_string(),
613 root: root.to_path_buf(),
614 taken_at_ms: now_ms(),
615 entries: BTreeMap::new(),
616 };
617 let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
618 stdfs::create_dir_all(dir.join("bodies")).map_err(|err| HostlibError::Backend {
619 builtin: SNAPSHOT_BUILTIN,
620 message: format!("mkdir {}: {err}", dir.display()),
621 })?;
622 bundle.snapshots.push(state);
623 Ok(())
624}
625
626fn capture_path(
627 bundle: &mut SessionSnapshots,
628 session_id: &str,
629 snapshot_id: &str,
630 path: &Path,
631 root: &Path,
632) -> Result<Option<u64>, String> {
633 let snap_index = bundle
634 .snapshots
635 .iter()
636 .position(|snap| snap.snapshot_id == snapshot_id)
637 .ok_or_else(|| format!("snapshot `{snapshot_id}` is not registered"))?;
638 if bundle.snapshots[snap_index].entries.contains_key(path) {
639 return Ok(None);
640 }
641 let metadata = stdfs::symlink_metadata(path);
642 let (entry, byte_count) = match metadata {
643 Err(err) if err.kind() == std::io::ErrorKind::NotFound => (SnapshotEntry::Absent, 0u64),
644 Err(err) => {
645 return Err(format!("stat `{}`: {err}", path.display()));
646 }
647 Ok(metadata) if metadata.is_dir() => {
648 return Err(format!(
649 "snapshot of directory `{}` is not supported yet",
650 path.display()
651 ));
652 }
653 Ok(metadata) if metadata.file_type().is_symlink() => {
654 return Err(format!(
655 "snapshot of symlink `{}` is not supported yet",
656 path.display()
657 ));
658 }
659 Ok(metadata) => {
660 let bytes = stdfs::read(path)
661 .map_err(|err| format!("read `{}` for snapshot: {err}", path.display()))?;
662 let body_hash = hex::encode(Sha256::digest(&bytes));
663 let len = bytes.len() as u64;
664 store_body(root, session_id, snapshot_id, &body_hash, &bytes)?;
665 #[cfg(unix)]
666 let mode = {
667 use std::os::unix::fs::MetadataExt;
668 Some(metadata.mode())
669 };
670 #[cfg(not(unix))]
671 let mode = {
672 let _ = &metadata;
673 None
674 };
675 (
676 SnapshotEntry::File {
677 body_hash,
678 len,
679 mode,
680 },
681 len,
682 )
683 }
684 };
685 let snap = &mut bundle.snapshots[snap_index];
686 snap.entries.insert(path.to_path_buf(), entry);
687 bundle.byte_count = bundle.byte_count.saturating_add(byte_count);
688 Ok(Some(byte_count))
689}
690
691fn store_body(
692 root: &Path,
693 session_id: &str,
694 snapshot_id: &str,
695 body_hash: &str,
696 bytes: &[u8],
697) -> Result<(), String> {
698 let bodies = snapshot_dir(root, session_id, snapshot_id).join("bodies");
699 stdfs::create_dir_all(&bodies).map_err(|err| format!("mkdir {}: {err}", bodies.display()))?;
700 let body_path = bodies.join(body_hash);
701 if !body_path.exists() {
702 atomic_write(&body_path, bytes)?;
703 }
704 Ok(())
705}
706
707fn restore_entry(state: &SnapshotState, path: &Path, entry: &SnapshotEntry) -> Result<(), String> {
708 match entry {
709 SnapshotEntry::Absent => match stdfs::symlink_metadata(path) {
710 Ok(metadata) if metadata.is_dir() => stdfs::remove_dir_all(path)
711 .map_err(|err| format!("remove_dir_all {}: {err}", path.display())),
712 Ok(_) => stdfs::remove_file(path)
713 .map_err(|err| format!("remove_file {}: {err}", path.display())),
714 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
715 Err(err) => Err(format!("stat {}: {err}", path.display())),
716 },
717 SnapshotEntry::File {
718 body_hash, mode, ..
719 } => {
720 let body_path = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id)
721 .join("bodies")
722 .join(body_hash);
723 let bytes = stdfs::read(&body_path)
724 .map_err(|err| format!("read snapshot body `{}`: {err}", body_path.display()))?;
725 atomic_write(path, &bytes)?;
726 #[cfg(unix)]
727 if let Some(bits) = mode {
728 use std::os::unix::fs::PermissionsExt;
729 let permissions = stdfs::Permissions::from_mode(*bits);
730 stdfs::set_permissions(path, permissions)
731 .map_err(|err| format!("set_permissions `{}`: {err}", path.display()))?;
732 }
733 #[cfg(not(unix))]
734 let _ = mode;
735 Ok(())
736 }
737 }
738}
739
740fn persist_manifest(state: &SnapshotState) -> Result<(), String> {
741 let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
742 stdfs::create_dir_all(&dir).map_err(|err| format!("mkdir {}: {err}", dir.display()))?;
743 let manifest = Manifest {
744 version: MANIFEST_VERSION,
745 snapshot_id: state.snapshot_id.clone(),
746 scope_id: state.scope_id.clone(),
747 session_id: state.session_id.clone(),
748 root: state.root.to_string_lossy().into_owned(),
749 taken_at_ms: state.taken_at_ms,
750 entries: state
751 .entries
752 .iter()
753 .map(|(path, entry)| (path.to_string_lossy().into_owned(), entry.clone()))
754 .collect(),
755 };
756 let bytes = serde_json::to_vec_pretty(&manifest)
757 .map_err(|err| format!("serialize snapshot manifest: {err}"))?;
758 atomic_write(&dir.join("manifest.json"), &bytes)
759}
760
761fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
762 if let Some(parent) = path.parent() {
763 stdfs::create_dir_all(parent)
764 .map_err(|err| format!("mkdir {}: {err}", parent.display()))?;
765 }
766 let tmp = path.with_extension(format!("tmp-{}-{}", std::process::id(), now_ms()));
767 stdfs::write(&tmp, bytes).map_err(|err| format!("write {}: {err}", tmp.display()))?;
768 match stdfs::rename(&tmp, path) {
769 Ok(()) => Ok(()),
770 Err(rename_err) => {
771 let _ = stdfs::remove_file(path);
772 stdfs::rename(&tmp, path).map_err(|retry| {
773 format!(
774 "rename {} to {}: {rename_err}; retry: {retry}",
775 tmp.display(),
776 path.display()
777 )
778 })
779 }
780 }
781}
782
783fn enforce_byte_cap(bundle: &mut SessionSnapshots, session_id: &str) {
784 while bundle.byte_count > bundle.byte_cap && !bundle.snapshots.is_empty() {
785 let evicted = bundle.snapshots.remove(0);
786 bundle.byte_count = bundle.byte_count.saturating_sub(entry_byte_count(&evicted));
787 tracing::info!(
788 "fs_snapshot: evicting snapshot `{}` from session `{session_id}` (over byte cap {})",
789 evicted.snapshot_id,
790 bundle.byte_cap,
791 );
792 remove_snapshot_dir(&evicted);
793 }
794}
795
796fn remove_snapshot_dir(state: &SnapshotState) {
797 let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
798 let _ = stdfs::remove_dir_all(&dir);
799}
800
801fn entry_byte_count(state: &SnapshotState) -> u64 {
802 state
803 .entries
804 .values()
805 .map(|entry| match entry {
806 SnapshotEntry::File { len, .. } => *len,
807 SnapshotEntry::Absent => 0,
808 })
809 .sum()
810}
811
812fn select_paths(state: &SnapshotState, paths: &[String]) -> Vec<PathBuf> {
813 if paths.is_empty() {
814 return state.entries.keys().cloned().collect();
815 }
816 let requested: BTreeSet<PathBuf> = paths
817 .iter()
818 .map(|path| normalize_logical(Path::new(path)))
819 .collect();
820 state
821 .entries
822 .keys()
823 .filter(|path| requested.contains(*path))
824 .cloned()
825 .collect()
826}
827
828fn validate_session_id(builtin: &'static str, session_id: &str) -> Result<(), HostlibError> {
829 if session_id.trim().is_empty() {
830 return Err(HostlibError::InvalidParameter {
831 builtin,
832 param: "session_id",
833 message: "must not be empty".to_string(),
834 });
835 }
836 Ok(())
837}
838
839fn validate_scope_id(builtin: &'static str, scope_id: &str) -> Result<(), HostlibError> {
840 if scope_id.trim().is_empty() {
841 let param = match builtin {
842 SNAPSHOT_BUILTIN => "scope_id",
843 _ => "snapshot_id",
844 };
845 return Err(HostlibError::InvalidParameter {
846 builtin,
847 param,
848 message: "must not be empty".to_string(),
849 });
850 }
851 Ok(())
852}
853
854fn active_session_id() -> Option<String> {
855 harn_vm::agent_sessions::current_session_id().filter(|id| !id.trim().is_empty())
856}
857
858fn resolve_root(root: Option<&Path>) -> PathBuf {
859 match root {
860 Some(path) => normalize_logical(path),
861 None => normalize_logical(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))),
862 }
863}
864
865fn snapshot_dir(root: &Path, session_id: &str, snapshot_id: &str) -> PathBuf {
866 let mut dir = root.to_path_buf();
867 for component in STATE_REL {
868 dir.push(component);
869 }
870 dir.push(sanitize_component(session_id));
871 dir.push(sanitize_component(snapshot_id));
872 dir
873}
874
875fn sanitize_component(input: &str) -> String {
876 let sanitized: String = input
877 .chars()
878 .map(|ch| match ch {
879 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => ch,
880 _ => '_',
881 })
882 .collect();
883 if sanitized == input {
884 sanitized
885 } else {
886 let hash = hex::encode(Sha256::digest(input.as_bytes()));
887 format!("{sanitized}-{}", &hash[..12])
888 }
889}
890
891fn normalize_logical(path: &Path) -> PathBuf {
892 let absolute = if path.is_absolute() {
893 path.to_path_buf()
894 } else {
895 std::env::current_dir()
896 .unwrap_or_else(|_| PathBuf::from("."))
897 .join(path)
898 };
899 let mut out = PathBuf::new();
900 for component in absolute.components() {
901 match component {
902 Component::ParentDir => {
903 out.pop();
904 }
905 Component::CurDir => {}
906 other => out.push(other),
907 }
908 }
909 out
910}
911
912fn now_ms() -> i64 {
913 std::time::SystemTime::now()
914 .duration_since(std::time::UNIX_EPOCH)
915 .map(|duration| duration.as_millis() as i64)
916 .unwrap_or(0)
917}
918
919#[cfg(test)]
920mod tests {
921 use super::*;
922 use std::sync::atomic::{AtomicU64, Ordering};
923 use tempfile::TempDir;
924
925 fn unique_session(prefix: &str) -> String {
929 static COUNTER: AtomicU64 = AtomicU64::new(0);
930 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
931 format!("{prefix}-{n}-{}", std::process::id())
932 }
933
934 fn unique_scope() -> String {
935 static COUNTER: AtomicU64 = AtomicU64::new(0);
936 format!("tc-{}", COUNTER.fetch_add(1, Ordering::Relaxed))
937 }
938
939 fn enter_session(id: &str) -> harn_vm::agent_sessions::CurrentSessionGuard {
940 harn_vm::agent_sessions::open_or_create(Some(id.to_string()));
941 harn_vm::agent_sessions::enter_current_session(id.to_string())
942 }
943
944 #[test]
945 fn explicit_snapshot_then_restore_round_trips_file_bytes() {
946 let dir = TempDir::new().unwrap();
947 let file = dir.path().join("note.txt");
948 stdfs::write(&file, b"v1").unwrap();
949 let session = unique_session("snap-roundtrip");
950 let scope = unique_scope();
951 let _session_guard = enter_session(&session);
952
953 let result = snapshot(
954 &session,
955 &scope,
956 &[file.to_string_lossy().into_owned()],
957 Some(dir.path()),
958 )
959 .unwrap();
960 assert_eq!(result.snapshot_id, scope);
961 assert_eq!(result.captured_paths.len(), 1);
962 assert_eq!(result.byte_count, 2);
963
964 stdfs::write(&file, b"clobbered").unwrap();
965 let restored = restore(&session, &scope, &[]).unwrap();
966 assert_eq!(restored.restored_paths.len(), 1);
967 assert!(restored.skipped_paths_with_reasons.is_empty());
968 assert_eq!(stdfs::read(&file).unwrap(), b"v1");
969 }
970
971 #[test]
972 fn restore_reinstates_deleted_file() {
973 let dir = TempDir::new().unwrap();
974 let file = dir.path().join("doomed.txt");
975 stdfs::write(&file, b"alive").unwrap();
976 let session = unique_session("snap-reinstate");
977 let scope = unique_scope();
978 let _session_guard = enter_session(&session);
979
980 snapshot(
981 &session,
982 &scope,
983 &[file.to_string_lossy().into_owned()],
984 Some(dir.path()),
985 )
986 .unwrap();
987 stdfs::remove_file(&file).unwrap();
988 assert!(!file.exists());
989 let restored = restore(&session, &scope, &[]).unwrap();
990 assert_eq!(restored.restored_paths.len(), 1);
991 assert_eq!(stdfs::read(&file).unwrap(), b"alive");
992 }
993
994 #[test]
995 fn absent_snapshot_means_restore_deletes_paths_created_during_the_call() {
996 let dir = TempDir::new().unwrap();
997 let file = dir.path().join("new.txt");
998 assert!(!file.exists());
999 let session = unique_session("snap-absent");
1000 let scope = unique_scope();
1001 let _session_guard = enter_session(&session);
1002
1003 snapshot(
1004 &session,
1005 &scope,
1006 &[file.to_string_lossy().into_owned()],
1007 Some(dir.path()),
1008 )
1009 .unwrap();
1010 stdfs::write(&file, b"created during call").unwrap();
1011 let restored = restore(&session, &scope, &[]).unwrap();
1012 assert_eq!(restored.restored_paths.len(), 1);
1013 assert!(
1014 !file.exists(),
1015 "restore must delete files that the snapshot saw as absent"
1016 );
1017 }
1018
1019 #[test]
1020 fn list_and_drop_round_trip_through_metadata() {
1021 let dir = TempDir::new().unwrap();
1022 let file = dir.path().join("listed.txt");
1023 stdfs::write(&file, b"abc").unwrap();
1024 let session = unique_session("snap-list");
1025 let scope = unique_scope();
1026 let _session_guard = enter_session(&session);
1027
1028 snapshot(
1029 &session,
1030 &scope,
1031 &[file.to_string_lossy().into_owned()],
1032 Some(dir.path()),
1033 )
1034 .unwrap();
1035 let summaries = list_snapshots(&session).unwrap();
1036 assert_eq!(summaries.len(), 1);
1037 assert_eq!(summaries[0].snapshot_id, scope);
1038 assert_eq!(summaries[0].byte_count, 3);
1039
1040 let dropped = drop_snapshot(&session, &scope).unwrap();
1041 assert!(dropped.dropped);
1042 assert!(list_snapshots(&session).unwrap().is_empty());
1043
1044 let again = drop_snapshot(&session, &scope).unwrap();
1045 assert!(!again.dropped, "second drop must be idempotent");
1046 }
1047
1048 #[test]
1049 fn auto_capture_records_pre_image_keyed_by_current_tool_call_id() {
1050 let dir = TempDir::new().unwrap();
1051 let file = dir.path().join("auto.txt");
1052 stdfs::write(&file, b"pre").unwrap();
1053 let session = unique_session("snap-auto");
1054 let scope = unique_scope();
1055 let _session_guard = enter_session(&session);
1056 let _tool_guard = harn_vm::agent_sessions::enter_current_tool_call(scope.clone());
1057
1058 snapshot(&session, &scope, &[], Some(dir.path())).unwrap();
1059 auto_capture_for_write("hostlib_tools_write_file", &file);
1060 stdfs::write(&file, b"post").unwrap();
1061
1062 let restored = restore(&session, &scope, &[]).unwrap();
1063 assert_eq!(restored.restored_paths.len(), 1);
1064 assert_eq!(stdfs::read(&file).unwrap(), b"pre");
1065 }
1066
1067 #[test]
1068 fn byte_cap_evicts_oldest_snapshot_when_exceeded() {
1069 let dir = TempDir::new().unwrap();
1070 let session = unique_session("snap-evict");
1071 let _session_guard = enter_session(&session);
1072
1073 configure_session_byte_cap(&session, 8);
1076
1077 let mk = |name: &str| {
1078 let path = dir.path().join(name);
1079 stdfs::write(&path, b"12345").unwrap();
1080 path
1081 };
1082
1083 let scope_a = unique_scope();
1084 let scope_b = unique_scope();
1085 let a = mk("a.txt");
1086 snapshot(
1087 &session,
1088 &scope_a,
1089 &[a.to_string_lossy().into_owned()],
1090 Some(dir.path()),
1091 )
1092 .unwrap();
1093 let b = mk("b.txt");
1094 snapshot(
1095 &session,
1096 &scope_b,
1097 &[b.to_string_lossy().into_owned()],
1098 Some(dir.path()),
1099 )
1100 .unwrap();
1101
1102 let ids: Vec<String> = list_snapshots(&session)
1103 .unwrap()
1104 .into_iter()
1105 .map(|summary| summary.snapshot_id)
1106 .collect();
1107 assert_eq!(
1108 ids,
1109 vec![scope_b],
1110 "older snapshot must be evicted when the per-session byte cap is exceeded"
1111 );
1112 }
1113
1114 #[test]
1115 fn drop_session_snapshots_removes_every_snapshot_for_a_session() {
1116 let dir = TempDir::new().unwrap();
1117 let file = dir.path().join("retained.txt");
1118 stdfs::write(&file, b"x").unwrap();
1119 let session = unique_session("snap-drop-session");
1120 let scope_a = unique_scope();
1121 let scope_b = unique_scope();
1122 let _session_guard = enter_session(&session);
1123
1124 snapshot(
1125 &session,
1126 &scope_a,
1127 &[file.to_string_lossy().into_owned()],
1128 Some(dir.path()),
1129 )
1130 .unwrap();
1131 snapshot(
1132 &session,
1133 &scope_b,
1134 &[file.to_string_lossy().into_owned()],
1135 Some(dir.path()),
1136 )
1137 .unwrap();
1138 assert_eq!(list_snapshots(&session).unwrap().len(), 2);
1139
1140 assert_eq!(drop_session_snapshots(&session), 2);
1141 assert!(list_snapshots(&session).unwrap().is_empty());
1142 assert_eq!(drop_session_snapshots(&session), 0, "idempotent");
1143 }
1144}