1use std::collections::{HashMap, HashSet};
31use std::path::{Path, PathBuf};
32
33use rusqlite::{Connection, OpenFlags};
34
35use crate::backend::agent_session::{
36 agent_current_zone, is_valid_definition_id, OUTPUT_FILE, SNAPSHOT_FILE, TSIDX_FILE,
37};
38use crate::backend::storage::filestore::{FileMeta, FileOpts, FileStore};
39
40fn richest_outputs(home: &Path, want: &HashSet<&str>) -> (HashMap<String, Vec<u8>>, usize) {
43 let mut scanned = 0;
44 let mut best: HashMap<String, Vec<u8>> = HashMap::new();
46 for data in collect_data_dirs(home) {
47 let objdb = data.join("db").join("objects.db");
48 let fdb = data.join("db").join("filestore.db");
49 if !objdb.is_file() || !fdb.is_file() {
50 continue;
51 }
52 scanned += 1;
53 let blocks = match read_agent_blocks(&objdb, want) {
54 Ok(b) if !b.is_empty() => b,
55 _ => continue,
56 };
57 let conn = match Connection::open_with_flags(&fdb, OpenFlags::SQLITE_OPEN_READ_ONLY) {
58 Ok(c) => c,
59 Err(_) => continue,
60 };
61 for (def_id, block_oid) in blocks {
62 if let Some(bytes) = read_zone_output(&conn, &block_oid) {
63 let better = best.get(&def_id).map(|b| bytes.len() > b.len()).unwrap_or(true);
64 if better {
65 best.insert(def_id, bytes);
66 }
67 }
68 }
69 }
70 (best, scanned)
71}
72
73#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
75pub struct RestoreStats {
76 pub zones: usize,
77 pub restored: usize,
78 pub no_source: usize,
80 pub source_shorter: usize,
82 pub not_restorable: usize,
84}
85
86pub fn restore_damaged(home: &Path, global: &FileStore, zones: &[String]) -> RestoreStats {
91 let mut stats = RestoreStats { zones: zones.len(), ..Default::default() };
92 let mut defs: Vec<(&str, &String)> = Vec::new();
93 for zone in zones {
94 match zone.strip_prefix("agent:").and_then(|z| z.strip_suffix(":current")).filter(|id| is_valid_definition_id(id)) {
95 Some(id) => defs.push((id, zone)),
96 None => stats.not_restorable += 1,
97 }
98 }
99 if defs.is_empty() {
100 return stats;
101 }
102 let want: HashSet<&str> = defs.iter().map(|(id, _)| *id).collect();
103 let (best, _) = richest_outputs(home, &want);
104 for (id, zone) in defs {
105 let Some(bytes) = best.get(id) else {
106 stats.no_source += 1;
107 continue;
108 };
109 let recorded = global.stat(zone, OUTPUT_FILE).ok().flatten().map(|f| f.size).unwrap_or(0);
110 if (bytes.len() as i64) < recorded {
111 stats.source_shorter += 1;
112 continue;
113 }
114 match seed_global_zone(global, zone, bytes) {
115 Ok(()) => stats.restored += 1,
116 Err(e) => tracing::warn!(zone = %zone, error = %e, "history repair: couldn't put the conversation back"),
117 }
118 }
119 stats
120}
121
122fn seed_global_zone(global: &FileStore, zone: &str, bytes: &[u8]) -> Result<(), String> {
125 global
129 .replace_file(zone, OUTPUT_FILE, bytes, &[TSIDX_FILE, "output.idx"])
130 .map_err(|e| format!("replace_file: {e}"))?;
131 crate::backend::transcript::images::forget(zone);
133 let hwm = count_nonblank_lines(bytes);
134 let overlay = serde_json::json!({
135 "schemaVersion": 2,
136 "savedAt": "",
137 "highWaterMark": hwm,
138 "sourceBlockId": "",
139 "documentState": {
140 "collapsedNodeIds": [],
141 "pinnedNodeIds": [],
142 "scrollPosition": 0,
143 "filter": {
144 "showThinking": false,
145 "showSuccessfulTools": true,
146 "showFailedTools": true,
147 "showIncoming": true,
148 "showOutgoing": true
149 }
150 },
151 "paneState": { "detailsOpen": false }
152 });
153 let overlay_bytes = serde_json::to_vec(&overlay).map_err(|e| format!("overlay json: {e}"))?;
154 overwrite_zone_file(global, zone, SNAPSHOT_FILE, &overlay_bytes)?;
155 Ok(())
156}
157
158fn overwrite_zone_file(fs: &FileStore, zone: &str, name: &str, bytes: &[u8]) -> Result<(), String> {
161 use crate::backend::storage::error::StoreError;
162 if fs.stat(zone, name).map_err(|e| format!("stat: {e}"))?.is_none() {
163 match fs.make_file(zone, name, FileMeta::default(), FileOpts::default()) {
164 Ok(()) => {}
165 Err(StoreError::AlreadyExists) => {}
166 Err(e) => return Err(format!("make_file: {e}")),
167 }
168 }
169 fs.write_file(zone, name, bytes).map_err(|e| format!("write_file: {e}"))
170}
171
172fn count_nonblank_lines(bytes: &[u8]) -> u64 {
173 String::from_utf8_lossy(bytes)
174 .lines()
175 .filter(|l| !l.trim().is_empty())
176 .count() as u64
177}
178
179fn read_agent_blocks(
182 objdb: &Path,
183 want: &HashSet<&str>,
184) -> Result<Vec<(String, String)>, rusqlite::Error> {
185 let conn = Connection::open_with_flags(objdb, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
186 let mut stmt = conn.prepare("SELECT data FROM db_block")?;
187 let rows = stmt.query_map([], |row| row.get::<_, Vec<u8>>(0))?;
191 let mut out = Vec::new();
192 for r in rows {
193 let Ok(bytes) = r else { continue };
194 let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes) else { continue };
195 let meta = v.get("meta");
196 let agent_id = meta
203 .and_then(|m| m.get("agentId"))
204 .and_then(|x| x.as_str())
205 .or_else(|| meta.and_then(|m| m.get("agent:id")).and_then(|x| x.as_str()));
206 let oid = v.get("oid").and_then(|x| x.as_str());
207 if let (Some(aid), Some(oid)) = (agent_id, oid) {
208 if want.contains(aid) {
209 out.push((aid.to_string(), oid.to_string()));
210 }
211 }
212 }
213 Ok(out)
214}
215
216fn read_zone_output(conn: &Connection, block_oid: &str) -> Option<Vec<u8>> {
221 let size: Option<i64> = conn
222 .query_row(
223 "SELECT size FROM db_wave_file WHERE zoneid = ?1 AND name = ?2",
224 rusqlite::params![block_oid, OUTPUT_FILE],
225 |r| r.get(0),
226 )
227 .ok();
228 if size.unwrap_or(0) <= 0 {
229 return None;
230 }
231 let mut stmt = conn
232 .prepare("SELECT data FROM db_file_data WHERE zoneid = ?1 AND name = ?2 ORDER BY partidx")
233 .ok()?;
234 let rows = stmt
235 .query_map(rusqlite::params![block_oid, OUTPUT_FILE], |r| {
236 r.get::<_, Vec<u8>>(0)
237 })
238 .ok()?;
239 let mut buf = Vec::new();
240 for r in rows {
241 if let Ok(part) = r {
242 buf.extend_from_slice(&part);
243 }
244 }
245 buf.truncate(size.unwrap_or(0).max(0) as usize);
247 if buf.is_empty() {
248 None
249 } else {
250 Some(buf)
251 }
252}
253
254fn collect_data_dirs(home: &Path) -> Vec<PathBuf> {
257 let mut dirs = Vec::new();
258 let mut add = |d: PathBuf| {
259 if d.join("db").join("objects.db").is_file() {
260 dirs.push(d);
261 }
262 };
263 for ch in dir_subdirs(&home.join("channels")) {
264 for v in dir_subdirs(&ch.join("versions")) {
265 add(v.join("data"));
266 }
267 }
268 for br in dir_subdirs(&home.join("dev")) {
269 add(br.join("data"));
270 for sub in dir_subdirs(&br) {
271 add(sub.join("data"));
272 }
273 }
274 dirs
275}
276
277fn dir_subdirs(p: &Path) -> Vec<PathBuf> {
278 let mut out = Vec::new();
279 if let Ok(rd) = std::fs::read_dir(p) {
280 for e in rd.flatten() {
281 let path = e.path();
282 if path.is_dir() {
283 out.push(path);
284 }
285 }
286 }
287 out
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293 use crate::backend::agent_session::OUTPUT_FILE as OUT;
294 use std::sync::Arc;
295
296 fn seed_channel(home: &Path, ch: &str, def_id: &str, block_oid: &str, output: &[u8]) {
299 seed_channel_keyed(home, ch, "agentId", def_id, block_oid, output);
300 }
301
302 fn seed_channel_keyed(
303 home: &Path,
304 ch: &str,
305 meta_key: &str,
306 def_id: &str,
307 block_oid: &str,
308 output: &[u8],
309 ) {
310 let data = home
311 .join("channels")
312 .join(ch)
313 .join("versions")
314 .join("0.44.1")
315 .join("data");
316 let db = data.join("db");
317 std::fs::create_dir_all(&db).unwrap();
318 let oc = Connection::open(db.join("objects.db")).unwrap();
320 oc.execute("CREATE TABLE db_block (data TEXT)", []).unwrap();
321 let block_json = serde_json::json!({"oid": block_oid, "meta": {"view":"agent", meta_key: def_id}});
322 oc.execute(
325 "INSERT INTO db_block (data) VALUES (?1)",
326 rusqlite::params![block_json.to_string().into_bytes()],
327 )
328 .unwrap();
329 drop(oc);
330 let fs = FileStore::open(&db.join("filestore.db")).unwrap();
332 fs.make_file(block_oid, OUT, FileMeta::default(), FileOpts::default()).unwrap();
333 fs.append_data(block_oid, OUT, output).unwrap();
334 }
335
336 #[test]
337 fn a_restore_takes_the_richest_copy_and_matches_a_block_with_the_legacy_agent_id_key() {
338 let tmp = tempfile::tempdir().unwrap();
342 let home = tmp.path();
343 let tdir = home.join("shared").join("agents").join("transcripts");
344 std::fs::create_dir_all(&tdir).unwrap();
345 let (rich, legacy) = ("11111111-2222-3333-4444-555555555555", "deadbeef-0000-1111-2222-333344445555");
346 let small = b"{\"type\":\"system\"}\n";
347 let big = b"{\"type\":\"system\"}\n{\"type\":\"assistant\"}\n{\"type\":\"result\"}\n";
348 seed_channel(home, "verify-a", rich, "blk-small", small);
349 seed_channel(home, "verify-b", rich, "blk-big", big);
350 seed_channel_keyed(home, "legacy-ch", "agent:id", legacy, "blk-legacy", small);
351
352 let global = Arc::new(FileStore::open(&tdir.join("filestore.db")).unwrap());
353 let zones: Vec<String> = [rich, legacy].iter().map(|id| agent_current_zone(id)).collect();
354 for zone in &zones {
355 global.make_file(zone, OUT, FileMeta::default(), FileOpts::default()).unwrap();
356 }
357 let stats = restore_damaged(home, &global, &zones);
358
359 assert_eq!(stats.restored, 2, "both zones are put back");
360 let rich_zone = agent_current_zone(rich);
361 assert_eq!(global.read_file(&rich_zone, OUT).unwrap().unwrap(), big, "the RICHEST channel output");
362 assert_eq!(global.read_file(&agent_current_zone(legacy), OUT).unwrap().unwrap(), small, "the legacy-keyed block is found");
363 let snap = global.read_file(&rich_zone, SNAPSHOT_FILE).unwrap().unwrap();
365 let o: serde_json::Value = serde_json::from_slice(&snap).unwrap();
366 assert_eq!(o["schemaVersion"], 2);
367 assert_eq!(o["highWaterMark"], 3);
368 assert_eq!(o["sourceBlockId"], "");
369 }
370
371 #[test]
372 fn a_damaged_zone_is_put_back_from_a_whole_channel_copy_and_never_from_a_shorter_one() {
373 let tmp = tempfile::tempdir().unwrap();
374 let home = tmp.path();
375 let tdir = home.join("shared").join("agents").join("transcripts");
376 std::fs::create_dir_all(&tdir).unwrap();
377 let (whole, short, none) = ("11111111-2222-3333-4444-555555555555", "22222222-2222-3333-4444-555555555555", "33333333-2222-3333-4444-555555555555");
378 let copy = b"{\"type\":\"system\"}\n{\"type\":\"assistant\"}\n{\"type\":\"result\"}\n";
379 seed_channel(home, "ch-a", whole, "blk-whole", copy);
380 seed_channel(home, "ch-b", short, "blk-short", b"{\"type\":\"system\"}\n");
381
382 let global = Arc::new(FileStore::open(&tdir.join("filestore.db")).unwrap());
383 let damaged = vec![0u8; copy.len() - 10];
385 for id in [whole, short, none] {
386 let zone = agent_current_zone(id);
387 global.make_file(&zone, OUT, FileMeta::default(), FileOpts::default()).unwrap();
388 global.write_file(&zone, OUT, &damaged).unwrap();
389 }
390 let zones: Vec<String> = [whole, short, none].iter().map(|id| agent_current_zone(id)).chain(["agent:abc:archive:5".to_string()]).collect();
391
392 let stats = restore_damaged(home, &global, &zones);
393 assert_eq!(stats, RestoreStats { zones: 4, restored: 1, no_source: 1, source_shorter: 1, not_restorable: 1 });
394 assert_eq!(global.read_file(&agent_current_zone(whole), OUT).unwrap().unwrap(), copy);
395 assert_eq!(global.read_file(&agent_current_zone(short), OUT).unwrap().unwrap(), damaged, "a shorter copy changes nothing");
396 assert_eq!(global.read_file(&agent_current_zone(none), OUT).unwrap().unwrap(), damaged);
397 }
398
399}