Skip to main content

agentmux_srv_core/backend/transcript/
provider.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A provider's session file read against the store (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 5.2).
5//!
6//! The provider CLI writes its own record of a conversation. AgentMux cannot rebuild that file from the store, so it
7//! stays until its session ends; at the end it is removed only after a proof, for that session, that the store holds
8//! what the file holds. This module is the proof's pure half: it turns a record of either side into the items it
9//! carries (a text, a thinking block, a tool call, a tool result, a summary), and matches a file's records against the
10//! store's items, record by record and in order. [`super::provider_end`] does the file work around it.
11//!
12//! What a match means: every item of the provider record is in the store, with equal content, at a position after the
13//! previous record's items. Content is compared exactly, after the one change the store makes by design (a value srv
14//! holds secret is replaced by its mark, on the provider side too: [`record`]). Timestamps, the `amx` stamp and cost
15//! totals are not compared; the provider's own timestamp and ids are kept in the sidecar ([`sidecar_fields`]).
16//!
17//! A record with no items (a snapshot, a queue operation, a line that is not JSON) never matches: it is imported
18//! as it is. So the proof can only fail to find a match, never find a wrong one, and what it does not match is kept.
19
20use std::collections::HashMap;
21
22use serde_json::{Map, Value};
23use sha2::{Digest, Sha256};
24
25use super::withhold;
26
27/// What one record carries, by content: a 128-bit digest of the kind and the exact text.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub struct Item(u128);
30
31fn item(kind: &str, parts: &[&str]) -> Item {
32    let mut h = Sha256::new();
33    h.update((kind.len() as u64).to_le_bytes());
34    h.update(kind.as_bytes());
35    for p in parts {
36        h.update((p.len() as u64).to_le_bytes());
37        h.update(p.as_bytes());
38    }
39    let d = h.finalize();
40    let mut b = [0u8; 16];
41    b.copy_from_slice(&d[..16]);
42    Item(u128::from_le_bytes(b))
43}
44
45fn write_canon(v: &Value, out: &mut String) {
46    match v {
47        Value::Object(m) => {
48            let mut keys: Vec<&String> = m.keys().collect();
49            keys.sort();
50            out.push('{');
51            for (i, k) in keys.into_iter().enumerate() {
52                if i > 0 {
53                    out.push(',');
54                }
55                out.push_str(&Value::String(k.clone()).to_string());
56                out.push(':');
57                write_canon(&m[k], out);
58            }
59            out.push('}');
60        }
61        Value::Array(a) => {
62            out.push('[');
63            for (i, e) in a.iter().enumerate() {
64                if i > 0 {
65                    out.push(',');
66                }
67                write_canon(e, out);
68            }
69            out.push(']');
70        }
71        other => out.push_str(&other.to_string()),
72    }
73}
74
75/// The value as JSON with its keys in order, so two spellings of one object are one string.
76fn canon(v: &Value) -> String {
77    let mut s = String::new();
78    write_canon(v, &mut s);
79    s
80}
81
82/// A tool result's content as text: a string as it is, a list of text blocks joined, anything else as canonical JSON.
83fn result_text(content: &Value) -> String {
84    match content {
85        Value::String(s) => s.clone(),
86        Value::Array(blocks) if blocks.iter().all(|b| b.get("type").and_then(Value::as_str) == Some("text")) => {
87            blocks.iter().filter_map(|b| b.get("text").and_then(Value::as_str)).collect::<Vec<_>>().join("\n")
88        }
89        other => canon(other),
90    }
91}
92
93fn str_of<'a>(b: &'a Value, key: &str) -> &'a str {
94    b.get(key).and_then(Value::as_str).unwrap_or("")
95}
96
97fn block_item(role: &str, b: &Value) -> Item {
98    match b.get("type").and_then(Value::as_str).unwrap_or("") {
99        "text" => item(&format!("{role}-text"), &[str_of(b, "text")]),
100        "thinking" => item("thinking", &[str_of(b, "thinking"), str_of(b, "signature")]),
101        "tool_use" => item("tool_use", &[str_of(b, "id"), str_of(b, "name"), &canon(b.get("input").unwrap_or(&Value::Null))]),
102        "tool_result" => {
103            let err = if b.get("is_error").and_then(Value::as_bool).unwrap_or(false) { "1" } else { "0" };
104            item("tool_result", &[str_of(b, "tool_use_id"), err, &result_text(b.get("content").unwrap_or(&Value::Null))])
105        }
106        _ => item("block", &[&canon(b)]),
107    }
108}
109
110fn message_items(role: &str, v: &Value) -> Vec<Item> {
111    match v.pointer("/message/content") {
112        Some(Value::String(s)) if !s.is_empty() => vec![item(&format!("{role}-text"), &[s])],
113        Some(Value::Array(blocks)) => blocks.iter().map(|b| block_item(role, b)).collect(),
114        _ => Vec::new(),
115    }
116}
117
118/// The items one record (a provider line, or a stored line) carries, in order.
119pub fn items_of(v: &Value) -> Vec<Item> {
120    match v.get("type").and_then(Value::as_str).unwrap_or("") {
121        "user" => message_items("user", v),
122        "assistant" => message_items("assistant", v),
123        "summary" => v.get("summary").and_then(Value::as_str).map(|s| vec![item("summary", &[s])]).unwrap_or_default(),
124        "system" => {
125            let meta = v.get("compact_metadata").or_else(|| v.get("compactMetadata")).map(canon).unwrap_or_default();
126            vec![item("system", &[str_of(v, "subtype"), str_of(v, "content"), &meta])]
127        }
128        _ => Vec::new(),
129    }
130}
131
132/// The store's items, in line order, for one session.
133#[derive(Default)]
134pub struct StoreIndex {
135    at: HashMap<Item, Vec<usize>>,
136    next: usize,
137}
138
139impl StoreIndex {
140    pub fn new() -> Self {
141        Self::default()
142    }
143
144    /// Take one stored line. A line of another session is skipped; one that names no session is taken.
145    pub fn add_line(&mut self, sid: &str, line: &str) {
146        let Ok(v) = serde_json::from_str::<Value>(line) else { return };
147        let named = v.get("session_id").or_else(|| v.get("sessionId")).and_then(Value::as_str);
148        if named.is_some_and(|n| n != sid) {
149            return;
150        }
151        for it in items_of(&v) {
152            self.at.entry(it).or_default().push(self.next);
153            self.next += 1;
154        }
155    }
156
157    /// Where `it` is first stored at or after `from`.
158    fn first_from(&self, it: &Item, from: usize) -> Option<usize> {
159        let at = self.at.get(it)?;
160        at.get(at.partition_point(|p| *p < from)).copied()
161    }
162
163    pub fn len(&self) -> usize {
164        self.next
165    }
166}
167
168/// One line of a provider file.
169pub struct Record {
170    /// 1-based line number in its file.
171    pub n: usize,
172    /// The line, with srv's secrets replaced as the store would: what an import writes.
173    pub line: String,
174    value: Option<Value>,
175    items: Vec<Item>,
176}
177
178/// Read one line of a provider file.
179pub fn record(n: usize, line: &str) -> Record {
180    let line = withhold::text(line).into_owned();
181    let value = serde_json::from_str::<Value>(&line).ok();
182    let items = value.as_ref().map(items_of).unwrap_or_default();
183    Record { n, line, value, items }
184}
185
186/// Matches records, in order, against a [`StoreIndex`].
187pub struct Matcher<'a> {
188    index: &'a StoreIndex,
189    cursor: usize,
190}
191
192impl<'a> Matcher<'a> {
193    pub fn new(index: &'a StoreIndex) -> Self {
194        Self { index, cursor: 0 }
195    }
196
197    /// Whether every item of `r` is stored, in order and after the previous matched record. A record that matches
198    /// moves the position past its items; one that does not leaves it where it was.
199    pub fn matches(&mut self, r: &Record) -> bool {
200        if r.items.is_empty() {
201            return false;
202        }
203        let mut at = self.cursor;
204        for it in &r.items {
205            match self.index.first_from(it, at) {
206                Some(p) => at = p + 1,
207                None => return false,
208            }
209        }
210        self.cursor = at;
211        true
212    }
213}
214
215/// The fields of a record's own that the store's line does not carry: its ids and chain (`uuid`, `parentUuid`), its
216/// sidechain and request ids, version, slug, working directory, branch, timestamp, and the message's id, model and usage;
217/// and a tool result's `toolUseResult` when it holds text the matched result does not. The sidecar keeps them.
218pub fn sidecar_fields(r: &Record) -> Option<Map<String, Value>> {
219    const KEEP: [&str; 17] = [
220        "uuid", "parentUuid", "logicalParentUuid", "isSidechain", "sessionId", "requestId", "version", "slug", "cwd",
221        "gitBranch", "userType", "entrypoint", "timestamp", "isMeta", "isCompactSummary", "agentId", "sourceToolUseID",
222    ];
223    let v = r.value.as_ref()?;
224    let mut out = Map::new();
225    for k in KEEP {
226        if let Some(x) = v.get(k) {
227            out.insert(k.to_string(), x.clone());
228        }
229    }
230    if let Some(m) = v.get("message").and_then(Value::as_object) {
231        let msg: Map<String, Value> =
232            ["id", "model", "usage", "stop_reason", "stop_sequence"].iter().filter_map(|k| m.get(*k).map(|x| (k.to_string(), x.clone()))).collect();
233        if !msg.is_empty() {
234            out.insert("message".to_string(), Value::Object(msg));
235        }
236    }
237    if let Some(extra) = v.get("toolUseResult").filter(|t| !covered_by_results(t, v)) {
238        out.insert("toolUseResult".to_string(), extra.clone());
239    }
240    (!out.is_empty()).then_some(out)
241}
242
243fn leaves<'a>(v: &'a Value, out: &mut Vec<&'a str>) {
244    match v {
245        Value::String(s) => out.push(s),
246        Value::Array(a) => a.iter().for_each(|e| leaves(e, out)),
247        Value::Object(m) => m.values().for_each(|e| leaves(e, out)),
248        _ => {}
249    }
250}
251
252/// Whether every text in `extra` is in the record's own tool results.
253fn covered_by_results(extra: &Value, record: &Value) -> bool {
254    let hay: Vec<String> = match record.pointer("/message/content") {
255        Some(Value::Array(blocks)) => blocks
256            .iter()
257            .filter(|b| b.get("type").and_then(Value::as_str) == Some("tool_result"))
258            .map(|b| result_text(b.get("content").unwrap_or(&Value::Null)))
259            .collect(),
260        _ => Vec::new(),
261    };
262    let mut texts = Vec::new();
263    leaves(extra, &mut texts);
264    texts.iter().all(|t| t.is_empty() || hay.iter().any(|h| h.contains(t)))
265}