Skip to main content

agentmux_srv_core/backend/transcript/
framer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The framer: compresses finished parts of the shared transcript store into
5//! frames (SPEC_HISTORY_STORE_COMPRESSION_AND_COMPACTION_2026_10_21.md §5).
6//!
7//! On unless `agent:transcriptframes` is `false` (the operator's call,
8//! 2026-10-25: on by default, the setting stays as the way out). Every srv whose
9//! own setting is on runs it (settings are per channel, so no one srv's speaks for the
10//! machine); each frame is one transaction that checks its parts first, so
11//! two srvs framing at once never conflict. Before each pass it checks that **every** running `agentmux-srv` has said
12//! it reads frames, in a file under `readers/` beside the store (written by
13//! [`mark_reader`] when a srv opens the store). An older build, or another
14//! agent's dev build from an older branch, can't read frames: while one runs,
15//! nothing is framed. The store is stamped `user_version` 3 before the first
16//! frame, so an older build started later refuses the store and runs from its
17//! own copy (`filestore::core`, `GLOBAL_TRANSCRIPT_STORE_FRAMES_VERSION`).
18//!
19//! What is framed (SPEC_CONVERSATION_HISTORY_ONE_TOTAL_AND_COMPRESSION_AT_THE_BOUNDARY_2026_11_30.md section 4): every
20//! append-only stream of an agent's zones (`output`, its sidecars, the provider copy and the imported session files), up
21//! to 16 parts (1 MiB) at a time, never the part a reader still tails. A live file keeps its last [`TAIL_BYTES`] raw; a
22//! file nobody has written to for [`QUIET_MS`] keeps only its last part, and its last group may be smaller than 16 parts.
23//! There is no longer a wait of hours: a block is framed as soon as it is behind the tail. `frame_parts` writes each frame,
24//! reads it back, compares every byte and only then removes the rows, in one transaction.
25
26use std::collections::HashSet;
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, OnceLock};
29
30use crate::backend::storage::error::StoreError;
31use crate::backend::transcript::damage;
32use crate::backend::storage::filestore::{FileStore, FrameOutcome, CODEC_DELTAS, CODEC_DELTA_API, CODEC_ZSTD, FRAME_PARTS};
33
34/// `agent:transcriptframes`: compress the shared transcript store. On unless `false`.
35pub const SETTING_FRAMES: &str = "agent:transcriptframes";
36/// `agent:transcriptdeltas`: with frames on, also store the streaming deltas as
37/// uuid and length (codec 2). On unless `false`.
38pub const SETTING_DELTAS: &str = "agent:transcriptdeltas";
39
40const OUTPUT: &str = "output";
41const TSIDX: &str = "output.tsidx";
42/// A live file keeps this many bytes of its end raw: the part appends go to and the lines a tail read wants first.
43const TAIL_BYTES: i64 = 1 << 20;
44/// A conversation whose last line was received longer ago than this is not being written: its files keep only their last
45/// part raw.
46const QUIET_MS: i64 = 10 * 60 * 1000;
47/// The part size of the store's files.
48const PART_BYTES: i64 = 65536;
49/// Frames written per pass, so a pass stays short (about 64 MiB).
50pub const PASS_FRAMES: usize = 64;
51/// The wait after each frame, so another srv's writes get the lock between frames.
52const FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(40);
53/// The frame codecs this build reads, written in its readers file. Codec 3 (deltas with an `api_message_id`) has been read
54/// since the release before the one that writes it, so a build rolled back one release still opens the store.
55const READS_CODECS: [i64; 3] = [CODEC_ZSTD, CODEC_DELTAS, CODEC_DELTA_API];
56/// The frame codecs the framer writes: every running srv must read all of them before it frames.
57const WRITES_CODECS: [i64; 3] = [CODEC_ZSTD, CODEC_DELTAS, CODEC_DELTA_API];
58
59static CONFIG: OnceLock<Arc<crate::backend::wconfig::ConfigState>> = OnceLock::new();
60
61/// Attach the live settings (bootstrap).
62pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
63    let _ = CONFIG.set(config);
64}
65
66/// Whether the framer runs (`agent:transcriptframes`): unset means on, only an
67/// explicit `false` turns it off.
68pub fn enabled() -> bool {
69    #[cfg(test)]
70    if FRAMES_OFF_FOR_TEST.with(std::cell::Cell::get) {
71        return false;
72    }
73    on_unless_false(CONFIG.get().and_then(|c| c.extra_bool(SETTING_FRAMES)))
74}
75
76#[cfg(test)]
77thread_local! {
78    static FRAMES_OFF_FOR_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
79}
80
81/// A test's switch: with it on this thread's framer is off, so the store's own bytes can be scanned for a marker
82/// (`history_guarantee_tests`, spec 13).
83#[cfg(test)]
84pub(crate) fn set_frames_off_for_test(off: bool) {
85    FRAMES_OFF_FOR_TEST.with(|c| c.set(off));
86}
87
88fn on_unless_false(setting: Option<bool>) -> bool {
89    setting.unwrap_or(true)
90}
91
92fn deltas_enabled() -> bool {
93    CONFIG.get().and_then(|c| c.extra_bool(SETTING_DELTAS)).unwrap_or(true)
94}
95
96fn readers_dir(store_dir: &Path) -> PathBuf {
97    store_dir.join("readers")
98}
99
100/// Process start time (seconds since the epoch) of `pid`, as sysinfo reports it.
101pub(crate) fn start_time(sys: &sysinfo::System, pid: u32) -> Option<u64> {
102    sys.process(sysinfo::Pid::from_u32(pid)).map(|p| p.start_time())
103}
104
105pub(crate) fn scan_processes() -> sysinfo::System {
106    let mut sys = sysinfo::System::new();
107    sys.refresh_processes_specifics(
108        sysinfo::ProcessesToUpdate::All,
109        true,
110        sysinfo::ProcessRefreshKind::nothing()
111            .without_tasks()
112            .with_cmd(sysinfo::UpdateKind::Always)
113            .with_exe(sysinfo::UpdateKind::Always),
114    );
115    sys
116}
117
118/// Say, in `readers/<pid>.json` beside the store, that this srv reads frames.
119/// Called when a srv opens the shared store. A file left by a process that has
120/// exited is pruned by the framer; the start time in it keeps a reused pid from
121/// passing for this one.
122pub fn mark_reader(store_dir: &Path) {
123    let pid = std::process::id();
124    let sys = scan_processes();
125    let mark = serde_json::json!({
126        "pid": pid,
127        "started_s": start_time(&sys, pid).unwrap_or(0),
128        "version": env!("CARGO_PKG_VERSION"),
129        "codecs": READS_CODECS,
130    });
131    let dir = readers_dir(store_dir);
132    let result = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(dir.join(format!("{pid}.json")), mark.to_string()));
133    if let Err(e) = result {
134        tracing::warn!(error = %e, dir = %dir.display(), "framer: couldn't write this srv's readers file; framing waits for it");
135    }
136}
137
138pub(crate) fn is_srv(name: &str) -> bool {
139    name.to_ascii_lowercase().starts_with("agentmux-srv")
140}
141
142/// The last pass's frames, or -1 before the first; and whether it was done.
143static LAST_PASS: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1);
144
145/// Record a pass, for [`steady`].
146pub fn note_pass(frames: usize, done: bool) {
147    let frames = if done { 0 } else { frames as i64 };
148    LAST_PASS.store(frames, std::sync::atomic::Ordering::Relaxed);
149}
150
151/// Whether compression has caught up here: off, or its last pass was done or
152/// framed at most 4 frames. Before then, giving space back would only have
153/// to be done again (SPEC_HISTORY_STORE_RECLAIM_SPACE_2026_10_23 §6).
154pub fn steady() -> bool {
155    let last = LAST_PASS.load(std::sync::atomic::Ordering::Relaxed);
156    !enabled() || (0..=4).contains(&last)
157}
158
159/// Another running srv, any build, as a sentence for the log and the Storage
160/// view; `None` when this srv is the only one. A reclaim swaps the store's
161/// file, so any open connection holds it off, not only an old build's
162/// (`filestore::reclaim`).
163pub fn other_srv() -> Option<String> {
164    let sys = scan_processes();
165    let me = std::process::id();
166    sys.processes().iter().find_map(|(pid, process)| {
167        let name = process.name().to_string_lossy().to_string();
168        let monitor = process.cmd().iter().any(|a| a.to_string_lossy() == "--crash-monitor");
169        (pid.as_u32() != me && is_srv(&name) && !monitor).then(|| format!("{name} (pid {}) is running", pid.as_u32()))
170    })
171}
172
173/// The first running srv that hasn't said it reads every frame codec, as a
174/// sentence for the log and the Storage view; `None` when all have. Prunes the
175/// readers files of processes that have exited.
176pub fn who_blocks(store_dir: &Path) -> Option<String> {
177    let sys = scan_processes();
178    let dir = readers_dir(store_dir);
179    // Prune files whose process is gone, or whose pid now belongs to another process.
180    if let Ok(entries) = std::fs::read_dir(&dir) {
181        for entry in entries.flatten() {
182            let path = entry.path();
183            let alive = path
184                .file_stem()
185                .and_then(|s| s.to_str())
186                .and_then(|s| s.parse::<u32>().ok())
187                .and_then(|pid| sys.process(sysinfo::Pid::from_u32(pid)))
188                .is_some_and(|p| is_srv(&p.name().to_string_lossy()));
189            if !alive {
190                let _ = std::fs::remove_file(&path);
191            }
192        }
193    }
194    for (pid, process) in sys.processes() {
195        let name = process.name().to_string_lossy().to_string();
196        if !is_srv(&name) || process.cmd().iter().any(|a| a.to_string_lossy() == "--crash-monitor") {
197            continue;
198        }
199        let file = dir.join(format!("{}.json", pid.as_u32()));
200        let ok = std::fs::read(&file).ok().is_some_and(|b| reads_frames(&b, process.start_time()));
201        if !ok && !keeps_its_own_store(pid.as_u32(), store_dir) {
202            return Some(blocker_sentence(&name, pid.as_u32(), process.start_time(), process.exe()));
203        }
204    }
205    None
206}
207
208/// Who blocks, for the person: the build, its pid, when it started and where it runs from. A dev or headless build left
209/// running for days is the usual blocker, and the person can only end it if they can tell which one it is.
210fn blocker_sentence(name: &str, pid: u32, started_s: u64, exe: Option<&Path>) -> String {
211    let since = chrono::DateTime::from_timestamp(started_s as i64, 0).map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string());
212    let mut facts = vec![format!("pid {pid}")];
213    if let Some(since) = since.filter(|_| started_s > 0) {
214        facts.push(format!("running since {since}"));
215    }
216    if let Some(exe) = exe {
217        facts.push(exe.display().to_string());
218    }
219    format!("{name} ({}) can't read compressed history; compression waits until it exits", facts.join(", "))
220}
221
222/// The shared transcripts folder a srv's own environment points at, or `None` when it points nowhere (no override set,
223/// or its environment couldn't be read): such a srv is taken to use the machine's own store, as every srv did before.
224/// A srv started with `AGENTMUX_HOME_OVERRIDE` or `AGENTMUX_SHARED_DIR` (every `task dev` instance and lab home) keeps its
225/// shared data, this store's twin, in a folder of its own (`registry::paths::shared_root_ignoring_deferral`, same order).
226fn store_dir_named_by(env: &[std::ffi::OsString]) -> Option<PathBuf> {
227    let var = |key: &str| {
228        env.iter().find_map(|kv| {
229            let kv = kv.to_string_lossy();
230            let (k, v) = kv.split_once('=')?;
231            (k.eq_ignore_ascii_case(key) && !v.is_empty()).then(|| PathBuf::from(v))
232        })
233    };
234    let shared = match var("AGENTMUX_HOME_OVERRIDE") {
235        Some(home) => home.join("shared"),
236        None => var("AGENTMUX_SHARED_DIR")?,
237    };
238    Some(shared.join("agents").join("transcripts"))
239}
240
241/// Whether two folder names are one folder: the same path, or the same after the system resolves links, ignoring case
242/// and separators on the systems that do.
243fn same_folder(a: &Path, b: &Path) -> bool {
244    let norm = |p: &Path| {
245        let p = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
246        let s = p.to_string_lossy().replace(std::path::MAIN_SEPARATOR, "/");
247        let s = s.trim_start_matches("//?/").trim_end_matches('/').to_string();
248        if cfg!(any(windows, target_os = "macos")) { s.to_lowercase() } else { s }
249    };
250    norm(a) == norm(b)
251}
252
253/// Whether the srv `pid` keeps its shared data in another folder than `store_dir`: it never opens this store, so it cannot
254/// be reading frames from it, and waiting for it would hold compression off for as long as it runs. A srv whose environment
255/// can't be read, or that names no folder, still counts as a reader of this store.
256fn keeps_its_own_store(pid: u32, store_dir: &Path) -> bool {
257    let id = sysinfo::Pid::from_u32(pid);
258    let mut sys = sysinfo::System::new();
259    sys.refresh_processes_specifics(
260        sysinfo::ProcessesToUpdate::Some(&[id]),
261        true,
262        sysinfo::ProcessRefreshKind::nothing().with_environ(sysinfo::UpdateKind::Always),
263    );
264    let Some(theirs) = sys.process(id).and_then(|p| store_dir_named_by(p.environ())) else { return false };
265    !same_folder(&theirs, store_dir)
266}
267
268/// Whether a readers file says its process (started at `started_s`) reads
269/// every frame codec this build writes.
270fn reads_frames(file: &[u8], started_s: u64) -> bool {
271    serde_json::from_slice::<serde_json::Value>(file).ok().is_some_and(|v| {
272        let started = v.get("started_s").and_then(|s| s.as_u64()).unwrap_or(0);
273        let codecs: Vec<i64> = v.get("codecs").and_then(|c| c.as_array()).map(|a| a.iter().filter_map(|x| x.as_i64()).collect()).unwrap_or_default();
274        started.abs_diff(started_s) <= 1 && WRITES_CODECS.iter().all(|c| codecs.contains(c))
275    })
276}
277
278/// What one pass did.
279#[derive(Debug, Default, Clone, PartialEq, Eq)]
280pub struct PassReport {
281    pub frames: usize,
282    pub codec2: usize,
283    pub raw_bytes: u64,
284    pub stored_bytes: u64,
285    pub skipped: usize,
286    /// Set when nothing was framed because a srv that can't read frames runs.
287    pub waiting: Option<String>,
288    /// Every eligible part is framed (no more work until transcripts grow).
289    pub done: bool,
290    /// The pass stopped early because another srv held the store's write lock
291    /// past the busy timeout; the next pass picks up where this one left off.
292    pub busy: bool,
293}
294
295/// The receive time of the line holding byte `offset` of a transcript, from
296/// its sidecar; `None` when the sidecar doesn't say.
297fn received_ms(store: &FileStore, zone: &str, offset: i64) -> Option<i64> {
298    let size = store.stat(zone, TSIDX).ok()??.size;
299    let read = |off: i64, len: i64| store.read_snapshot(|r| r.bytes(zone, TSIDX, off, len));
300    let stamps = crate::backend::blockcontroller::shell::stamps::stamps_for(&read, size, &[offset as u64]).ok()??;
301    stamps.first().copied().filter(|&ms| ms > 0)
302}
303
304/// One pass over the agent transcripts in `store` (at `store_dir`), framing at
305/// most `budget` frames. `skip` carries the frames found ineligible (a lost or
306/// short part) across passes, so they aren't read again and again.
307pub fn pass(store: &FileStore, store_dir: &Path, budget: usize, skip: &mut HashSet<(String, i32)>, now_ms: i64) -> Result<PassReport, StoreError> {
308    pass_with(store, &|| who_blocks(store_dir), budget, skip, now_ms)
309}
310
311/// [`pass`] with the running-process check given (tests can't depend on
312/// which AgentMux builds this machine runs).
313fn pass_with(
314    store: &FileStore,
315    blocks: &dyn Fn() -> Option<String>,
316    budget: usize,
317    skip: &mut HashSet<(String, i32)>,
318    now_ms: i64,
319) -> Result<PassReport, StoreError> {
320    let mut report = PassReport::default();
321    match pass_into(store, blocks, budget, skip, now_ms, &mut report) {
322        Ok(()) => Ok(report),
323        // Another srv held the store's write lock past the busy timeout (a loaded
324        // machine, or a long run of frames from the other srv). Nothing is lost:
325        // what this pass framed stays framed, and the next pass carries on.
326        Err(e) if is_busy(&e) => {
327            tracing::debug!(error = %e, frames = report.frames, "framer: the store is busy; the next pass carries on");
328            report.busy = true;
329            report.done = false;
330            Ok(report)
331        }
332        Err(e) => Err(e),
333    }
334}
335
336/// A pass that failed. A corrupt store is the person's to hear about, once, and asks for the rebuild
337/// ([`damage::note_corrupt`]): a pass walks every part, so it finds damage that no append or read of
338/// one agent's zone reaches, and a pass that only logged left the store damaged for days.
339pub fn note_pass_failed(e: &StoreError) {
340    note_pass_failed_in(damage::FRAMES_ZONE, e);
341}
342
343fn note_pass_failed_in(zone: &str, e: &StoreError) {
344    if !damage::note_corrupt(zone, "framer", e) {
345        tracing::warn!(error = %e, "framer: pass failed");
346    }
347}
348
349/// A store error that means "another connection holds the lock", not "something broke".
350fn is_busy(e: &StoreError) -> bool {
351    matches!(
352        e,
353        StoreError::Sqlite(rusqlite::Error::SqliteFailure(f, _))
354            if matches!(f.code, rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked)
355    )
356}
357
358/// Whole groups of a live file that lie behind its tail when it is `size` bytes long.
359fn groups_behind(size: i64) -> i64 {
360    ((size - TAIL_BYTES).max(0) / PART_BYTES) / FRAME_PARTS as i64
361}
362
363/// Whether an append that took `name` in `zone` from `old` to `new` bytes put a whole group behind the tail: the moment a
364/// block leaves the live conversation.
365fn crosses_the_boundary(zone: &str, name: &str, old: i64, new: i64) -> bool {
366    (zone.starts_with("agent:") || zone.starts_with("agent-uid:")) && kind_of(name).is_some() && groups_behind(new) > groups_behind(old)
367}
368
369static WAKE: tokio::sync::Notify = tokio::sync::Notify::const_new();
370
371/// Called after an append commits: when it pushed a group behind the live tail, the framer's loop is woken at once instead
372/// of at its next turn, so a block is compressed seconds after it leaves the live conversation. Cheap: two integer
373/// operations and a name check on every append, a wake only when a group is ready.
374pub fn appended(zone: &str, name: &str, old_size: i64, new_size: i64) {
375    if crosses_the_boundary(zone, name, old_size, new_size) {
376        WAKE.notify_one();
377    }
378}
379
380/// Resolves when an append has put a group behind a tail (see [`appended`]). A wake that came while nobody waited is kept.
381pub async fn woken() {
382    WAKE.notified().await;
383}
384
385/// How a stream of a zone is treated.
386#[derive(Clone, Copy)]
387enum Kind {
388    /// The transcript: the delta codecs apply.
389    Output,
390    /// Written beside the transcript, in step with it: framed like it, as plain zstd.
391    Sidecar,
392    /// Written once and never appended to after it is read back (an imported session file, the provider copy): no tail.
393    Final,
394}
395
396/// The streams the framer takes, by file name.
397fn kind_of(name: &str) -> Option<Kind> {
398    match name {
399        OUTPUT => Some(Kind::Output),
400        "output.tsidx" | "output.idx" | "output.consol" | "continuity.state.jsonl" => Some(Kind::Sidecar),
401        "output.provider" => Some(Kind::Final),
402        _ if name.starts_with("import/") => Some(Kind::Final),
403        _ => None,
404    }
405}
406
407/// Whether the conversation in `zone` has had no line for [`QUIET_MS`] (by its receive-time sidecar). A zone with none is
408/// not quiet: its files keep the byte tail.
409fn zone_is_quiet(store: &FileStore, zone: &str, now_ms: i64) -> bool {
410    let Ok(Some(file)) = store.stat(zone, OUTPUT) else { return false };
411    file.size > 0 && received_ms(store, zone, file.size - 1).is_some_and(|ms| now_ms - ms >= QUIET_MS)
412}
413
414/// The groups to frame: runs of consecutive part rows cut into groups of at most `step`. A group shorter than `step` is
415/// taken only when `quiet`: a live file waits for a whole group.
416fn groups_of(raw: &[i32], step: i32, quiet: bool) -> Vec<(i32, i32)> {
417    let mut out = Vec::new();
418    let mut i = 0;
419    while i < raw.len() {
420        let mut j = i;
421        while j + 1 < raw.len() && raw[j + 1] == raw[j] + 1 && (j + 1 - i) < step as usize {
422            j += 1;
423        }
424        let count = (j - i + 1) as i32;
425        if count == step || quiet {
426            out.push((raw[i], count));
427        }
428        i = j + 1;
429    }
430    out
431}
432
433/// Frame what one file has behind its tail. `true` when the pass's budget is spent.
434#[allow(clippy::too_many_arguments)]
435fn frame_file(
436    store: &FileStore,
437    zone: &str,
438    name: &str,
439    size: i64,
440    quiet: bool,
441    codec: i64,
442    skip: &mut HashSet<(String, i32)>,
443    report: &mut PassReport,
444    budget: usize,
445) -> Result<bool, StoreError> {
446    if size <= 0 {
447        return Ok(false);
448    }
449    // The file's last part takes appends and never goes into a frame; a live file also keeps its tail.
450    let last_part = ((size - 1) / PART_BYTES) as i32;
451    let below = if quiet { last_part } else { ((size - TAIL_BYTES).max(0) / PART_BYTES) as i32 };
452    if below <= 0 {
453        return Ok(false);
454    }
455    let raw = store.raw_parts_below(zone, name, below)?;
456    // A skipped group is remembered by (zone, first part); another stream of the same zone has its own name in the key.
457    let key_zone = if name == OUTPUT { zone.to_string() } else { format!("{zone}/{name}") };
458    for (first, count) in groups_of(&raw, FRAME_PARTS, quiet) {
459        let key = (key_zone.clone(), first);
460        if skip.contains(&key) {
461            continue;
462        }
463        match store.frame_parts(zone, name, first, count, codec)? {
464            FrameOutcome::Framed { raw, stored, codec } => {
465                report.frames += 1;
466                report.raw_bytes += raw as u64;
467                report.stored_bytes += stored as u64;
468                report.codec2 += usize::from(codec == CODEC_DELTAS || codec == CODEC_DELTA_API);
469            }
470            FrameOutcome::Skipped(why) => {
471                tracing::debug!(zone = %zone, name, first, why, "framer: skipped");
472                report.skipped += 1;
473                skip.insert(key);
474            }
475        }
476        if report.frames >= budget {
477            return Ok(true);
478        }
479        // Between frames, with no lock held: SQLite's busy wait is a sleep and retry, not a queue, so a writer that frames
480        // back to back keeps the lock from another srv's writes (and its framer) for as long as it runs, past their busy
481        // timeout.
482        std::thread::sleep(FRAME_PAUSE);
483    }
484    Ok(false)
485}
486
487/// The body of [`pass_with`], filling `report` as it goes so a pass that fails
488/// part-way still reports the frames it wrote.
489fn pass_into(
490    store: &FileStore,
491    blocks: &dyn Fn() -> Option<String>,
492    budget: usize,
493    skip: &mut HashSet<(String, i32)>,
494    now_ms: i64,
495    report: &mut PassReport,
496) -> Result<(), StoreError> {
497    if let Some(who) = blocks() {
498        report.waiting = Some(who);
499        return Ok(());
500    }
501    // Stamp first, then look again: a build that opened the store before the
502    // stamp is a running process now, and one that starts after it refuses
503    // the store. With the deltas on the framer may write codec 3, which a build
504    // that reads only codecs 1 and 2 would take for damage, so the store is
505    // stamped `GLOBAL_TRANSCRIPT_STORE_API_DELTAS_VERSION` (4) and such a build
506    // refuses it; with them off only codec 1 is written and 3 is enough.
507    let deltas = deltas_enabled();
508    store.stamp_frames_version(if deltas {
509        crate::backend::storage::filestore::GLOBAL_TRANSCRIPT_STORE_API_DELTAS_VERSION
510    } else {
511        crate::backend::storage::filestore::GLOBAL_TRANSCRIPT_STORE_FRAMES_VERSION
512    })?;
513    if let Some(who) = blocks() {
514        report.waiting = Some(who);
515        return Ok(());
516    }
517    // Asking for codec 3 is codec 2 that also takes the lines that carry an `api_message_id`: a frame with none of them
518    // is still codec 2, and a frame with no delta line at all is codec 1.
519    let output_codec = if deltas { CODEC_DELTA_API } else { CODEC_ZSTD };
520    let mut zones = store.zone_ids_with_prefix("agent:")?;
521    zones.extend(store.zone_ids_with_prefix("agent-uid:")?);
522    for zone in zones {
523        let quiet_zone = zone_is_quiet(store, &zone, now_ms);
524        for file in store.list_files(&zone)? {
525            let Some(kind) = kind_of(&file.name) else { continue };
526            let quiet = match kind {
527                Kind::Final => true,
528                Kind::Output | Kind::Sidecar => quiet_zone,
529            };
530            let codec = if matches!(kind, Kind::Output) { output_codec } else { CODEC_ZSTD };
531            if frame_file(store, &zone, &file.name, file.size, quiet, codec, skip, report, budget)? {
532                return Ok(());
533            }
534        }
535    }
536    report.done = true;
537    Ok(())
538}
539
540#[cfg(test)]
541#[path = "framer_tests.rs"]
542mod tests;