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