Skip to main content

agentmux_srv_core/backend/transcript/
consol.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The map a swap leaves in `output.consol`, and what reads it: how a position in the old file
5//! (a counted line, or a byte) is the same position in the new one
6//! (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 9).
7//!
8//! A swap drops only fragment lines and blank lines, writes interrupted lines in place of
9//! fragments and copies everything else as it was, so the whole change is a list of runs: where a
10//! run of old lines (or bytes) stood, how many there were, and how many take their place. Inside a
11//! kept line a position moves exactly; inside a run it moves to where the run started, so a reader
12//! that was in the middle of dropped fragments sees the interrupted line, or the next kept line,
13//! and never a piece of a line.
14
15use serde_json::{json, Value};
16
17use crate::backend::storage::filestore::FileStore;
18
19/// The file the swaps are recorded in.
20pub const CONSOL: &str = "output.consol";
21
22/// A run of counted old lines the compact form dropped, and what stands in their place.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Run {
25    /// The first dropped line, as a counted line number of the old file.
26    pub old_line: u64,
27    pub dropped: u64,
28    /// Lines written after the run in place of its fragments (interrupted replies).
29    pub synthesized: u64,
30}
31
32/// The same run in bytes, which also holds the blank lines that were not carried over.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct ByteRun {
35    pub old_at: i64,
36    pub old_len: i64,
37    /// Bytes written in its place.
38    pub new_len: i64,
39}
40
41/// One swap's map: from the file of generation `gen_before` to the file of `gen_after`.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Map {
44    pub gen_before: String,
45    pub gen_after: String,
46    pub runs: Vec<Run>,
47    pub byte_runs: Vec<ByteRun>,
48}
49
50impl Map {
51    /// The map line as it is written to `output.consol`.
52    pub fn to_json(&self) -> Value {
53        let runs: Vec<[u64; 3]> = self.runs.iter().map(|r| [r.old_line, r.dropped, r.synthesized]).collect();
54        let bytes: Vec<[i64; 3]> = self.byte_runs.iter().map(|r| [r.old_at, r.old_len, r.new_len]).collect();
55        json!({ "k": "map", "gen_before": self.gen_before, "gen_after": self.gen_after, "runs": runs, "bytes": bytes })
56    }
57
58    /// A map line of `output.consol`; `None` for any other line or one that does not parse.
59    pub fn from_json(v: &Value) -> Option<Self> {
60        if v.get("k").and_then(Value::as_str) != Some("map") {
61            return None;
62        }
63        let triples = |key: &str| -> Option<Vec<[i64; 3]>> {
64            v.get(key)?.as_array()?.iter().map(|t| {
65                let t = t.as_array()?;
66                Some([t.first()?.as_i64()?, t.get(1)?.as_i64()?, t.get(2)?.as_i64()?])
67            }).collect()
68        };
69        Some(Self {
70            gen_before: v.get("gen_before")?.as_str()?.to_string(),
71            gen_after: v.get("gen_after")?.as_str()?.to_string(),
72            runs: triples("runs")?.into_iter().map(|[a, b, c]| Run { old_line: a as u64, dropped: b as u64, synthesized: c as u64 }).collect(),
73            byte_runs: triples("bytes").unwrap_or_default().into_iter().map(|[a, b, c]| ByteRun { old_at: a, old_len: b, new_len: c }).collect(),
74        })
75    }
76
77    /// Where counted line `old` of the old file is in the new one (a position counts the lines before
78    /// it, so a line count translates the same way).
79    pub fn line(&self, old: u64) -> u64 {
80        let mut delta: i64 = 0;
81        for r in &self.runs {
82            if r.old_line + r.dropped <= old {
83                delta += r.synthesized as i64 - r.dropped as i64;
84            } else {
85                if r.old_line < old {
86                    // Inside the run: where it started.
87                    return (r.old_line as i64 + delta).max(0) as u64;
88                }
89                break;
90            }
91        }
92        (old as i64 + delta).max(0) as u64
93    }
94
95    /// Where byte `old` of the old file is in the new one.
96    pub fn byte(&self, old: i64) -> i64 {
97        let mut delta: i64 = 0;
98        for r in &self.byte_runs {
99            if r.old_at + r.old_len <= old {
100                delta += r.new_len - r.old_len;
101            } else {
102                if r.old_at < old {
103                    return r.old_at + delta;
104                }
105                break;
106            }
107        }
108        (old + delta).max(0)
109    }
110}
111
112/// The swaps recorded for `zone`, oldest first. A line that is not a map is skipped. Empty when there
113/// are none or the record cannot be read.
114pub fn maps(fs: &FileStore, zone: &str) -> Vec<Map> {
115    let Ok(Some(state)) = fs.line_state(zone, CONSOL) else { return Vec::new() };
116    let Ok(raw) = fs.read_bytes_db(zone, CONSOL, 0, state.size) else { return Vec::new() };
117    String::from_utf8_lossy(&raw).lines().filter(|l| l.contains("\"k\":\"map\"")).filter_map(|l| serde_json::from_str::<Value>(l).ok()).filter_map(|v| Map::from_json(&v)).collect()
118}
119
120/// The swaps that took the file from generation `from` to `to`, in order, or `None` when the record
121/// does not hold an unbroken chain (a swap too old to be kept, or a rewrite that was no swap).
122pub fn chain(all: &[Map], from: &str, to: &str) -> Option<Vec<Map>> {
123    let mut out = Vec::new();
124    let mut at = from.to_string();
125    while at != to {
126        let next = all.iter().find(|m| m.gen_before == at)?;
127        at = next.gen_after.clone();
128        out.push(next.clone());
129        if out.len() > 64 {
130            return None;
131        }
132    }
133    Some(out)
134}
135
136/// A counted line number of the file of generation `from`, in the file of generation `to`.
137pub fn translate_line(all: &[Map], from: &str, to: &str, line: u64) -> Option<u64> {
138    Some(chain(all, from, to)?.iter().fold(line, |l, m| m.line(l)))
139}
140
141/// A byte offset of the file of generation `from`, in the file of generation `to`.
142pub fn translate_byte(all: &[Map], from: &str, to: &str, byte: i64) -> Option<i64> {
143    Some(chain(all, from, to)?.iter().fold(byte, |b, m| m.byte(b)))
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    fn map(gen_before: &str, gen_after: &str) -> Map {
151        Map {
152            gen_before: gen_before.into(),
153            gen_after: gen_after.into(),
154            // Lines 2 to 4 dropped (three fragments), then lines 10 to 11 dropped and one interrupted line in their place.
155            runs: vec![Run { old_line: 2, dropped: 3, synthesized: 0 }, Run { old_line: 10, dropped: 2, synthesized: 1 }],
156            // 100 bytes at 20 dropped; 40 bytes at 200 replaced by 25.
157            byte_runs: vec![ByteRun { old_at: 20, old_len: 100, new_len: 0 }, ByteRun { old_at: 200, old_len: 40, new_len: 25 }],
158        }
159    }
160
161    #[test]
162    fn a_kept_line_moves_exactly_and_a_dropped_one_goes_to_where_its_run_began() {
163        let m = map("a", "b");
164        assert_eq!([0, 1, 2].map(|l| m.line(l)), [0, 1, 2], "before the first run");
165        assert_eq!(m.line(3), 2, "inside a run: where it began");
166        assert_eq!(m.line(4), 2);
167        assert_eq!(m.line(5), 2, "the first line after the run");
168        assert_eq!(m.line(9), 6);
169        assert_eq!(m.line(10), 7, "the start of the second run");
170        assert_eq!(m.line(11), 7, "inside it");
171        assert_eq!(m.line(12), 8, "after it: two dropped, one written");
172        assert_eq!(m.line(20), 16);
173        assert_eq!([20, 120, 119, 121, 200, 240, 300].map(|b| m.byte(b)), [20, 20, 20, 21, 100, 125, 185]);
174    }
175
176    #[test]
177    fn a_map_survives_its_json_and_other_lines_are_not_maps() {
178        let m = map("a", "b");
179        assert_eq!(Map::from_json(&m.to_json()), Some(m));
180        assert_eq!(Map::from_json(&json!({ "k": "done", "gen_before": "a" })), None);
181        assert_eq!(Map::from_json(&json!({ "k": "map", "gen_before": "a", "gen_after": "b", "runs": [[1, 2]] })), None, "a short triple is no map");
182    }
183
184    #[test]
185    fn positions_cross_several_swaps_and_a_broken_chain_is_not_guessed() {
186        let all = [map("a", "b"), map("b", "c")];
187        assert_eq!(translate_line(&all, "a", "a", 12), Some(12), "the same file: no change");
188        assert_eq!(translate_line(&all, "a", "b", 12), Some(8));
189        assert_eq!(translate_line(&all, "a", "c", 20), Some(map("a", "b").line(map("a", "b").line(20))));
190        assert_eq!(translate_line(&all, "z", "c", 5), None);
191        assert_eq!(translate_line(&all[1..], "a", "c", 5), None, "a swap in the chain is missing");
192        assert_eq!(translate_byte(&all, "b", "c", 300), Some(map("b", "c").byte(300)));
193    }
194}