1use std::sync::Mutex;
5
6use adk_core::Result;
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use super::walk::NotCovered;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
25#[serde(rename_all = "lowercase")]
26pub enum SnapshotKind {
27 Turn,
29 Step,
31 Destructive,
33 Rewind,
35}
36
37impl SnapshotKind {
38 pub fn as_str(self) -> &'static str {
40 match self {
41 Self::Turn => "turn",
42 Self::Step => "step",
43 Self::Destructive => "destructive",
44 Self::Rewind => "rewind",
45 }
46 }
47}
48
49impl std::fmt::Display for SnapshotKind {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 f.write_str(self.as_str())
52 }
53}
54
55#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "camelCase")]
58pub struct FileEntry {
59 pub path: String,
61 pub sha256: String,
63 pub len: u64,
65 #[serde(default)]
67 pub mode: u32,
68 #[serde(default)]
70 pub mtime_ns: u64,
71 #[serde(default)]
73 pub inode: u64,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub link: Option<String>,
77}
78
79impl FileEntry {
80 pub fn same_content(&self, other: &Self) -> bool {
82 self.sha256 == other.sha256 && self.mode == other.mode && self.link == other.link
83 }
84}
85
86#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub struct PlanMark {
90 pub plan_hash: String,
92 pub thread_id: String,
94 pub completed: Vec<String>,
96 pub running: bool,
98}
99
100#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase")]
104pub struct TranscriptTail {
105 pub after: Option<String>,
107 pub events: Vec<Value>,
109}
110
111#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
114#[serde(rename_all = "camelCase")]
115pub struct SnapshotRecord {
116 pub id: String,
118 pub app_name: String,
120 pub user_id: String,
122 pub session_id: String,
124 pub root: String,
126 pub created_at: DateTime<Utc>,
128 pub kind: SnapshotKind,
130 pub invocation_id: String,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub step: Option<String>,
135 pub files_object: String,
137 pub file_count: usize,
139 pub total_bytes: u64,
141 pub bytes_new: u64,
143 pub partial: bool,
145 #[serde(default)]
147 pub not_covered: Vec<NotCovered>,
148 #[serde(default)]
150 pub not_covered_more: usize,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub plan: Option<PlanMark>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub transcript: Option<TranscriptTail>,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub rewound: Option<std::collections::BTreeMap<String, Option<String>>>,
161}
162
163#[async_trait]
168pub trait SnapshotStore: Send + Sync {
169 async fn put(&self, record: &SnapshotRecord) -> Result<()>;
171
172 async fn get(&self, id: &str) -> Result<Option<SnapshotRecord>>;
174
175 async fn list_session(
177 &self,
178 app: &str,
179 user: &str,
180 session: &str,
181 ) -> Result<Vec<SnapshotRecord>>;
182
183 async fn list_root(&self, root: &str) -> Result<Vec<SnapshotRecord>>;
185
186 async fn delete(&self, ids: &[String]) -> Result<()>;
188}
189
190fn oldest_first(records: &mut [SnapshotRecord]) {
191 records.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
192}
193
194#[derive(Debug, Default)]
210pub struct InMemorySnapshotStore {
211 records: Mutex<Vec<SnapshotRecord>>,
212}
213
214impl InMemorySnapshotStore {
215 pub fn new() -> Self {
217 Self::default()
218 }
219}
220
221#[async_trait]
222impl SnapshotStore for InMemorySnapshotStore {
223 async fn put(&self, record: &SnapshotRecord) -> Result<()> {
224 let mut records = self.records.lock().unwrap_or_else(|e| e.into_inner());
225 records.retain(|known| known.id != record.id);
226 records.push(record.clone());
227 Ok(())
228 }
229
230 async fn get(&self, id: &str) -> Result<Option<SnapshotRecord>> {
231 Ok(self
232 .records
233 .lock()
234 .unwrap_or_else(|e| e.into_inner())
235 .iter()
236 .find(|record| record.id == id)
237 .cloned())
238 }
239
240 async fn list_session(
241 &self,
242 app: &str,
243 user: &str,
244 session: &str,
245 ) -> Result<Vec<SnapshotRecord>> {
246 let mut out: Vec<SnapshotRecord> = self
247 .records
248 .lock()
249 .unwrap_or_else(|e| e.into_inner())
250 .iter()
251 .filter(|r| r.app_name == app && r.user_id == user && r.session_id == session)
252 .cloned()
253 .collect();
254 oldest_first(&mut out);
255 Ok(out)
256 }
257
258 async fn list_root(&self, root: &str) -> Result<Vec<SnapshotRecord>> {
259 let mut out: Vec<SnapshotRecord> = self
260 .records
261 .lock()
262 .unwrap_or_else(|e| e.into_inner())
263 .iter()
264 .filter(|record| record.root == root)
265 .cloned()
266 .collect();
267 oldest_first(&mut out);
268 Ok(out)
269 }
270
271 async fn delete(&self, ids: &[String]) -> Result<()> {
272 self.records.lock().unwrap_or_else(|e| e.into_inner()).retain(|r| !ids.contains(&r.id));
273 Ok(())
274 }
275}
276
277#[cfg(feature = "sqlite")]
288#[derive(Debug, Clone)]
289pub struct SqliteSnapshotStore {
290 pool: sqlx::SqlitePool,
291 #[cfg(feature = "encrypted")]
292 envelope: Option<crate::encrypted::StoreEnvelope>,
293}
294
295#[cfg(feature = "sqlite")]
296impl SqliteSnapshotStore {
297 pub fn new(pool: sqlx::SqlitePool) -> Self {
299 Self {
300 pool,
301 #[cfg(feature = "encrypted")]
302 envelope: None,
303 }
304 }
305
306 #[cfg(feature = "encrypted")]
308 #[must_use]
309 pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
310 self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "snapshots"));
311 self
312 }
313
314 #[cfg(feature = "encrypted")]
322 pub async fn rewrap(&self) -> Result<u64> {
323 let Some(envelope) = &self.envelope else {
324 return Ok(0);
325 };
326 let rows: Vec<(String, String)> =
327 sqlx::query_as("SELECT id, record FROM adk_harness_snapshots")
328 .fetch_all(&self.pool)
329 .await
330 .map_err(crate::fsutil::db_error)?;
331 let mut changed = 0;
332 for (id, text) in rows {
333 if let Some(resealed) = envelope.reseal_or_seal(&[&id], &text)? {
334 sqlx::query("UPDATE adk_harness_snapshots SET record = ? WHERE id = ?")
335 .bind(resealed)
336 .bind(&id)
337 .execute(&self.pool)
338 .await
339 .map_err(crate::fsutil::db_error)?;
340 changed += 1;
341 }
342 }
343 Ok(changed)
344 }
345
346 pub async fn migrate(&self) -> Result<()> {
352 for statement in [
353 "CREATE TABLE IF NOT EXISTS adk_harness_snapshots (\
354 id TEXT PRIMARY KEY, app_name TEXT NOT NULL, user_id TEXT NOT NULL, \
355 session_id TEXT NOT NULL, root TEXT NOT NULL, created_at TEXT NOT NULL, \
356 kind TEXT NOT NULL, record TEXT NOT NULL)",
357 "CREATE INDEX IF NOT EXISTS adk_harness_snapshots_session \
358 ON adk_harness_snapshots (app_name, user_id, session_id)",
359 "CREATE INDEX IF NOT EXISTS adk_harness_snapshots_root \
360 ON adk_harness_snapshots (root)",
361 ] {
362 sqlx::query(statement).execute(&self.pool).await.map_err(crate::fsutil::db_error)?;
363 }
364 Ok(())
365 }
366
367 #[cfg(feature = "encrypted")]
368 fn encode(&self, id: &str, text: String) -> Result<String> {
369 crate::encrypted::encode_row(self.envelope.as_ref(), &[id], text)
370 }
371
372 #[cfg(not(feature = "encrypted"))]
373 fn encode(&self, _id: &str, text: String) -> Result<String> {
374 Ok(text)
375 }
376
377 #[cfg(feature = "encrypted")]
378 fn decode(&self, id: &str, text: String) -> Result<String> {
379 crate::encrypted::decode_row(self.envelope.as_ref(), "snapshots", &[id], text)
380 }
381
382 #[cfg(not(feature = "encrypted"))]
383 fn decode(&self, _id: &str, text: String) -> Result<String> {
384 Ok(text)
385 }
386
387 fn parse(&self, id: String, text: String) -> Result<Option<SnapshotRecord>> {
388 let text = self.decode(&id, text)?;
389 Ok(serde_json::from_str(&text).ok())
391 }
392
393 async fn select(&self, sql: &'static str, binds: &[&str]) -> Result<Vec<SnapshotRecord>> {
394 let mut query = sqlx::query_as::<_, (String, String)>(sql);
395 for bind in binds {
396 query = query.bind(*bind);
397 }
398 let rows = query.fetch_all(&self.pool).await.map_err(crate::fsutil::db_error)?;
399 let mut out = Vec::with_capacity(rows.len());
400 for (id, text) in rows {
401 if let Some(record) = self.parse(id, text)? {
402 out.push(record);
403 }
404 }
405 oldest_first(&mut out);
406 Ok(out)
407 }
408}
409
410#[cfg(feature = "sqlite")]
411#[async_trait]
412impl SnapshotStore for SqliteSnapshotStore {
413 async fn put(&self, record: &SnapshotRecord) -> Result<()> {
414 let text = serde_json::to_string(record)
415 .map_err(|error| crate::fsutil::serialize_error("snapshot record", &error))?;
416 let text = self.encode(&record.id, text)?;
417 sqlx::query(
418 "INSERT INTO adk_harness_snapshots \
419 (id, app_name, user_id, session_id, root, created_at, kind, record) \
420 VALUES (?, ?, ?, ?, ?, ?, ?, ?) \
421 ON CONFLICT (id) DO UPDATE SET record = excluded.record",
422 )
423 .bind(&record.id)
424 .bind(&record.app_name)
425 .bind(&record.user_id)
426 .bind(&record.session_id)
427 .bind(&record.root)
428 .bind(record.created_at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true))
429 .bind(record.kind.as_str())
430 .bind(text)
431 .execute(&self.pool)
432 .await
433 .map_err(crate::fsutil::db_error)?;
434 Ok(())
435 }
436
437 async fn get(&self, id: &str) -> Result<Option<SnapshotRecord>> {
438 Ok(self
439 .select("SELECT id, record FROM adk_harness_snapshots WHERE id = ?", &[id])
440 .await?
441 .into_iter()
442 .next())
443 }
444
445 async fn list_session(
446 &self,
447 app: &str,
448 user: &str,
449 session: &str,
450 ) -> Result<Vec<SnapshotRecord>> {
451 self.select(
452 "SELECT id, record FROM adk_harness_snapshots \
453 WHERE app_name = ? AND user_id = ? AND session_id = ?",
454 &[app, user, session],
455 )
456 .await
457 }
458
459 async fn list_root(&self, root: &str) -> Result<Vec<SnapshotRecord>> {
460 self.select("SELECT id, record FROM adk_harness_snapshots WHERE root = ?", &[root]).await
461 }
462
463 async fn delete(&self, ids: &[String]) -> Result<()> {
464 for id in ids {
465 sqlx::query("DELETE FROM adk_harness_snapshots WHERE id = ?")
466 .bind(id)
467 .execute(&self.pool)
468 .await
469 .map_err(crate::fsutil::db_error)?;
470 }
471 Ok(())
472 }
473}