Skip to main content

adk_harness/snapshot/
mod.rs

1//! Snapshots and rewind (spec 3.1 §7.27, amending spec 3.3 §7.10; invariant I68).
2//!
3//! Before each user turn, before each plan-graph step, before a `Destructive` call and
4//! before a rewind, the harness snapshots the whole tree under the workspace root, so what a
5//! command wrote is covered like what a file tool wrote. A rewind restores files, the
6//! transcript and the plan from one of those snapshots, and `/redo` restores the snapshot
7//! taken before the rewind.
8//!
9//! | Item | Role |
10//! |---|---|
11//! | [`SnapshotConfig`] | `keep_turns` (50), `max_bytes` (2 GiB per workspace), `max_files` (50,000), `max_file_bytes` (8 MiB), `skip_dirs` |
12//! | [`walk`], [`WalkOptions`] | The breadth-first walker ultracode shares: `.gitignore` and `Workspace::exclude_globs` honoured, `.git` never opened, build directories skipped |
13//! | [`Snapshots`] | The stat cache (size, mtime, inode), the object store, the record store, retention and garbage collection; [`Snapshots::take`] is "snapshot now" |
14//! | [`SnapshotObjects`]: [`FileSnapshotObjects`], [`InMemorySnapshotObjects`] | Content-addressed objects, beside `harness.db`, sealed under the store key when one is configured |
15//! | [`SnapshotStore`]: [`InMemorySnapshotStore`], `SqliteSnapshotStore` (feature `sqlite`) | One record per snapshot |
16//! | [`RewindTarget`], [`RewindPlan`], [`RewindReport`] | What `Harness::rewind_plan` shows and `Harness::rewind` does |
17//!
18//! Snapshots are off in the library until [`HarnessAgentBuilder::snapshots`](crate::HarnessAgentBuilder::snapshots)
19//! is set, and on in adk-cli (spec 3.1 §13 Q11).
20//!
21//! # Example
22//!
23//! ```rust,ignore
24//! use adk_harness::snapshot::{RewindTarget, SnapshotConfig};
25//!
26//! let harness = HarnessAgent::builder("harness")
27//!     .model(model)
28//!     .workspace(workspace)
29//!     .snapshots(SnapshotConfig::default())
30//!     .build()?
31//!     .into_harness("my-app", sessions)?;
32//! // ... turns run ...
33//! let mut plan = harness.rewind_plan(&user, &session, RewindTarget::Turn(1)).await?;
34//! println!("{}", plan.render());
35//! plan.confirm_protected();
36//! let report = harness.rewind(&user, &session, &plan).await?;
37//! ```
38
39mod objects;
40mod plan;
41#[cfg(feature = "runner")]
42mod rewind;
43mod runtime;
44mod store;
45mod walk;
46
47#[cfg(feature = "encrypted")]
48pub use objects::rewrap_all;
49pub use objects::{
50    FileSnapshotObjects, InMemorySnapshotObjects, ObjectInfo, SnapshotObjects, object_id,
51    root_digest,
52};
53pub use plan::{
54    ChangeKind, NotUndone, PlanRewind, RewindEntry, RewindPlan, RewindReport, RewindTarget,
55    RewindTurn, SkippedPath, TranscriptPlan,
56};
57pub use runtime::{SnapshotInfo, SnapshotRequest, Snapshots, TreeScan};
58#[cfg(feature = "sqlite")]
59pub use store::SqliteSnapshotStore;
60pub use store::{
61    FileEntry, InMemorySnapshotStore, PlanMark, SnapshotKind, SnapshotRecord, SnapshotStore,
62    TranscriptTail,
63};
64pub use walk::{
65    DEFAULT_SKIP_DIRS, EntryKind, ExcludeFilter, NotCovered, SkipReason, TreeWalk, WalkOptions,
66    WalkedFile, walk,
67};
68
69#[cfg(feature = "runner")]
70pub(crate) use plan::{harness_writes, transcript_cut, turns_of};
71
72use std::sync::Arc;
73
74/// Most not-covered files a snapshot record lists; the rest are counted.
75pub const NOT_COVERED_LISTED: usize = 200;
76
77/// The audit action of a snapshot (spec 3.1 §9.3).
78pub const SNAPSHOT_TAKEN_ACTION: &str = "harness.snapshot.taken";
79
80/// The audit action of a rewind (spec 3.1 §9.3), recorded before anything changes.
81pub const REWIND_ACTION: &str = "harness.rewind";
82
83/// What snapshots keep and skip (spec 3.1 §7.27).
84///
85/// # Example
86///
87/// ```rust
88/// use adk_harness::snapshot::SnapshotConfig;
89///
90/// let config = SnapshotConfig::default();
91/// assert_eq!(config.keep_turns, 50);
92/// assert_eq!(config.max_bytes, 2 * 1024 * 1024 * 1024);
93/// assert_eq!(config.max_files, 50_000);
94/// assert_eq!(config.max_file_bytes, 8 * 1024 * 1024);
95/// assert!(config.skip_dirs.iter().any(|dir| dir == "target"));
96/// ```
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct SnapshotConfig {
99    /// Turn snapshots kept per session, with whatever was taken after the oldest of them.
100    pub keep_turns: u32,
101    /// Object bytes kept per workspace; the oldest snapshots go first.
102    pub max_bytes: u64,
103    /// Files a snapshot records before it stops and is partial.
104    pub max_files: usize,
105    /// Larger files are listed as not covered.
106    pub max_file_bytes: u64,
107    /// Directory names never entered: build output and dependencies.
108    pub skip_dirs: Vec<String>,
109}
110
111impl Default for SnapshotConfig {
112    fn default() -> Self {
113        Self {
114            keep_turns: 50,
115            max_bytes: 2 * 1024 * 1024 * 1024,
116            max_files: 50_000,
117            max_file_bytes: 8 * 1024 * 1024,
118            skip_dirs: DEFAULT_SKIP_DIRS.iter().map(|dir| (*dir).to_string()).collect(),
119        }
120    }
121}
122
123/// What the builder collects for snapshots: the configuration and, optionally, where
124/// records and objects go (both in memory by default).
125#[derive(Default)]
126pub(crate) struct SnapshotSetup {
127    pub(crate) config: Option<SnapshotConfig>,
128    pub(crate) store: Option<Arc<dyn SnapshotStore>>,
129    pub(crate) objects: Option<Arc<dyn SnapshotObjects>>,
130}
131
132impl SnapshotSetup {
133    /// The workspace's snapshots, when a configuration was set.
134    pub(crate) fn build(
135        self,
136        workspace: &adk_devtools::Workspace,
137    ) -> adk_core::Result<Option<Arc<Snapshots>>> {
138        let Some(config) = self.config else {
139            return Ok(None);
140        };
141        let store = self.store.unwrap_or_else(|| Arc::new(InMemorySnapshotStore::new()));
142        let objects = self.objects.unwrap_or_else(|| Arc::new(InMemorySnapshotObjects::new()));
143        Ok(Some(Arc::new(Snapshots::new(config, workspace, store, objects)?)))
144    }
145}
146
147/// The capability-block line for snapshots (spec 3.1 §7.25, §13 Q11): what they cover and
148/// when a snapshot is partial.
149pub(crate) fn safety_covers(config: &SnapshotConfig, plan_rewind: bool) -> (String, String) {
150    let plan = if plan_rewind { ", transcript and plan" } else { " and transcript" };
151    (
152        format!(
153            "files: before each user turn and plan step the whole workspace is snapshotted, \
154             shell writes included; /rewind restores those files{plan}, and /redo undoes a \
155             rewind; the last {} turns",
156            config.keep_turns
157        ),
158        format!(
159            "pushes, payments, sent messages, webhooks or running background shells; \
160             .gitignore'd files, build \
161             directories ({}), excluded paths and files over {} MiB; a snapshot that reaches \
162             {} files is partial and /rewind lists what it did not cover",
163            config.skip_dirs.join(", "),
164            config.max_file_bytes / (1024 * 1024),
165            config.max_files
166        ),
167    )
168}
169
170/// Takes the turn snapshot of a run that carries a user message (spec 3.1 §7.27): once per
171/// run, before its first model call. A failure is logged and the turn goes on without one.
172pub(crate) async fn before_turn(
173    snapshots: &Snapshots,
174    ctx: &dyn adk_core::InvocationContext,
175    plan: Option<PlanMark>,
176) {
177    if ctx.user_content().parts.is_empty()
178        || !snapshots.first_turn_snapshot(ctx.session_id(), ctx.invocation_id())
179    {
180        return;
181    }
182    let request = SnapshotRequest::for_context(ctx, SnapshotKind::Turn).plan(plan);
183    record_taken(snapshots.take(request).await, ctx).await;
184}
185
186/// Takes the snapshot before plan step `step` (spec 3.1 §7.27).
187#[cfg(feature = "graph")]
188pub(crate) async fn before_step(
189    snapshots: &Snapshots,
190    ctx: &dyn adk_core::InvocationContext,
191    step: &str,
192    plan: PlanMark,
193) {
194    let request = SnapshotRequest::for_context(ctx, SnapshotKind::Step).step(step).plan(Some(plan));
195    record_taken(snapshots.take(request).await, ctx).await;
196}
197
198async fn record_taken(
199    taken: adk_core::Result<SnapshotInfo>,
200    ctx: &dyn adk_core::InvocationContext,
201) {
202    match taken {
203        Ok(info) => {
204            if let Some(trail) = ctx.run_config().audit.clone() {
205                let audit = crate::audit::HarnessAudit::new(
206                    trail,
207                    adk_core::audit_log::AuditActor::for_context(ctx),
208                    ctx.session_id(),
209                );
210                if let Err(error) = audit.record(SNAPSHOT_TAKEN_ACTION, info.audit_fields()).await {
211                    tracing::warn!(error = %error, "the snapshot's audit record was not written");
212                }
213            }
214        }
215        Err(error) => {
216            tracing::warn!(error = %error, "no snapshot before this turn; /rewind cannot restore it");
217        }
218    }
219}