1use std::collections::{BTreeMap, BTreeSet};
33use std::fs as stdfs;
34use std::path::{Component, Path, PathBuf};
35use std::sync::Arc;
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, None);
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, Some(scope_id));
317 let state = bundle
318 .snapshots
319 .iter()
320 .find(|snap| snap.snapshot_id == scope_id)
321 .expect("snapshot just upserted is protected from byte-cap eviction");
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, Some(&snapshot_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(Arc::new(
507 result
508 .captured_paths
509 .into_iter()
510 .map(|path| VmValue::String(Arc::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(Arc::new(
530 result
531 .restored_paths
532 .into_iter()
533 .map(|path| VmValue::String(Arc::from(path)))
534 .collect(),
535 )),
536 ),
537 (
538 "skipped_paths_with_reasons",
539 VmValue::List(Arc::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(Arc::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(Arc::new(
585 summary
586 .captured_paths
587 .into_iter()
588 .map(|path| VmValue::String(Arc::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 let _ = stdfs::remove_file(&tmp);
776 format!(
777 "rename {} to {}: {rename_err}; retry: {retry}",
778 tmp.display(),
779 path.display()
780 )
781 })
782 }
783 }
784}
785
786fn enforce_byte_cap(bundle: &mut SessionSnapshots, session_id: &str, protected: Option<&str>) {
794 while bundle.byte_count > bundle.byte_cap {
795 let Some(idx) = bundle
796 .snapshots
797 .iter()
798 .position(|snap| Some(snap.snapshot_id.as_str()) != protected)
799 else {
800 break;
801 };
802 let evicted = bundle.snapshots.remove(idx);
803 bundle.byte_count = bundle.byte_count.saturating_sub(entry_byte_count(&evicted));
804 tracing::info!(
805 "fs_snapshot: evicting snapshot `{}` from session `{session_id}` (over byte cap {})",
806 evicted.snapshot_id,
807 bundle.byte_cap,
808 );
809 remove_snapshot_dir(&evicted);
810 }
811}
812
813fn remove_snapshot_dir(state: &SnapshotState) {
814 let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
815 let _ = stdfs::remove_dir_all(&dir);
816}
817
818fn entry_byte_count(state: &SnapshotState) -> u64 {
819 state
820 .entries
821 .values()
822 .map(|entry| match entry {
823 SnapshotEntry::File { len, .. } => *len,
824 SnapshotEntry::Absent => 0,
825 })
826 .sum()
827}
828
829fn select_paths(state: &SnapshotState, paths: &[String]) -> Vec<PathBuf> {
830 if paths.is_empty() {
831 return state.entries.keys().cloned().collect();
832 }
833 let requested: BTreeSet<PathBuf> = paths
834 .iter()
835 .map(|path| normalize_logical(Path::new(path)))
836 .collect();
837 state
838 .entries
839 .keys()
840 .filter(|path| requested.contains(*path))
841 .cloned()
842 .collect()
843}
844
845fn validate_session_id(builtin: &'static str, session_id: &str) -> Result<(), HostlibError> {
846 if session_id.trim().is_empty() {
847 return Err(HostlibError::InvalidParameter {
848 builtin,
849 param: "session_id",
850 message: "must not be empty".to_string(),
851 });
852 }
853 Ok(())
854}
855
856fn validate_scope_id(builtin: &'static str, scope_id: &str) -> Result<(), HostlibError> {
857 if scope_id.trim().is_empty() {
858 let param = match builtin {
859 SNAPSHOT_BUILTIN => "scope_id",
860 _ => "snapshot_id",
861 };
862 return Err(HostlibError::InvalidParameter {
863 builtin,
864 param,
865 message: "must not be empty".to_string(),
866 });
867 }
868 Ok(())
869}
870
871fn active_session_id() -> Option<String> {
872 harn_vm::agent_sessions::current_session_id().filter(|id| !id.trim().is_empty())
873}
874
875fn resolve_root(root: Option<&Path>) -> PathBuf {
876 match root {
877 Some(path) => normalize_logical(path),
878 None => normalize_logical(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))),
879 }
880}
881
882fn snapshot_dir(root: &Path, session_id: &str, snapshot_id: &str) -> PathBuf {
883 let mut dir = root.to_path_buf();
884 for component in STATE_REL {
885 dir.push(component);
886 }
887 dir.push(sanitize_component(session_id));
888 dir.push(sanitize_component(snapshot_id));
889 dir
890}
891
892fn sanitize_component(input: &str) -> String {
893 let sanitized: String = input
894 .chars()
895 .map(|ch| match ch {
896 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => ch,
897 _ => '_',
898 })
899 .collect();
900 if sanitized == input {
901 sanitized
902 } else {
903 let hash = hex::encode(Sha256::digest(input.as_bytes()));
904 format!("{sanitized}-{}", &hash[..12])
905 }
906}
907
908fn normalize_logical(path: &Path) -> PathBuf {
909 let absolute = if path.is_absolute() {
910 path.to_path_buf()
911 } else {
912 std::env::current_dir()
913 .unwrap_or_else(|_| PathBuf::from("."))
914 .join(path)
915 };
916 let mut out = PathBuf::new();
917 for component in absolute.components() {
918 match component {
919 Component::ParentDir => {
920 out.pop();
921 }
922 Component::CurDir => {}
923 other => out.push(other),
924 }
925 }
926 out
927}
928
929fn now_ms() -> i64 {
930 std::time::SystemTime::now()
931 .duration_since(std::time::UNIX_EPOCH)
932 .map(|duration| duration.as_millis() as i64)
933 .unwrap_or(0)
934}
935
936#[cfg(test)]
937mod tests {
938 use super::*;
939 use std::sync::atomic::{AtomicU64, Ordering};
940 use tempfile::TempDir;
941
942 fn unique_session(prefix: &str) -> String {
946 static COUNTER: AtomicU64 = AtomicU64::new(0);
947 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
948 format!("{prefix}-{n}-{}", std::process::id())
949 }
950
951 fn unique_scope() -> String {
952 static COUNTER: AtomicU64 = AtomicU64::new(0);
953 format!("tc-{}", COUNTER.fetch_add(1, Ordering::Relaxed))
954 }
955
956 fn enter_session(id: &str) -> harn_vm::agent_sessions::CurrentSessionGuard {
957 harn_vm::agent_sessions::open_or_create(Some(id.to_string()));
958 harn_vm::agent_sessions::enter_current_session(id.to_string())
959 }
960
961 #[test]
962 fn explicit_snapshot_then_restore_round_trips_file_bytes() {
963 let dir = TempDir::new().unwrap();
964 let file = dir.path().join("note.txt");
965 stdfs::write(&file, b"v1").unwrap();
966 let session = unique_session("snap-roundtrip");
967 let scope = unique_scope();
968 let _session_guard = enter_session(&session);
969
970 let result = snapshot(
971 &session,
972 &scope,
973 &[file.to_string_lossy().into_owned()],
974 Some(dir.path()),
975 )
976 .unwrap();
977 assert_eq!(result.snapshot_id, scope);
978 assert_eq!(result.captured_paths.len(), 1);
979 assert_eq!(result.byte_count, 2);
980
981 stdfs::write(&file, b"clobbered").unwrap();
982 let restored = restore(&session, &scope, &[]).unwrap();
983 assert_eq!(restored.restored_paths.len(), 1);
984 assert!(restored.skipped_paths_with_reasons.is_empty());
985 assert_eq!(stdfs::read(&file).unwrap(), b"v1");
986 }
987
988 #[test]
989 fn restore_reinstates_deleted_file() {
990 let dir = TempDir::new().unwrap();
991 let file = dir.path().join("doomed.txt");
992 stdfs::write(&file, b"alive").unwrap();
993 let session = unique_session("snap-reinstate");
994 let scope = unique_scope();
995 let _session_guard = enter_session(&session);
996
997 snapshot(
998 &session,
999 &scope,
1000 &[file.to_string_lossy().into_owned()],
1001 Some(dir.path()),
1002 )
1003 .unwrap();
1004 stdfs::remove_file(&file).unwrap();
1005 assert!(!file.exists());
1006 let restored = restore(&session, &scope, &[]).unwrap();
1007 assert_eq!(restored.restored_paths.len(), 1);
1008 assert_eq!(stdfs::read(&file).unwrap(), b"alive");
1009 }
1010
1011 #[test]
1012 fn absent_snapshot_means_restore_deletes_paths_created_during_the_call() {
1013 let dir = TempDir::new().unwrap();
1014 let file = dir.path().join("new.txt");
1015 assert!(!file.exists());
1016 let session = unique_session("snap-absent");
1017 let scope = unique_scope();
1018 let _session_guard = enter_session(&session);
1019
1020 snapshot(
1021 &session,
1022 &scope,
1023 &[file.to_string_lossy().into_owned()],
1024 Some(dir.path()),
1025 )
1026 .unwrap();
1027 stdfs::write(&file, b"created during call").unwrap();
1028 let restored = restore(&session, &scope, &[]).unwrap();
1029 assert_eq!(restored.restored_paths.len(), 1);
1030 assert!(
1031 !file.exists(),
1032 "restore must delete files that the snapshot saw as absent"
1033 );
1034 }
1035
1036 #[test]
1037 fn list_and_drop_round_trip_through_metadata() {
1038 let dir = TempDir::new().unwrap();
1039 let file = dir.path().join("listed.txt");
1040 stdfs::write(&file, b"abc").unwrap();
1041 let session = unique_session("snap-list");
1042 let scope = unique_scope();
1043 let _session_guard = enter_session(&session);
1044
1045 snapshot(
1046 &session,
1047 &scope,
1048 &[file.to_string_lossy().into_owned()],
1049 Some(dir.path()),
1050 )
1051 .unwrap();
1052 let summaries = list_snapshots(&session).unwrap();
1053 assert_eq!(summaries.len(), 1);
1054 assert_eq!(summaries[0].snapshot_id, scope);
1055 assert_eq!(summaries[0].byte_count, 3);
1056
1057 let dropped = drop_snapshot(&session, &scope).unwrap();
1058 assert!(dropped.dropped);
1059 assert!(list_snapshots(&session).unwrap().is_empty());
1060
1061 let again = drop_snapshot(&session, &scope).unwrap();
1062 assert!(!again.dropped, "second drop must be idempotent");
1063 }
1064
1065 #[test]
1066 fn auto_capture_records_pre_image_keyed_by_current_tool_call_id() {
1067 let dir = TempDir::new().unwrap();
1068 let file = dir.path().join("auto.txt");
1069 stdfs::write(&file, b"pre").unwrap();
1070 let session = unique_session("snap-auto");
1071 let scope = unique_scope();
1072 let _session_guard = enter_session(&session);
1073 let _tool_guard = harn_vm::agent_sessions::enter_current_tool_call(scope.clone());
1074
1075 snapshot(&session, &scope, &[], Some(dir.path())).unwrap();
1076 auto_capture_for_write("hostlib_tools_write_file", &file);
1077 stdfs::write(&file, b"post").unwrap();
1078
1079 let restored = restore(&session, &scope, &[]).unwrap();
1080 assert_eq!(restored.restored_paths.len(), 1);
1081 assert_eq!(stdfs::read(&file).unwrap(), b"pre");
1082 }
1083
1084 #[test]
1085 fn byte_cap_evicts_oldest_snapshot_when_exceeded() {
1086 let dir = TempDir::new().unwrap();
1087 let session = unique_session("snap-evict");
1088 let _session_guard = enter_session(&session);
1089
1090 configure_session_byte_cap(&session, 8);
1093
1094 let mk = |name: &str| {
1095 let path = dir.path().join(name);
1096 stdfs::write(&path, b"12345").unwrap();
1097 path
1098 };
1099
1100 let scope_a = unique_scope();
1101 let scope_b = unique_scope();
1102 let a = mk("a.txt");
1103 snapshot(
1104 &session,
1105 &scope_a,
1106 &[a.to_string_lossy().into_owned()],
1107 Some(dir.path()),
1108 )
1109 .unwrap();
1110 let b = mk("b.txt");
1111 snapshot(
1112 &session,
1113 &scope_b,
1114 &[b.to_string_lossy().into_owned()],
1115 Some(dir.path()),
1116 )
1117 .unwrap();
1118
1119 let ids: Vec<String> = list_snapshots(&session)
1120 .unwrap()
1121 .into_iter()
1122 .map(|summary| summary.snapshot_id)
1123 .collect();
1124 assert_eq!(
1125 ids,
1126 vec![scope_b],
1127 "older snapshot must be evicted when the per-session byte cap is exceeded"
1128 );
1129 }
1130
1131 #[test]
1132 fn snapshot_larger_than_cap_is_retained_not_evicted() {
1133 let dir = TempDir::new().unwrap();
1137 let session = unique_session("snap-oversized");
1138 let _session_guard = enter_session(&session);
1139 configure_session_byte_cap(&session, 4);
1140
1141 let scope = unique_scope();
1142 let file = dir.path().join("big.txt");
1143 stdfs::write(&file, b"0123456789").unwrap();
1144 let result = snapshot(
1145 &session,
1146 &scope,
1147 &[file.to_string_lossy().into_owned()],
1148 Some(dir.path()),
1149 )
1150 .unwrap();
1151 assert_eq!(result.byte_count, 10);
1152
1153 let ids: Vec<String> = list_snapshots(&session)
1154 .unwrap()
1155 .into_iter()
1156 .map(|summary| summary.snapshot_id)
1157 .collect();
1158 assert_eq!(
1159 ids,
1160 vec![scope],
1161 "an oversized snapshot must be retained rather than evicting itself"
1162 );
1163 }
1164
1165 #[test]
1166 fn drop_session_snapshots_removes_every_snapshot_for_a_session() {
1167 let dir = TempDir::new().unwrap();
1168 let file = dir.path().join("retained.txt");
1169 stdfs::write(&file, b"x").unwrap();
1170 let session = unique_session("snap-drop-session");
1171 let scope_a = unique_scope();
1172 let scope_b = unique_scope();
1173 let _session_guard = enter_session(&session);
1174
1175 snapshot(
1176 &session,
1177 &scope_a,
1178 &[file.to_string_lossy().into_owned()],
1179 Some(dir.path()),
1180 )
1181 .unwrap();
1182 snapshot(
1183 &session,
1184 &scope_b,
1185 &[file.to_string_lossy().into_owned()],
1186 Some(dir.path()),
1187 )
1188 .unwrap();
1189 assert_eq!(list_snapshots(&session).unwrap().len(), 2);
1190
1191 assert_eq!(drop_session_snapshots(&session), 2);
1192 assert!(list_snapshots(&session).unwrap().is_empty());
1193 assert_eq!(drop_session_snapshots(&session), 0, "idempotent");
1194 }
1195}