Skip to main content

agentmux_srv_core/backend/transcript/
compact.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The compact form of a conversation's transcript lines
5//! (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 2).
6//!
7//! The compact form is the store's existing line format **minus the streaming fragments**, and it is
8//! lossless: every other line is kept byte for byte. The only lines this module ever drops are
9//! `stream_event` lines of a message whose complete `assistant` lines hold every block those
10//! fragments reassemble to. A reply that was cut off has fragments and no complete line; its
11//! fragments are reassembled into one `assistant` line marked `interrupted`, with the text and tool
12//! input received so far, so nothing a person could see is lost.
13//!
14//! * **Keep by default.** [`DROP_RULES`] names what may be dropped; a line kind it does not name is
15//!   kept. A new CLI line kind is never lost by an omission. A stream event this module cannot
16//!   prove (an unknown block or delta kind, a message it never saw start, a fragment that differs
17//!   from the complete line) is kept as it is and counted, never guessed at.
18//! * **Replay lines stay.** A stored `isReplay` line is either the echo of a turn srv wrote (dropped
19//!   before it is stored, in `stdout_reader`, with the ledger only the write path has) or a frame of
20//!   the CLI's own, such as a local command's output, which must stay. Nothing in a stored line tells
21//!   the two apart, so the compact form keeps every one.
22//! * **Pure.** No I/O and no clock: lines in, a [`Plan`] out. [`verify`] re-checks a result against
23//!   its input with its own, separate reassembly (checks L1 to L3 of the spec), and [`no_fragments`]
24//!   is check L4. Nothing calls this module yet.
25
26use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
27
28use serde_json::{json, Map, Value};
29
30/// What a drop rule needs before it may drop a line.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Requires {
33    /// The line belongs to a message every block of which is in a complete line of the same window,
34    /// or whose fragments are closed by a turn boundary and are reassembled into an interrupted line.
35    CompleteOrClosedMessage,
36}
37
38/// A line kind the compact form may drop, and what it needs first.
39#[derive(Debug, Clone, Copy)]
40pub struct DropRule {
41    pub name: &'static str,
42    /// The `type` field of the line.
43    pub line_type: &'static str,
44    pub requires: Requires,
45}
46
47/// The whole list of what may be dropped. Anything not named here is kept.
48pub const DROP_RULES: &[DropRule] = &[DropRule { name: "stream_event_of_complete_message", line_type: "stream_event", requires: Requires::CompleteOrClosedMessage }];
49
50/// What to do with one input line.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum Action {
53    Keep,
54    Drop,
55}
56
57/// Whether a window of lines ends the zone's stream, or is only a slice of it.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum WindowEnd {
60    /// More lines may follow: a message with an unmatched block and no turn boundary yet is pending,
61    /// so its fragments stay.
62    Open,
63    /// Nothing follows (the end of the file, or a recovery after a crash): a message still without
64    /// a complete line is interrupted.
65    Final,
66}
67
68/// A line written in place of fragments: the reassembled interrupted reply.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct Synth {
71    /// The input line it follows (the last fragment of its message).
72    pub after: usize,
73    pub message_id: String,
74    pub line: String,
75}
76
77/// Counts of what a plan did, for the migration's report. No content.
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct Stats {
80    pub lines: usize,
81    pub kept: usize,
82    pub dropped_fragments: usize,
83    pub interrupted_lines: usize,
84    /// Fragments kept because their message cannot be proven (an unknown kind, or they differ from the complete line).
85    pub unproven_fragments: usize,
86    /// The same fragments, by why their message could not be proven.
87    pub unproven_by_cause: BTreeMap<&'static str, usize>,
88    /// Fragments kept because their message may still get a complete line (an open window).
89    pub pending_fragments: usize,
90    /// Fragments kept because no message start was seen for them.
91    pub orphan_fragments: usize,
92    /// The event and delta kinds this module does not reassemble, by name (`event:<type>`, `delta:<type>`), each with the
93    /// number of messages that named it. Protocol names only, no content.
94    pub unknown_kinds: BTreeMap<String, usize>,
95}
96
97impl Stats {
98    /// Add the counts of another window to these.
99    pub fn absorb(&mut self, s: &Stats) {
100        self.lines += s.lines;
101        self.kept += s.kept;
102        self.dropped_fragments += s.dropped_fragments;
103        self.interrupted_lines += s.interrupted_lines;
104        self.unproven_fragments += s.unproven_fragments;
105        for (why, n) in &s.unproven_by_cause {
106            *self.unproven_by_cause.entry(why).or_default() += n;
107        }
108        self.pending_fragments += s.pending_fragments;
109        self.orphan_fragments += s.orphan_fragments;
110        for (kind, n) in &s.unknown_kinds {
111            // Bounded: a stream cannot make the report grow.
112            if self.unknown_kinds.len() < 32 || self.unknown_kinds.contains_key(kind) {
113                *self.unknown_kinds.entry(kind.clone()).or_default() += n;
114            }
115        }
116    }
117}
118
119/// The result of planning one window of lines.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Plan {
122    pub actions: Vec<Action>,
123    pub synth: Vec<Synth>,
124    pub stats: Stats,
125}
126
127impl Plan {
128    /// The compact lines: kept lines unchanged, in order, with each interrupted line after the last
129    /// fragment it replaces.
130    pub fn apply<S: AsRef<str>>(&self, old: &[S]) -> Vec<String> {
131        let mut out = Vec::with_capacity(old.len());
132        let mut synth = self.synth.iter().peekable();
133        for (i, line) in old.iter().enumerate() {
134            if self.actions[i] == Action::Keep {
135                out.push(line.as_ref().to_string());
136            }
137            while let Some(s) = synth.next_if(|s| s.after == i) {
138                out.push(s.line.clone());
139            }
140        }
141        out
142    }
143
144    /// For each line [`Self::apply`] makes, the index of the old line it stands at: itself for a kept
145    /// line, the last fragment it replaces for an interrupted line.
146    pub fn sources(&self) -> Vec<usize> {
147        let mut out = Vec::with_capacity(self.actions.len());
148        let mut synth = self.synth.iter().peekable();
149        for (i, action) in self.actions.iter().enumerate() {
150            if *action == Action::Keep {
151                out.push(i);
152            }
153            while synth.next_if(|s| s.after == i).is_some() {
154                out.push(i);
155            }
156        }
157        out
158    }
159}
160
161/// A block as the stream built it.
162#[derive(Debug, Clone, Default)]
163struct StreamBlock {
164    start: Value,
165    kind: String,
166    text: String,
167    thinking: String,
168    signature: String,
169    partial_json: String,
170    /// A delta or block kind this module does not reassemble.
171    unknown: bool,
172    /// How many deltas the stream sent for it (a block that came whole, in its start event, has none).
173    deltas: usize,
174    /// The citations it received, in order. They are not rebuilt: only a complete block can carry them, and it must carry
175    /// these exactly.
176    citations: Vec<Value>,
177}
178
179impl StreamBlock {
180    fn new(start: &Value) -> Self {
181        let kind = start.get("type").and_then(Value::as_str).unwrap_or("").to_string();
182        let unknown = !matches!(kind.as_str(), "text" | "thinking" | "tool_use" | "server_tool_use" | "mcp_tool_use");
183        let take = |k: &str| start.get(k).and_then(Value::as_str).unwrap_or("").to_string();
184        StreamBlock {
185            text: if kind == "text" { take("text") } else { String::new() },
186            thinking: if kind == "thinking" { take("thinking") } else { String::new() },
187            signature: if kind == "thinking" { take("signature") } else { String::new() },
188            start: start.clone(),
189            kind,
190            unknown,
191            partial_json: String::new(),
192            deltas: 0,
193            citations: Vec::new(),
194        }
195    }
196
197    /// The tool input the stream carried: `{}` when there was no delta, the parsed value when it parses.
198    fn input(&self) -> Option<Value> {
199        if self.partial_json.is_empty() {
200            return Some(Value::Object(Map::new()));
201        }
202        serde_json::from_str(&self.partial_json).ok()
203    }
204
205    /// Whether `complete` (a content block of a complete line) is this block.
206    fn matches(&self, complete: &Value) -> bool {
207        // A block of a kind this module does not know, with no delta, came whole in its start event: it is the complete block
208        // when the two are equal. One with a delta of an unknown kind has content that was not reassembled: not provable.
209        if self.unknown {
210            return self.deltas == 0 && complete == &self.start;
211        }
212        if complete.get("type").and_then(Value::as_str) != Some(self.kind.as_str()) {
213            return false;
214        }
215        let s = |k: &str| complete.get(k).and_then(Value::as_str);
216        match self.kind.as_str() {
217            // A block that received citations is the complete block only when that one carries the same citations.
218            "text" => s("text") == Some(self.text.as_str()) && (self.citations.is_empty() || complete.get("citations").and_then(Value::as_array) == Some(&self.citations)),
219            "thinking" => s("thinking") == Some(self.thinking.as_str()) && (self.signature.is_empty() || s("signature") == Some(self.signature.as_str())),
220            "tool_use" | "server_tool_use" | "mcp_tool_use" => {
221                s("id") == self.start.get("id").and_then(Value::as_str)
222                    && s("name") == self.start.get("name").and_then(Value::as_str)
223                    && self.input().is_some_and(|i| complete.get("input") == Some(&i))
224            }
225            _ => false,
226        }
227    }
228
229    /// The block as an `assistant` line carries it.
230    fn as_content(&self) -> Value {
231        match self.kind.as_str() {
232            "text" => json!({ "type": "text", "text": self.text }),
233            "thinking" => {
234                let mut b = json!({ "type": "thinking", "thinking": self.thinking });
235                if !self.signature.is_empty() {
236                    b["signature"] = Value::String(self.signature.clone());
237                }
238                b
239            }
240            _ => {
241                let mut b = json!({
242                    "type": "tool_use",
243                    "id": self.start.get("id").cloned().unwrap_or(Value::Null),
244                    "name": self.start.get("name").cloned().unwrap_or(Value::Null),
245                });
246                match self.input() {
247                    Some(i) => b["input"] = i,
248                    None => {
249                        b["input"] = Value::Object(Map::new());
250                        b["partial_input_json"] = Value::String(self.partial_json.clone());
251                    }
252                }
253                b
254            }
255        }
256    }
257}
258
259#[derive(Debug, Default)]
260struct Msg {
261    fragment_lines: Vec<usize>,
262    blocks: BTreeMap<u64, StreamBlock>,
263    /// The content blocks of every complete `assistant` line of this message id.
264    complete: Vec<Value>,
265    has_complete: bool,
266    /// A fragment this module cannot reassemble, or a message of another role.
267    unproven: bool,
268    /// The first reason it became unproven.
269    why: Option<&'static str>,
270    closed: bool,
271    /// The event and delta kinds it named that this module does not reassemble (`event:<type>`, `delta:<type>`).
272    kinds: BTreeSet<String>,
273    /// Its `message_stop` fragment was seen.
274    stopped: bool,
275    session_id: Option<Value>,
276    parent: Option<Value>,
277}
278
279fn field<'a>(v: &'a Value, path: &[&str]) -> Option<&'a Value> {
280    path.iter().try_fold(v, |v, k| v.get(*k))
281}
282
283fn line_type(v: &Value) -> &str {
284    v.get("type").and_then(Value::as_str).unwrap_or("")
285}
286
287/// Whether a line is a turn boundary: after one, no complete line of an earlier message follows.
288fn is_boundary(v: &Value) -> bool {
289    match line_type(v) {
290        "result" => true,
291        "system" => v.get("subtype").and_then(Value::as_str) == Some("init"),
292        _ => false,
293    }
294}
295
296/// The last line after which no reply is in flight: every message that has a fragment by then has its complete
297/// line and its closing fragments, was taken over by a newer message on its stream, or a turn boundary closed it. A window cut there splits no message between two windows. It is the cut for
298/// a stretch so long that no turn boundary comes within the window limit. `None` when no line qualifies.
299pub fn last_quiet_line<S: AsRef<str>>(lines: &[S]) -> Option<usize> {
300    let mut scan = Scan::default();
301    let mut open: HashSet<String> = HashSet::new();
302    let mut last = None;
303    for (i, raw) in lines.iter().enumerate() {
304        if scan.line(i, raw.as_ref()) == Seen::Boundary {
305            open.clear();
306        } else {
307            if let Some(id) = scan.superseded.take() {
308                open.remove(&id);
309            }
310            if let Some(id) = scan.touched.take() {
311                // Its complete line comes before its closing fragments (`message_delta`, `message_stop`), so a
312                // reply is in flight until both are seen.
313                let m = &scan.msgs[&id];
314                if !m.fragment_lines.is_empty() && !(m.has_complete && m.stopped) {
315                    open.insert(id);
316                } else {
317                    open.remove(&id);
318                }
319            }
320        }
321        if open.is_empty() {
322            last = Some(i);
323        }
324    }
325    last
326}
327
328/// Whether a stored line is a turn boundary (a `result`, or a session `init`), as the planner reads it.
329pub fn is_turn_boundary(line: &str) -> bool {
330    if !line.starts_with('{') {
331        return false;
332    }
333    serde_json::from_str::<Value>(line).is_ok_and(|v| is_boundary(&v))
334}
335
336impl Msg {
337    /// Take one fragment event of this message (its line is already recorded).
338    fn take_event(&mut self, ev: &str, event: &Value) {
339        let index = event.get("index").and_then(Value::as_u64);
340        match ev {
341            "content_block_start" => match (index, event.get("content_block")) {
342                (Some(ix), Some(b)) => {
343                    self.blocks.insert(ix, StreamBlock::new(b));
344                }
345                _ => self.mark_unproven("block_start_without_index_or_block"),
346            },
347            "content_block_delta" => self.take_delta(index, event.get("delta")),
348            "message_stop" => self.stopped = true,
349            "content_block_stop" | "message_delta" | "ping" => {}
350            // An error carries what no complete line holds.
351            "error" => self.mark_unproven("error_event"),
352            // Any other event adds no block of its own: the proof that the complete line holds the reply is the blocks, so
353            // the kind is named for the report and does not keep the message.
354            other => self.name_kind(format!("event:{other}")),
355        }
356    }
357
358    fn name_kind(&mut self, name: String) {
359        // Bounded: a stream cannot make the report grow.
360        if self.kinds.len() < 8 {
361            self.kinds.insert(name.chars().take(64).collect());
362        }
363    }
364
365    fn mark_unproven(&mut self, why: &'static str) {
366        self.unproven = true;
367        self.why.get_or_insert(why);
368    }
369
370    fn take_delta(&mut self, index: Option<u64>, delta: Option<&Value>) {
371        let (Some(ix), Some(delta)) = (index, delta) else {
372            self.mark_unproven("delta_without_index_or_body");
373            return;
374        };
375        let Some(b) = self.blocks.get_mut(&ix) else {
376            self.mark_unproven("delta_for_a_block_never_started");
377            return;
378        };
379        let s = |k: &str| delta.get(k).and_then(Value::as_str).unwrap_or("");
380        b.deltas += 1;
381        match (delta.get("type").and_then(Value::as_str), b.kind.as_str()) {
382            (Some("text_delta"), "text") => b.text.push_str(s("text")),
383            // The citations of a text block are on its complete block, which must carry the same ones. A reply cut off has no
384            // complete block to carry them, so a block with citations is never rebuilt (see `fate`).
385            (Some("citations_delta"), "text") => b.citations.push(delta.get("citation").cloned().unwrap_or(Value::Null)),
386            (Some("thinking_delta"), "thinking") => b.thinking.push_str(s("thinking")),
387            (Some("signature_delta"), "thinking") => b.signature.push_str(s("signature")),
388            (Some("input_json_delta"), "tool_use" | "server_tool_use" | "mcp_tool_use") => b.partial_json.push_str(s("partial_json")),
389            (kind, _) => {
390                b.unknown = true;
391                let name = format!("delta:{}", kind.unwrap_or(""));
392                self.name_kind(name);
393                self.mark_unproven("unknown_delta_kind");
394            }
395        }
396    }
397}
398
399/// What kind of line [`Scan::line`] took.
400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
401enum Seen {
402    Fragment,
403    /// A complete `assistant` line.
404    Complete,
405    /// A turn boundary.
406    Boundary,
407    Other,
408}
409
410/// What one pass over a window learned: the messages its fragments and complete lines name.
411#[derive(Default)]
412struct Scan {
413    msgs: HashMap<String, Msg>,
414    order: Vec<String>,
415    /// The message a stream is on, per parent tool use ("" for the main stream).
416    current: HashMap<String, Option<String>>,
417    /// Fragments that belong to no message seen to start.
418    orphan: Vec<usize>,
419    /// The message the last line named, for [`last_quiet_line`].
420    touched: Option<String>,
421    /// The message the last line took the stream away from (a new message started on the same stream).
422    superseded: Option<String>,
423}
424
425impl Scan {
426    fn msg(&mut self, id: &str) -> &mut Msg {
427        if !self.msgs.contains_key(id) {
428            self.order.push(id.to_string());
429        }
430        self.msgs.entry(id.to_string()).or_default()
431    }
432
433    /// Take line `i`, and say what kind of line it was.
434    fn line(&mut self, i: usize, raw: &str) -> Seen {
435        // Cheap reject: a line that is not a JSON object is only ever kept.
436        if !raw.starts_with('{') {
437            return Seen::Other;
438        }
439        let Ok(v) = serde_json::from_str::<Value>(raw) else { return Seen::Other };
440        let key = match v.get("parent_tool_use_id") {
441            Some(Value::String(s)) => s.clone(),
442            _ => String::new(),
443        };
444        match line_type(&v) {
445            "stream_event" => {
446                self.fragment(i, &v, key);
447                Seen::Fragment
448            }
449            "assistant" => {
450                self.complete_line(&v);
451                Seen::Complete
452            }
453            _ if is_boundary(&v) => {
454                for m in self.msgs.values_mut() {
455                    m.closed = true;
456                }
457                self.current.clear();
458                Seen::Boundary
459            }
460            _ => Seen::Other,
461        }
462    }
463
464    fn fragment(&mut self, i: usize, v: &Value, key: String) {
465        let Some(event) = v.get("event") else {
466            self.orphan.push(i);
467            return;
468        };
469        let ev = event.get("type").and_then(Value::as_str).unwrap_or("");
470        if ev == "message_start" {
471            self.message_start(i, v, event, key);
472            return;
473        }
474        let Some(id) = self.current.get(&key).cloned().flatten() else {
475            self.orphan.push(i);
476            return;
477        };
478        let Some(m) = self.msgs.get_mut(&id) else {
479            self.orphan.push(i);
480            return;
481        };
482        m.fragment_lines.push(i);
483        m.take_event(ev, event);
484        self.touched = Some(id);
485    }
486
487    fn message_start(&mut self, i: usize, v: &Value, event: &Value, key: String) {
488        let id = field(event, &["message", "id"]).and_then(Value::as_str).map(str::to_string);
489        let previous = self.current.insert(key, id.clone()).flatten();
490        self.superseded = previous.filter(|p| Some(p) != id.as_ref());
491        let Some(id) = id else {
492            self.orphan.push(i);
493            return;
494        };
495        self.touched = Some(id.clone());
496        let m = self.msg(&id);
497        m.fragment_lines.push(i);
498        m.session_id = m.session_id.take().or_else(|| v.get("session_id").cloned());
499        m.parent = m.parent.take().or_else(|| v.get("parent_tool_use_id").cloned());
500        // A message of another role (a user turn carrying tool results) is not an assistant reply.
501        if field(event, &["message", "role"]).and_then(Value::as_str) != Some("assistant") {
502            m.mark_unproven("message_of_another_role");
503        }
504    }
505
506    fn complete_line(&mut self, v: &Value) {
507        if v.get("partial").and_then(Value::as_bool) == Some(true) {
508            return;
509        }
510        let Some(id) = field(v, &["message", "id"]).and_then(Value::as_str) else { return };
511        self.touched = Some(id.to_string());
512        let m = self.msg(id);
513        m.has_complete = true;
514        if let Some(Value::Array(blocks)) = field(v, &["message", "content"]) {
515            m.complete.extend(blocks.iter().cloned());
516        }
517    }
518}
519
520/// What becomes of one message's fragments.
521enum Fate {
522    /// Kept whole: a block or delta kind this module cannot reassemble, or nothing to prove.
523    Unproven(&'static str),
524    /// Kept for now: the message may still get a complete line.
525    Pending,
526    /// Dropped, with the interrupted line that replaces them when some block has no complete counterpart.
527    Drop(Option<String>),
528}
529
530fn fate(id: &str, m: &Msg, end: WindowEnd) -> Fate {
531    if m.unproven {
532        return Fate::Unproven(m.why.unwrap_or("unproven"));
533    }
534    if m.blocks.is_empty() {
535        return Fate::Unproven("no_blocks");
536    }
537    // Match every stream block to a block of a complete line, each complete block once.
538    let mut used = vec![false; m.complete.len()];
539    let mut unmatched: Vec<&StreamBlock> = Vec::new();
540    for b in m.blocks.values() {
541        match m.complete.iter().enumerate().find(|(j, c)| !used[*j] && b.matches(c)) {
542            Some((j, _)) => used[j] = true,
543            None => unmatched.push(b),
544        }
545    }
546    if unmatched.is_empty() {
547        // Blocks with nothing to match and no complete line cannot happen; keep what we do not understand.
548        return if m.has_complete { Fate::Drop(None) } else { Fate::Unproven("no_complete_line") };
549    }
550    if !m.closed && end == WindowEnd::Open {
551        return Fate::Pending;
552    }
553    if unmatched.iter().any(|b| b.unknown || !matches!(b.kind.as_str(), "text" | "thinking" | "tool_use")) {
554        return Fate::Unproven("cut_off_block_of_unknown_kind");
555    }
556    if unmatched.iter().any(|b| !b.citations.is_empty()) {
557        return Fate::Unproven("cut_off_block_with_citations");
558    }
559    // An event kind that was only named has no block to rebuild, and nothing says it holds nothing the reply needs.
560    if !m.kinds.is_empty() {
561        return Fate::Unproven("cut_off_message_with_unknown_event");
562    }
563    Fate::Drop(Some(interrupted_line(id, m, &unmatched)))
564}
565
566/// The `assistant` line of a reply that was cut off: the blocks its fragments built and no complete line holds.
567fn interrupted_line(id: &str, m: &Msg, unmatched: &[&StreamBlock]) -> String {
568    let content: Vec<Value> = unmatched.iter().map(|b| b.as_content()).collect();
569    let mut line = json!({
570        "type": "assistant",
571        "interrupted": true,
572        "message": { "id": id, "type": "message", "role": "assistant", "content": content, "stop_reason": Value::Null },
573    });
574    if let Some(s) = &m.session_id {
575        line["session_id"] = s.clone();
576    }
577    if let Some(p) = &m.parent {
578        line["parent_tool_use_id"] = p.clone();
579    }
580    line.to_string()
581}
582
583/// Plan one window of lines (each one JSON line, without its newline). `end` says whether more lines follow.
584pub fn plan_window<S: AsRef<str>>(lines: &[S], end: WindowEnd) -> Plan {
585    let mut scan = Scan::default();
586    for (i, raw) in lines.iter().enumerate() {
587        let _ = scan.line(i, raw.as_ref());
588    }
589    let mut actions = vec![Action::Keep; lines.len()];
590    let mut stats = Stats { lines: lines.len(), orphan_fragments: scan.orphan.len(), ..Stats::default() };
591    let mut synth = Vec::new();
592    for id in &scan.order {
593        let m = &scan.msgs[id];
594        let n = m.fragment_lines.len();
595        if n == 0 {
596            continue;
597        }
598        for kind in &m.kinds {
599            *stats.unknown_kinds.entry(kind.clone()).or_default() += 1;
600        }
601        match fate(id, m, end) {
602            Fate::Unproven(why) => {
603                stats.unproven_fragments += n;
604                *stats.unproven_by_cause.entry(why).or_default() += n;
605            }
606            Fate::Pending => stats.pending_fragments += n,
607            Fate::Drop(interrupted) => {
608                for &i in &m.fragment_lines {
609                    actions[i] = Action::Drop;
610                }
611                stats.dropped_fragments += n;
612                if let Some(line) = interrupted {
613                    synth.push(Synth { after: *m.fragment_lines.last().expect("non-empty"), message_id: id.clone(), line });
614                }
615            }
616        }
617    }
618    synth.sort_by_key(|s| s.after);
619    stats.interrupted_lines = synth.len();
620    stats.kept = actions.iter().filter(|a| **a == Action::Keep).count();
621    Plan { actions, synth, stats }
622}
623
624/// The compact lines of a window, with the plan that made them.
625pub fn compact_lines<S: AsRef<str>>(lines: &[S], end: WindowEnd) -> (Vec<String>, Plan) {
626    let plan = plan_window(lines, end);
627    (plan.apply(lines), plan)
628}
629
630/// A line the write path appends to `output` in place of fragments it held back.
631#[derive(Debug, Clone, PartialEq, Eq)]
632pub enum Emit {
633    /// The `assistant` line of a reply that was cut off (compact form, interrupted).
634    Interrupted(String),
635    /// A fragment that cannot be proven redundant: kept in `output` as it was written.
636    Fragment(String),
637}
638
639impl Emit {
640    pub fn line(&self) -> &str {
641        match self {
642            Emit::Interrupted(l) | Emit::Fragment(l) => l,
643        }
644    }
645}
646
647/// What a closed scan leaves for `output`, in the order of the lines it came from: every fragment
648/// that is not proven redundant, and an interrupted line after the last fragment of a cut-off reply.
649fn leftovers(scan: &Scan, raw: &[String]) -> Vec<Emit> {
650    let mut out: Vec<(usize, Emit)> = scan.orphan.iter().map(|&i| (i, Emit::Fragment(raw[i].clone()))).collect();
651    for id in &scan.order {
652        let m = &scan.msgs[id];
653        let Some(&last) = m.fragment_lines.last() else { continue };
654        match fate(id, m, WindowEnd::Final) {
655            Fate::Drop(None) => {}
656            Fate::Drop(Some(line)) => out.push((last, Emit::Interrupted(line))),
657            Fate::Unproven(_) | Fate::Pending => out.extend(m.fragment_lines.iter().map(|&i| (i, Emit::Fragment(raw[i].clone())))),
658        }
659    }
660    out.sort_by_key(|(i, _)| *i);
661    out.into_iter().map(|(_, e)| e).collect()
662}
663
664/// The write path's view of one agent's reply as it streams: fragments are held in `output.live`,
665/// and this tells when they have become redundant (every block is in a complete line and the
666/// message has stopped), and what must go to `output` instead when a turn ends without that.
667#[derive(Default)]
668pub struct LiveReply {
669    scan: Scan,
670    /// Every line taken since the last reset; only the fragment lines are kept.
671    raw: Vec<String>,
672}
673
674/// What [`LiveReply::before`] says of the line it took.
675#[derive(Debug, Clone, PartialEq, Eq)]
676pub struct Before {
677    /// The line is a stream fragment: hold it in `output.live`, not in `output`.
678    pub fragment: bool,
679    /// At a turn boundary: what the held-back fragments leave for `output`, to go before this line.
680    pub emits: Vec<Emit>,
681    /// A turn boundary ended a reply that held fragments: the live file is to be emptied.
682    pub ended: bool,
683}
684
685impl LiveReply {
686    pub fn new() -> Self {
687        Self::default()
688    }
689
690    /// Take the next line the CLI wrote, before it is stored. At a turn boundary the answer is what
691    /// the held-back fragments leave for `output`, to be written before the boundary line.
692    pub fn before(&mut self, line: &str) -> Before {
693        let i = self.raw.len();
694        let seen = self.scan.line(i, line);
695        let fragment = seen == Seen::Fragment;
696        self.raw.push(if fragment { line.to_string() } else { String::new() });
697        if seen != Seen::Boundary {
698            return Before { fragment, emits: Vec::new(), ended: false };
699        }
700        let ended = self.holds_fragments();
701        let emits = leftovers(&self.scan, &self.raw);
702        *self = Self::default();
703        Before { fragment, emits, ended }
704    }
705
706    /// Whether the fragments held back so far are all redundant now. True also when there are none
707    /// (nothing to clear). Call after a line is stored; on true with fragments held, clear
708    /// `output.live` and call [`LiveReply::reset`].
709    pub fn settled(&self) -> bool {
710        self.scan.orphan.is_empty()
711            && self.scan.order.iter().all(|id| {
712                let m = &self.scan.msgs[id];
713                m.fragment_lines.is_empty() || (m.stopped && matches!(fate(id, m, WindowEnd::Open), Fate::Drop(None)))
714            })
715    }
716
717    /// Whether any fragment is held.
718    pub fn holds_fragments(&self) -> bool {
719        !self.scan.orphan.is_empty() || self.scan.msgs.values().any(|m| !m.fragment_lines.is_empty())
720    }
721
722    pub fn reset(&mut self) {
723        *self = Self::default();
724    }
725}
726
727/// What a start finds in `output.live`, left by a process that was killed mid-reply: `tail` is the
728/// last complete lines of `output` (their `assistant` lines say which blocks are already stored),
729/// `live` the held fragments. Returns what must be appended to `output` before `output.live` is emptied.
730pub fn recover_live<S: AsRef<str>, T: AsRef<str>>(tail: &[S], live: &[T]) -> Vec<Emit> {
731    let mut r = LiveReply::new();
732    for l in tail {
733        // Only complete `assistant` lines tell which blocks are stored; a legacy fragment in the tail is not fed to the scan.
734        if let Some(v) = parse(l.as_ref()).filter(|v| line_type(v) == "assistant") {
735            r.scan.complete_line(&v);
736        }
737    }
738    for l in live {
739        let _ = r.before(l.as_ref());
740    }
741    for m in r.scan.msgs.values_mut() {
742        m.closed = true;
743    }
744    leftovers(&r.scan, &r.raw)
745}
746
747/// Which check failed, with counts and positions only (never line content).
748#[derive(Debug, Clone, PartialEq, Eq)]
749pub enum CheckFailure {
750    /// L1: the kept lines are not the old lines minus fragments, byte for byte and in order.
751    L1 { detail: String },
752    /// L2: a dropped fragment's message is not in a kept line, or an interrupted line differs from its fragments.
753    L2 { detail: String },
754    /// L3: counts by line kind, or an id, differ by more than the dropped fragments.
755    L3 { detail: String },
756}
757
758impl std::fmt::Display for CheckFailure {
759    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
760        match self {
761            CheckFailure::L1 { detail } => write!(f, "L1: {detail}"),
762            CheckFailure::L2 { detail } => write!(f, "L2: {detail}"),
763            CheckFailure::L3 { detail } => write!(f, "L3: {detail}"),
764        }
765    }
766}
767
768fn parse(line: &str) -> Option<Value> {
769    if line.starts_with('{') {
770        serde_json::from_str(line).ok()
771    } else {
772        None
773    }
774}
775
776fn is_fragment(line: &str) -> bool {
777    parse(line).is_some_and(|v| line_type(&v) == "stream_event")
778}
779
780fn is_interrupted(line: &str) -> bool {
781    parse(line).is_some_and(|v| line_type(&v) == "assistant" && v.get("interrupted").and_then(Value::as_bool) == Some(true))
782}
783
784/// The ids a line carries: its session, and its tool uses and results.
785fn ids_of(v: &Value, out: &mut HashSet<String>) {
786    if let Some(s) = v.get("session_id").and_then(Value::as_str) {
787        out.insert(format!("session:{s}"));
788    }
789    let mut blocks = |content: Option<&Value>| {
790        if let Some(Value::Array(bs)) = content {
791            for b in bs {
792                match b.get("type").and_then(Value::as_str) {
793                    Some("tool_use") => {
794                        if let Some(id) = b.get("id").and_then(Value::as_str) {
795                            out.insert(format!("tool:{id}"));
796                        }
797                    }
798                    Some("tool_result") => {
799                        if let Some(id) = b.get("tool_use_id").and_then(Value::as_str) {
800                            out.insert(format!("tool:{id}"));
801                        }
802                    }
803                    _ => {}
804                }
805            }
806        }
807    };
808    blocks(field(v, &["message", "content"]));
809    if line_type(v) == "stream_event" {
810        if let Some(b) = field(v, &["event", "content_block"]) {
811            if b.get("type").and_then(Value::as_str) == Some("tool_use") {
812                if let Some(id) = b.get("id").and_then(Value::as_str) {
813                    out.insert(format!("tool:{id}"));
814                }
815            }
816        }
817    }
818}
819
820/// What [`verify`] builds per dropped block: kind, text or thinking or partial json, signature, tool id and name (a text
821/// block: the JSON array of the citations it received, empty when none), unknown.
822type VBlock = (String, String, String, String, bool);
823
824/// Add a received citation to the JSON array a text block keeps in its `extra`.
825fn add_citation(extra: &mut String, citation: Option<&Value>) {
826    let mut all: Vec<Value> = serde_json::from_str(extra).unwrap_or_default();
827    all.push(citation.cloned().unwrap_or(Value::Null));
828    *extra = Value::Array(all).to_string();
829}
830
831/// The lines of the new window told apart from what the old one had.
832struct Split<'a> {
833    /// Kept lines, including interrupted lines the old window already held.
834    plain: Vec<&'a str>,
835    /// Interrupted lines this pass wrote.
836    synth: Vec<&'a str>,
837    /// Old fragments that are not in the new window.
838    dropped: Vec<&'a str>,
839}
840
841/// Check L1: the lines that are not fragments are the same sequence, byte for byte; the kept fragments are a subsequence of the old ones.
842fn check_l1<'a, S: AsRef<str>, T: AsRef<str>>(old: &'a [S], new: &'a [T]) -> Result<Split<'a>, CheckFailure> {
843    let old_other: Vec<&str> = old.iter().map(AsRef::as_ref).filter(|l| !is_fragment(l)).collect();
844    // An interrupted line the old window already had is an ordinary kept line; any other is one this pass wrote.
845    let mut old_interrupted: HashMap<&str, usize> = HashMap::new();
846    for l in old.iter().map(AsRef::as_ref).filter(|l| is_interrupted(l)) {
847        *old_interrupted.entry(l).or_insert(0) += 1;
848    }
849    let (mut plain, mut synth): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
850    for l in new.iter().map(AsRef::as_ref) {
851        match old_interrupted.get_mut(l) {
852            Some(n) if *n > 0 => {
853                *n -= 1;
854                plain.push(l);
855            }
856            _ if is_interrupted(l) => synth.push(l),
857            _ => plain.push(l),
858        }
859    }
860    let new_other: Vec<&str> = plain.iter().copied().filter(|l| !is_fragment(l)).collect();
861    if old_other != new_other {
862        let first = old_other.iter().zip(new_other.iter()).position(|(a, b)| a != b).unwrap_or(old_other.len().min(new_other.len()));
863        return Err(CheckFailure::L1 { detail: format!("lines other than fragments differ from position {first} (old {}, new {})", old_other.len(), new_other.len()) });
864    }
865    let old_frag: Vec<&str> = old.iter().map(AsRef::as_ref).filter(|l| is_fragment(l)).collect();
866    let new_frag: Vec<&str> = plain.iter().copied().filter(|l| is_fragment(l)).collect();
867    let mut it = old_frag.iter();
868    for f in &new_frag {
869        if !it.any(|o| o == f) {
870            return Err(CheckFailure::L1 { detail: "a kept fragment is not, in order, one of the old fragments".into() });
871        }
872    }
873    // The dropped fragments are the old ones that the kept ones do not account for, in order.
874    let mut dropped = Vec::new();
875    let mut kept = new_frag.iter().peekable();
876    for o in &old_frag {
877        if kept.peek().is_some_and(|k| *k == o) {
878            kept.next();
879        } else {
880            dropped.push(*o);
881        }
882    }
883    Ok(Split { plain, synth, dropped })
884}
885
886/// The blocks the dropped fragments of each message reassemble to, built here and not by the planner.
887fn reassemble_dropped(dropped: &[&str]) -> Result<HashMap<String, BTreeMap<u64, VBlock>>, CheckFailure> {
888    let l2 = |detail: &str| CheckFailure::L2 { detail: detail.into() };
889    let mut by_msg: HashMap<String, BTreeMap<u64, VBlock>> = HashMap::new();
890    let mut cur: HashMap<String, Option<String>> = HashMap::new();
891    for l in dropped {
892        let v = parse(l).expect("is_fragment parsed it");
893        let key = v.get("parent_tool_use_id").and_then(Value::as_str).unwrap_or("").to_string();
894        let ev = v.get("event").cloned().unwrap_or(Value::Null);
895        let t = ev.get("type").and_then(Value::as_str).unwrap_or("");
896        if t == "message_start" {
897            cur.insert(key, field(&ev, &["message", "id"]).and_then(Value::as_str).map(str::to_string));
898            continue;
899        }
900        let Some(Some(id)) = cur.get(&key).cloned() else {
901            return Err(l2("a dropped fragment has no message start before it"));
902        };
903        let blocks = by_msg.entry(id).or_default();
904        let ix = ev.get("index").and_then(Value::as_u64).unwrap_or(u64::MAX);
905        let d = ev.get("delta").cloned().unwrap_or(Value::Null);
906        let ds = |k: &str| d.get(k).and_then(Value::as_str).unwrap_or("").to_string();
907        match t {
908            "content_block_start" => {
909                let b = ev.get("content_block").cloned().unwrap_or(Value::Null);
910                let kind = b.get("type").and_then(Value::as_str).unwrap_or("").to_string();
911                let tool = matches!(kind.as_str(), "tool_use" | "server_tool_use" | "mcp_tool_use");
912                let unknown = !tool && !matches!(kind.as_str(), "text" | "thinking");
913                // A tool block is known by its id and name; a block of a kind not known here, by the whole start event (it came whole).
914                let extra = if tool {
915                    format!("{}\u{1}{}", b.get("id").and_then(Value::as_str).unwrap_or(""), b.get("name").and_then(Value::as_str).unwrap_or(""))
916                } else if unknown {
917                    b.to_string()
918                } else {
919                    String::new()
920                };
921                // A block may start with text, thinking or a signature already in it, as the planner's does.
922                let seed = |k: &str| if kind == "text" && k == "text" || kind == "thinking" && k != "text" { b.get(k).and_then(Value::as_str).unwrap_or("").to_string() } else { String::new() };
923                let (body, sig) = (if kind == "text" { seed("text") } else { seed("thinking") }, seed("signature"));
924                blocks.insert(ix, (kind, body, sig, extra, unknown));
925            }
926            "content_block_delta" => {
927                let Some(b) = blocks.get_mut(&ix) else {
928                    return Err(l2("a dropped delta has no block start"));
929                };
930                match (d.get("type").and_then(Value::as_str), b.0.as_str()) {
931                    (Some("text_delta"), "text") => b.1.push_str(&ds("text")),
932                    (Some("thinking_delta"), "thinking") => b.1.push_str(&ds("thinking")),
933                    (Some("signature_delta"), "thinking") => b.2.push_str(&ds("signature")),
934                    (Some("input_json_delta"), "tool_use" | "server_tool_use" | "mcp_tool_use") => b.1.push_str(&ds("partial_json")),
935                    (Some("citations_delta"), "text") => add_citation(&mut b.3, d.get("citation")),
936                    _ => return Err(l2("a dropped delta is of a kind the compact form does not reassemble")),
937                }
938            }
939            "content_block_stop" | "message_delta" | "message_stop" | "ping" => {}
940            "error" => return Err(l2("a dropped fragment is an error event, which no kept line holds")),
941            // An event kind that adds no block: the blocks are what the kept lines are checked against.
942            _ => {}
943        }
944    }
945    Ok(by_msg)
946}
947
948/// Whether the content block `c` of a kept line is the reassembled block `b`.
949fn block_is(c: &Value, b: &VBlock) -> bool {
950    let (kind, body, sig, extra, unknown) = b;
951    if c.get("type").and_then(Value::as_str) != Some(kind.as_str()) {
952        return false;
953    }
954    if *unknown {
955        return serde_json::from_str::<Value>(extra).is_ok_and(|start| &start == c);
956    }
957    let s = |k: &str| c.get(k).and_then(Value::as_str);
958    match kind.as_str() {
959        "text" => s("text") == Some(body.as_str()) && (extra.is_empty() || serde_json::from_str::<Vec<Value>>(extra).is_ok_and(|all| c.get("citations").and_then(Value::as_array) == Some(&all))),
960        "thinking" => s("thinking") == Some(body.as_str()) && (sig.is_empty() || s("signature") == Some(sig.as_str())),
961        _ => {
962            let (tid, name) = extra.split_once('\u{1}').unwrap_or(("", ""));
963            let input = if body.is_empty() { Some(Value::Object(Map::new())) } else { serde_json::from_str::<Value>(body).ok() };
964            s("id") == Some(tid) && s("name") == Some(name) && input.map_or_else(|| c.get("partial_input_json").and_then(Value::as_str) == Some(body.as_str()), |i| c.get("input") == Some(&i))
965        }
966    }
967}
968
969/// Check L2: every dropped fragment's message is covered by kept lines, and an interrupted line holds only what its fragments built.
970fn check_l2(split: &Split<'_>, by_msg: &HashMap<String, BTreeMap<u64, VBlock>>) -> Result<(), CheckFailure> {
971    // The kept complete blocks, and the interrupted lines' blocks, by message id.
972    let mut kept_blocks: HashMap<String, Vec<Value>> = HashMap::new();
973    let mut synth_blocks: HashMap<String, Vec<Value>> = HashMap::new();
974    for (is_synth, l) in split.plain.iter().map(|l| (false, *l)).chain(split.synth.iter().map(|l| (true, *l))) {
975        let Some(v) = parse(l) else { continue };
976        if line_type(&v) != "assistant" || v.get("partial").and_then(Value::as_bool) == Some(true) {
977            continue;
978        }
979        let Some(id) = field(&v, &["message", "id"]).and_then(Value::as_str) else { continue };
980        let Some(Value::Array(bs)) = field(&v, &["message", "content"]) else { continue };
981        let into = if is_synth { &mut synth_blocks } else { &mut kept_blocks };
982        into.entry(id.to_string()).or_default().extend(bs.iter().cloned());
983    }
984    for (id, blocks) in by_msg {
985        let mut have: Vec<(Value, bool)> = kept_blocks.get(id).into_iter().flatten().map(|b| (b.clone(), false)).collect();
986        let kept = have.len();
987        have.extend(synth_blocks.get(id).into_iter().flatten().map(|b| (b.clone(), false)));
988        for b in blocks.values() {
989            // A block that received citations is proven only by a kept complete line: an interrupted line cannot carry them.
990            let reach = if b.0 == "text" && !b.3.is_empty() { kept } else { have.len() };
991            match have.iter_mut().take(reach).find(|(c, used)| !*used && block_is(c, b)) {
992                Some((_, used)) => *used = true,
993                None => return Err(CheckFailure::L2 { detail: format!("a dropped {} block of a message is in no kept line", b.0) }),
994            }
995        }
996    }
997    for (id, bs) in &synth_blocks {
998        if bs.len() > by_msg.get(id).map_or(0, BTreeMap::len) {
999            return Err(CheckFailure::L2 { detail: "an interrupted line has more blocks than its fragments".into() });
1000        }
1001    }
1002    Ok(())
1003}
1004
1005/// Check L3: counts by line kind differ only by the dropped fragments and the interrupted lines; every session and tool id survives.
1006fn check_l3<S: AsRef<str>, T: AsRef<str>>(old: &[S], new: &[T], split: &Split<'_>) -> Result<(), CheckFailure> {
1007    let count = |ls: &mut dyn Iterator<Item = &str>| {
1008        let mut m: BTreeMap<String, i64> = BTreeMap::new();
1009        for l in ls {
1010            let k = parse(l).map_or_else(|| "unparsed".to_string(), |v| line_type(&v).to_string());
1011            *m.entry(k).or_insert(0) += 1;
1012        }
1013        m
1014    };
1015    let mut old_counts = count(&mut old.iter().map(AsRef::as_ref));
1016    *old_counts.entry("stream_event".into()).or_insert(0) -= split.dropped.len() as i64;
1017    *old_counts.entry("assistant".into()).or_insert(0) += split.synth.len() as i64;
1018    old_counts.retain(|_, n| *n != 0);
1019    let mut new_counts = count(&mut new.iter().map(AsRef::as_ref));
1020    new_counts.retain(|_, n| *n != 0);
1021    if old_counts != new_counts {
1022        return Err(CheckFailure::L3 { detail: format!("line counts by kind differ: expected {old_counts:?}, found {new_counts:?}") });
1023    }
1024    let (mut old_ids, mut new_ids) = (HashSet::new(), HashSet::new());
1025    for l in old {
1026        if let Some(v) = parse(l.as_ref()) {
1027            ids_of(&v, &mut old_ids);
1028        }
1029    }
1030    for l in new {
1031        if let Some(v) = parse(l.as_ref()) {
1032            ids_of(&v, &mut new_ids);
1033        }
1034    }
1035    let lost = old_ids.difference(&new_ids).count();
1036    if lost > 0 {
1037        return Err(CheckFailure::L3 { detail: format!("{lost} session or tool ids of the old lines are in no kept line") });
1038    }
1039    Ok(())
1040}
1041
1042/// Checks L1 to L3 of the spec: `new` is a correct compact form of `old`. Written apart from
1043/// [`plan_window`]: its own reassembly, so a fault in one does not pass the other.
1044pub fn verify<S: AsRef<str>, T: AsRef<str>>(old: &[S], new: &[T]) -> Result<(), CheckFailure> {
1045    let split = check_l1(old, new)?;
1046    let by_msg = reassemble_dropped(&split.dropped)?;
1047    check_l2(&split, &by_msg)?;
1048    check_l3(old, new, &split)
1049}
1050
1051/// Check L4: no `stream_event` line remains. A file that still has one is not declared compact.
1052/// Returns how many remain.
1053pub fn no_fragments<S: AsRef<str>>(lines: &[S]) -> Result<(), usize> {
1054    let n = lines.iter().filter(|l| l.as_ref().starts_with('{') && is_fragment(l.as_ref())).count();
1055    if n == 0 {
1056        Ok(())
1057    } else {
1058        Err(n)
1059    }
1060}
1061
1062#[cfg(test)]
1063#[path = "compact_tests.rs"]
1064mod tests;