Skip to main content

agentmux_srv_core/backend/
transcript_backfill.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Put an agent's CONVERSATION back into the GLOBAL transcript store from the
5//! copies that live in the channels it ran in (`restore_damaged`, after a
6//! repair of the shared store).
7//!
8//! Cross-channel transcripts mirror agent output into the global
9//! `agent:<defId>:current` zone, but the channel the agent ran in keeps its own
10//! copy. This scans every channel/dev `objects.db` for blocks belonging to each
11//! agent definition, reads the richest `output` from that channel's
12//! `filestore.db`, and seeds the global zone with it.
13//!
14//! **Source = the channel block's `output`, NOT the provider `.jsonl`.** The
15//! block `output` is the exact stdout stream-json the renderer already parses
16//! (`parseHistoryLines` + the `claude-stream-json` translator); the provider
17//! `~/.claude/projects/<slug>/<sid>.jsonl` transcript is a *different* envelope
18//! (`queue-operation` / `user`+`parentUuid`/`sessionId`) the renderer can't
19//! consume, so copying it would render empty. Using the block output needs zero
20//! translation.
21//!
22//! The seeded snapshot overlay uses `sourceBlockId: ""`, which the frontend
23//! treats as "matches any block" — so opening the agent (a fresh local block
24//! with no local `output`) takes the v2 fast-path and the
25//! `blockfile:read_range` global fallback (#1399) serves the restored zone.
26//!
27//! Read-only on every scanned SQLite (the global store is the only thing
28//! written).
29
30use 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
40/// The richest `output` found for each wanted agent definition across every channel and dev data
41/// dir under `home`, and how many data dirs were scanned. Read-only on every scanned store.
42fn richest_outputs(home: &Path, want: &HashSet<&str>) -> (HashMap<String, Vec<u8>>, usize) {
43    let mut scanned = 0;
44    // def_id -> richest output bytes found across all channels/dev DBs.
45    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/// What [`restore_damaged`] did.
74#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
75pub struct RestoreStats {
76    pub zones: usize,
77    pub restored: usize,
78    /// No channel copy of the agent's conversation was found.
79    pub no_source: usize,
80    /// The best copy is shorter than the zone's recorded size: it may lack lines the zone had, so the zone is left.
81    pub source_shorter: usize,
82    /// Zones that are not an agent's current conversation (an archive, a memory record): no copy of them exists.
83    pub not_restorable: usize,
84}
85
86/// After a repair of the shared store (`filestore::repair`): put back the conversation of each agent
87/// whose zone in `zones` lost rows, from the richest whole copy of it in a channel's own store. A copy
88/// that is shorter than the size the zone records is not used: the shared zone also holds conversation
89/// from other channels and builds. Best-effort, never fatal.
90pub 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
122/// Write `bytes` as the zone's `output` and a v2 snapshot overlay
123/// (`sourceBlockId: ""`) so the open path restores it cross-channel.
124fn seed_global_zone(global: &FileStore, zone: &str, bytes: &[u8]) -> Result<(), String> {
125    // Replace `output` and drop both sidecars in one transaction (5a-2b):
126    // they describe the bytes being replaced (offsets, receive times), and a
127    // stale output.idx could pass the covered_size check by coincidence.
128    global
129        .replace_file(zone, OUTPUT_FILE, bytes, &[TSIDX_FILE, "output.idx"])
130        .map_err(|e| format!("replace_file: {e}"))?;
131    // The bytes are new, so a count of the images in the old ones does not carry over.
132    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
158/// Create-or-replace a zone file with exactly `bytes` (FileStore `write_file`
159/// requires the file to exist first).
160fn 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
179/// Read all blocks from `objdb` whose `meta.agentId` is in `want`, returning
180/// `(def_id, block_oid)` pairs. Read-only.
181fn 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    // `db_block.data` is declared TEXT but the mstore stores the JSON as a BLOB
188    // (`typeof = 'blob'`), so read raw bytes — `get::<String>` would error on
189    // every row and silently skip the whole DB. `from_slice` parses either.
190    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        // The agent definition id is stored under either `agentId` (current
197        // shape) or the legacy `agent:id` — match both, exactly like the
198        // canonical block scan in `agent_session/migrations/v1_blocks.rs`.
199        // Legacy blocks are a core part of the pre-existing population this
200        // backfill targets, so missing them would strand those conversations
201        // permanently (the marker is written after the scan). (#1403)
202        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
216/// Reassemble a zone's `output` file bytes directly from `db_file_data`
217/// (read-only, avoids opening a second writable FileStore on another channel).
218/// Returns `None` when absent or empty. Agent `output` is non-circular, so
219/// concatenating parts in `partidx` order matches `FileStore::read_file`.
220fn 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    // The last part's row can be longer than the file (blank slack, filestore parts.rs).
246    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
254/// Every `<home>/channels/*/versions/*/data` and `<home>/dev/<branch>[/<sub>]/data`
255/// (mirrors `registry::def_migrate::collect_scan_dbs`, returning the data dir).
256fn 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    // Build a channel data dir at <home>/channels/<ch>/versions/<v>/data with a
297    // db_block row (agentId=def) and a filestore.db holding that block's output.
298    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        // objects.db with a minimal db_block(data) row.
319        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        // Store as a BLOB to mirror the mstore (db_block.data is declared TEXT
323        // but holds blob-typed JSON) — the reader reads raw bytes.
324        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        // filestore.db with the block's output written via FileStore.
331        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        // Two channels hold the agent; the richer (bigger) output wins. A third agent's only block
339        // stamps the legacy `agent:id` meta key that older builds wrote instead of `agentId`; it
340        // must still be recovered (#1403).
341        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        // Snapshot overlay: v2, hwm = non-blank line count, sourceBlockId empty.
364        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        // What a repair leaves: the file's row (and its recorded size), with the bytes damaged.
384        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}