Skip to main content

telemetry/recorder/
mod.rs

1//! Recorder — records every LLM call and replays it deterministically.
2//!
3//! A `Model` decorator sitting on `Model::stream()`, the one place in the
4//! engine that sees a complete request and a complete response at once: the
5//! turn loop assembles the request but hands the stream away, and the stream
6//! consumer sees the response but not what produced it.
7//!
8//! What it produces is diagnostic data, not session state. It takes no part in
9//! resume, fork, or context reconstruction — deleting a recording leaves the
10//! session working exactly as before. `crates/history` remains the sole
11//! authority on what a conversation is.
12//!
13//! Replay matches by **position**, not by hashing the request: within a
14//! session, the k-th live conversation call replays the k-th recorded one,
15//! and the k-th auxiliary call of a purpose replays the k-th recorded call of
16//! that purpose. Hash-keyed lookup makes every environment-dependent byte in a
17//! prompt a correctness problem, and when it misses it can only report that it
18//! missed. Recording the whole request instead means a mismatch can name the
19//! field that moved.
20//!
21//! **A recording holds everything the model saw, in the clear.** System
22//! prompts, the whole conversation, tool arguments and results — verbatim, and
23//! deliberately not passed through [`crate::RedactionPolicy`], which exists for
24//! telemetry events and would defeat the point here: a recording is worth
25//! keeping only if it says what was actually sent. So a recording carries
26//! whatever secrets the prompt carried, and its directory deserves the same
27//! handling as the transcript it came from: the recorder creates its
28//! directories and files readable by their owner only. Recording is off
29//! unless configured.
30
31pub mod blob;
32pub mod format;
33pub mod override_doc;
34pub mod pack;
35mod private;
36pub mod reader;
37pub mod rerun;
38mod stream;
39pub mod writer;
40
41use async_trait::async_trait;
42use base::interface::model::{
43    Model, ModelError, ModelEvent, ModelMessage, ModelStream, StreamParams, ToolDef, Usage,
44};
45use base::prompt::PromptBlock;
46use base::provider::ApiType;
47use base::recorder::{Divergence, RecorderConfig, RecorderMode};
48use std::collections::{HashMap, HashSet};
49use std::path::PathBuf;
50use std::sync::{Arc, Mutex};
51use tokio_util::sync::CancellationToken;
52
53use blob::BlobId;
54use format::{
55    now_ms, CallRecord, Header, Outcome, Record, RecordedError, RecordedParams, FORMAT_VERSION,
56};
57use pack::RunPacker;
58pub(crate) use private::{private_dir, private_file};
59use reader::Recording;
60use stream::{write_end, RecordingStream};
61use writer::RecordingWriter;
62
63/// The recording a call belongs to, or nothing.
64///
65/// A call that cannot name its session has no recording to belong to. A
66/// shared name for such calls would file unrelated calls together, and since
67/// a writer truncates the file it opens, concurrent sessions would erase
68/// each other.
69fn recording_name_of(config: &RecorderConfig, params: &StreamParams) -> Option<String> {
70    if let Some(name) = &config.name {
71        return Some(name.clone());
72    }
73    params.origin.as_ref().map(|o| o.session_id.clone())
74}
75
76/// Everything a set of recordings shares: the open writers and how far each
77/// replay has got, keyed by recording name.
78///
79/// Held behind an `Arc` and shared by every [`RecorderModel`] that records into
80/// the same root. Multi-provider routing hands out one `Model` per provider,
81/// and each of them needs wrapping to be recorded at all — but they must not
82/// each open their own writer for the same file, or the second one to write
83/// truncates the first one's recording out from under it. One shared state, one
84/// writer per name, appends serialized by that writer's lock.
85#[derive(Default)]
86pub struct Recorder {
87    writers: Mutex<HashMap<String, Arc<RecordingWriter>>>,
88    replays: Mutex<HashMap<String, ReplayState>>,
89}
90
91impl Recorder {
92    pub fn new() -> Arc<Self> {
93        Arc::new(Self::default())
94    }
95
96    /// Report any replay that did not run to the end of what was recorded.
97    ///
98    /// A run that made *fewer* calls than the recording holds passes every
99    /// other check — nothing diverged, nothing ran out — while having quietly
100    /// stopped doing part of the work. Overshooting is already an error at the
101    /// call that overshoots; this is the other direction, and it can only be
102    /// asked at the end. Returns one line per unfinished session, empty when
103    /// every recorded call was replayed — or the only ones left are calls a
104    /// replay may go without.
105    pub fn unconsumed(&self) -> Vec<String> {
106        let replays = self.replays.lock().unwrap_or_else(|e| e.into_inner());
107        let mut out = Vec::new();
108        for (name, state) in replays.iter() {
109            for recorded in &state.recorded_sessions {
110                let calls = state.calls_of(recorded);
111                let total = calls.len();
112                let replayed = state.replayed_of(recorded);
113                let used = replayed.len();
114                let owed = calls.iter().enumerate().any(|(at, c)| {
115                    !replayed.contains(&at)
116                        && !c.request.purpose.as_deref().is_some_and(may_go_unreplayed)
117                });
118                if owed {
119                    out.push(format!(
120                        "recording {name:?} session {recorded:?}: replayed {used} of {total} call(s)"
121                    ));
122                }
123            }
124        }
125        out
126    }
127}
128
129pub struct RecorderModel {
130    inner: Arc<dyn Model>,
131    config: Option<RecorderConfig>,
132    engine_version: String,
133    /// The provider id this instance fronts, as named in settings.json. The
134    /// api type alone cannot tell two OpenAI-compatible endpoints apart.
135    provider_id: Option<String>,
136    shared: Arc<Recorder>,
137}
138
139/// One recording being replayed, sliced per session and, within a session,
140/// per purpose.
141///
142/// A single cursor over the whole file works only when the file holds one
143/// session. When a parent and its sub-agents record under one name their calls
144/// interleave, and the order they interleave in is a scheduling detail that
145/// will not repeat — so each live session walks only the calls that were made
146/// by its counterpart, and the interleaving is allowed to differ.
147///
148/// The same holds inside a session. Its conversation calls come in an order
149/// the turn loop fixes, but auxiliary calls — memory extraction, naming —
150/// run in the background and land among them wherever they happened to
151/// finish. So a conversation call takes the session's next recorded
152/// conversation call, passing over auxiliary ones, and an auxiliary call
153/// takes the earliest recorded call of its purpose not yet replayed.
154struct ReplayState {
155    recording: Recording,
156    /// Recorded session ids in order of first appearance, which is the order
157    /// live sessions bind to them when the ids themselves don't match.
158    recorded_sessions: Vec<String>,
159    /// Live session id → the recorded session it replays against.
160    bound: HashMap<String, String>,
161    /// Recorded session id → which of its calls (indices into
162    /// [`Self::calls_of`]) have been handed out.
163    ///
164    /// Kept apart from `bound` so marking a call needs no second lookup into
165    /// `bound` — one that could only be written as an `unwrap()` resting on an
166    /// invariant held across two functions with nothing enforcing it.
167    replayed: HashMap<String, HashSet<usize>>,
168}
169
170impl ReplayState {
171    fn new(recording: Recording) -> Self {
172        let mut recorded_sessions: Vec<String> = Vec::new();
173        for call in &recording.calls {
174            let session = call
175                .request
176                .session_id
177                .clone()
178                .unwrap_or_else(|| recording.header.session_id.clone());
179            if !recorded_sessions.contains(&session) {
180                recorded_sessions.push(session);
181            }
182        }
183        Self {
184            recording,
185            recorded_sessions,
186            bound: HashMap::new(),
187            replayed: HashMap::new(),
188        }
189    }
190
191    /// Which recorded session `live` replays against.
192    ///
193    /// An id that appears in the recording binds to itself — a replay driven
194    /// with the same session ids it was recorded with is exact. Otherwise
195    /// sessions bind in the order they first call, which is what a live run
196    /// can guarantee: the parent necessarily streams before it can delegate.
197    /// Returns the recorded session id, or `None` when the run has introduced
198    /// more distinct sessions than the recording holds.
199    fn bind(&mut self, live: &str) -> Option<String> {
200        if let Some(recorded) = self.bound.get(live) {
201            return Some(recorded.clone());
202        }
203        let recorded = if self.recorded_sessions.iter().any(|s| s == live) {
204            live.to_string()
205        } else {
206            self.recorded_sessions
207                .iter()
208                .find(|s| !self.bound.values().any(|taken| taken == *s))?
209                .clone()
210        };
211        self.bound.insert(live.to_string(), recorded.clone());
212        Some(recorded)
213    }
214
215    fn replayed_of(&self, recorded_session: &str) -> HashSet<usize> {
216        self.replayed
217            .get(recorded_session)
218            .cloned()
219            .unwrap_or_default()
220    }
221
222    /// The earliest call of `recorded_session` with `purpose` (`None` for a
223    /// conversation call) not yet handed out, as an index into
224    /// [`Self::calls_of`].
225    fn next_of(&self, recorded_session: &str, purpose: Option<&str>) -> Option<usize> {
226        let replayed = self.replayed.get(recorded_session);
227        self.calls_of(recorded_session)
228            .iter()
229            .enumerate()
230            .find(|(at, c)| {
231                c.request.purpose.as_deref() == purpose && !replayed.is_some_and(|r| r.contains(at))
232            })
233            .map(|(at, _)| at)
234    }
235
236    fn mark_replayed(&mut self, recorded_session: &str, at: usize) {
237        self.replayed
238            .entry(recorded_session.to_string())
239            .or_default()
240            .insert(at);
241    }
242
243    fn calls_of(&self, recorded_session: &str) -> Vec<&reader::RecordedCall> {
244        self.recording
245            .calls
246            .iter()
247            .filter(|c| {
248                c.request
249                    .session_id
250                    .as_deref()
251                    .unwrap_or(&self.recording.header.session_id)
252                    == recorded_session
253            })
254            .collect()
255    }
256}
257
258impl RecorderModel {
259    pub fn new(
260        inner: Arc<dyn Model>,
261        config: Option<RecorderConfig>,
262        engine_version: &str,
263    ) -> Self {
264        Self::shared(inner, config, engine_version, Recorder::new())
265    }
266
267    /// Wrap `inner` sharing `shared` with every other model recording into the
268    /// same root — the constructor multi-provider routing uses, so a session's
269    /// calls land in one recording however many providers served them.
270    pub fn shared(
271        inner: Arc<dyn Model>,
272        config: Option<RecorderConfig>,
273        engine_version: &str,
274        shared: Arc<Recorder>,
275    ) -> Self {
276        Self {
277            inner,
278            config: config.or_else(Self::env_config),
279            engine_version: engine_version.to_string(),
280            provider_id: None,
281            shared,
282        }
283    }
284
285    pub fn with_provider_id(mut self, provider_id: impl Into<String>) -> Self {
286        self.provider_id = Some(provider_id.into());
287        self
288    }
289
290    /// `AGIX_RECORD=<name>` / `AGIX_REPLAY=<name>` with `AGIX_RECORDINGS_DIR`
291    /// for the root. Absent all of them, the decorator is a pass-through.
292    fn env_config() -> Option<RecorderConfig> {
293        let root = std::env::var("AGIX_RECORDINGS_DIR")
294            .ok()
295            .map(PathBuf::from)?;
296        let on_divergence = Self::default_divergence();
297        if let Ok(name) = std::env::var("AGIX_RECORD") {
298            Some(RecorderConfig {
299                mode: RecorderMode::Record,
300                name: Some(name),
301                root,
302                on_divergence,
303            })
304        } else if let Ok(name) = std::env::var("AGIX_REPLAY") {
305            Some(RecorderConfig {
306                mode: RecorderMode::Replay,
307                name: Some(name),
308                root,
309                on_divergence,
310            })
311        } else {
312            None
313        }
314    }
315
316    fn writer_for(
317        &self,
318        config: &RecorderConfig,
319        name: &str,
320        params: &StreamParams,
321    ) -> Arc<RecordingWriter> {
322        let mut writers = self
323            .shared
324            .writers
325            .lock()
326            .unwrap_or_else(|e| e.into_inner());
327        writers
328            .entry(name.to_string())
329            .or_insert_with(|| {
330                Arc::new(RecordingWriter::create(
331                    &config.root,
332                    Header {
333                        version: FORMAT_VERSION,
334                        name: name.to_string(),
335                        session_id: params
336                            .origin
337                            .as_ref()
338                            .map(|o| o.session_id.clone())
339                            .unwrap_or_default(),
340                        // Fixed by the first call, which is why a sub-agent has
341                        // to know its lineage at spawn time rather than
342                        // discovering it later.
343                        parent: params
344                            .origin
345                            .as_ref()
346                            .and_then(|o| o.parent_session_id.clone()),
347                        agent_type: params.origin.as_ref().and_then(|o| o.agent_type.clone()),
348                        created_at: now_ms(),
349                        engine_version: self.engine_version.clone(),
350                    },
351                ))
352            })
353            .clone()
354    }
355}
356
357/// When the recording `name` under `root` began (its header's `created_at`, milliseconds since
358/// the epoch), reading only its first line. `None` when there is no such recording.
359///
360/// What a replaying session sets its clock to, so the date its prompt carries is the date the
361/// recording's prompt carried.
362pub fn recorded_at(root: &std::path::Path, name: &str) -> Option<u64> {
363    use std::io::BufRead;
364    let file = std::fs::File::open(root.join(name).join("calls.jsonl")).ok()?;
365    let line = std::io::BufReader::new(file)
366        .lines()
367        .map_while(Result::ok)
368        .find(|l| !l.trim().is_empty())?;
369    match serde_json::from_str::<format::Record>(&line).ok()? {
370        format::Record::Recording(header) => Some(header.created_at),
371        _ => None,
372    }
373}
374
375fn flag(name: &str) -> bool {
376    std::env::var(name).is_ok_and(|v| v != "0" && !v.is_empty())
377}
378
379/// The environment facts that decide the default divergence policy. Split from
380/// the lookups so the policy is a pure function that can be tested without
381/// mutating process-global environment variables.
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383struct DivergenceInputs {
384    forced_strict: bool,
385    forced_warn: bool,
386    in_test: bool,
387    in_ci: bool,
388}
389
390fn resolve_divergence(inputs: DivergenceInputs) -> Divergence {
391    if inputs.forced_strict {
392        return Divergence::Strict;
393    }
394    if inputs.forced_warn {
395        return Divergence::Warn;
396    }
397    // Strict wherever a divergence means a broken test; lenient only for a
398    // human driving a replay by hand, so a brand-new case still runs before
399    // anyone has recorded it.
400    if inputs.in_test || inputs.in_ci {
401        Divergence::Strict
402    } else {
403        Divergence::Warn
404    }
405}
406
407impl RecorderModel {
408    /// The divergence policy a harness should ask for rather than re-derive.
409    ///
410    /// Public because a harness that builds an explicit [`RecorderConfig`]
411    /// never reaches [`RecorderModel::env_config`], and re-deriving this is
412    /// how the equivalent flag once shipped as a silent no-op.
413    ///
414    /// Overrides, highest precedence first: `AGIX_REPLAY_STRICT=1`, then
415    /// `AGIX_REPLAY_WARN=1`.
416    pub fn default_divergence() -> Divergence {
417        resolve_divergence(DivergenceInputs {
418            forced_strict: flag("AGIX_REPLAY_STRICT"),
419            forced_warn: flag("AGIX_REPLAY_WARN"),
420            in_test: std::env::var("CARGO_TEST_RUNNER").is_ok()
421                || std::env::var("AGIX_RECORDER_AUTO_DETECT").is_ok(),
422            in_ci: flag("CI"),
423        })
424    }
425}
426
427/// The parts of a request that identify it, as blob ids. Computed for both a
428/// live request and a recorded one so replay can compare them without loading
429/// content that matches.
430struct RequestShape {
431    params: RecordedParams,
432    system: Vec<BlobId>,
433    tools: BlobId,
434    messages: Vec<BlobId>,
435}
436
437impl RequestShape {
438    fn of(
439        prompt_blocks: &[PromptBlock],
440        tools: &[ToolDef],
441        messages: &[ModelMessage],
442        params: &StreamParams,
443    ) -> Self {
444        Self {
445            params: RecordedParams {
446                model: params.model.clone(),
447                max_tokens: params.max_tokens,
448                thinking_mode: params.thinking_mode.clone(),
449                effort: params.effort,
450                cache_edits: params.cache_edits.clone(),
451                search_max_uses: params.provider_search.map(|s| s.max_uses),
452            },
453            system: prompt_blocks.iter().map(BlobId::of_value).collect(),
454            tools: BlobId::of_value(&tools),
455            messages: messages.iter().map(BlobId::of_value).collect(),
456        }
457    }
458}
459
460/// Field-level differences between what was recorded and what the live run
461/// produced. Empty means the two agree.
462fn diverges(recorded: &CallRecord, live: &RequestShape) -> Vec<String> {
463    let mut out = Vec::new();
464    if recorded.params != live.params {
465        out.push(format!(
466            "params: recorded {:?}, live {:?}",
467            recorded.params, live.params
468        ));
469    }
470    if recorded.system.len() != live.system.len() {
471        out.push(format!(
472            "system: recorded {} blocks, live {}",
473            recorded.system.len(),
474            live.system.len()
475        ));
476    } else {
477        for (i, (a, b)) in recorded.system.iter().zip(&live.system).enumerate() {
478            if a != b {
479                out.push(format!("system[{i}]: recorded {a}, live {b}"));
480            }
481        }
482    }
483    if recorded.tools != live.tools {
484        out.push(format!(
485            "tools: recorded {}, live {}",
486            recorded.tools, live.tools
487        ));
488    }
489    if recorded.messages.len() != live.messages.len() {
490        out.push(format!(
491            "messages: recorded {} messages, live {}",
492            recorded.messages.len(),
493            live.messages.len()
494        ));
495    } else {
496        for (i, (a, b)) in recorded.messages.iter().zip(&live.messages).enumerate() {
497            if a != b {
498                out.push(format!("messages[{i}]: recorded {a}, live {b}"));
499            }
500        }
501    }
502    out
503}
504
505#[async_trait]
506impl Model for RecorderModel {
507    fn api_type(&self) -> ApiType {
508        self.inner.api_type()
509    }
510
511    fn provenance(&self) -> Option<String> {
512        self.inner.provenance()
513    }
514
515    fn meters_its_calls(&self) -> bool {
516        self.inner.meters_its_calls()
517    }
518
519    async fn stream(
520        &self,
521        prompt_blocks: Vec<PromptBlock>,
522        tools: Vec<ToolDef>,
523        messages: Vec<ModelMessage>,
524        params: StreamParams,
525        cancel: CancellationToken,
526    ) -> Result<ModelStream, ModelError> {
527        let Some(config) = self.config.clone() else {
528            return self
529                .inner
530                .stream(prompt_blocks, tools, messages, params, cancel)
531                .await;
532        };
533        let Some(name) = recording_name_of(&config, &params) else {
534            return self
535                .inner
536                .stream(prompt_blocks, tools, messages, params, cancel)
537                .await;
538        };
539
540        match config.mode {
541            RecorderMode::Replay => {
542                let shape = RequestShape::of(&prompt_blocks, &tools, &messages, &params);
543                let live_session = params
544                    .origin
545                    .as_ref()
546                    .map(|o| o.session_id.as_str())
547                    .unwrap_or_default();
548                let purpose = params.origin.as_ref().and_then(|o| o.purpose());
549                self.replay(&config, &name, live_session, purpose, shape)
550            }
551            RecorderMode::Record => {
552                let writer = self.writer_for(&config, &name, &params);
553                self.record(writer, prompt_blocks, tools, messages, params, cancel)
554                    .await
555            }
556            // Rerun drives the provider from a recording rather than from a
557            // live session, so it does not sit on this path — see
558            // [`rerun::rerun_one`], which the daemon's `session.rerunCall`
559            // drives. A session that somehow runs under this mode
560            // just talks to the model, which is the only honest thing to do
561            // here: intercepting would mean answering a live request with a
562            // response recorded for some other request.
563            RecorderMode::Rerun => {
564                self.inner
565                    .stream(prompt_blocks, tools, messages, params, cancel)
566                    .await
567            }
568        }
569    }
570}
571
572/// Blob writes are synchronous disk IO; on a multi-thread runtime they are
573/// told to the scheduler so other tasks move off this worker meanwhile.
574fn off_the_reactor<T>(f: impl FnOnce() -> T) -> T {
575    match tokio::runtime::Handle::try_current().map(|h| h.runtime_flavor()) {
576        Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(f),
577        _ => f(),
578    }
579}
580
581impl RecorderModel {
582    async fn record(
583        &self,
584        writer: Arc<RecordingWriter>,
585        prompt_blocks: Vec<PromptBlock>,
586        tools: Vec<ToolDef>,
587        messages: Vec<ModelMessage>,
588        params: StreamParams,
589        cancel: CancellationToken,
590    ) -> Result<ModelStream, ModelError> {
591        let call_seq = writer.next_seq();
592        let started = std::time::Instant::now();
593
594        // Written before the stream opens, and flushed: a process killed
595        // mid-response still leaves behind the request that was in flight.
596        if let Err(e) = off_the_reactor(|| {
597            self.write_call(
598                &writer,
599                call_seq,
600                &prompt_blocks,
601                &tools,
602                &messages,
603                &params,
604            )
605        }) {
606            tracing::warn!(error = %e, "recorder: failed to write call record, continuing unrecorded");
607        }
608
609        let result = self
610            .inner
611            .stream(prompt_blocks, tools, messages, params, cancel)
612            .await;
613
614        match result {
615            Ok(inner) => Ok(Box::new(RecordingStream {
616                inner,
617                writer,
618                packer: RunPacker::new(),
619                call_seq,
620                started,
621                stop_reason: String::new(),
622                usage: Usage::default(),
623                finished: false,
624            })),
625            Err(e) => {
626                write_end(
627                    &writer,
628                    call_seq,
629                    Outcome::Error {
630                        error: RecordedError::from(&e),
631                    },
632                    None,
633                    None,
634                    started,
635                );
636                Err(e)
637            }
638        }
639    }
640
641    fn write_call(
642        &self,
643        writer: &RecordingWriter,
644        call_seq: u64,
645        prompt_blocks: &[PromptBlock],
646        tools: &[ToolDef],
647        messages: &[ModelMessage],
648        params: &StreamParams,
649    ) -> std::io::Result<()> {
650        let blobs = writer.blobs();
651        let system = prompt_blocks
652            .iter()
653            .map(|b| blobs.put(b))
654            .collect::<Result<Vec<_>, _>>()?;
655        let tools_id = blobs.put(&tools)?;
656        let message_ids = messages
657            .iter()
658            .map(|m| blobs.put(m))
659            .collect::<Result<Vec<_>, _>>()?;
660
661        let (turn, step) = params
662            .origin
663            .as_ref()
664            .map(|o| o.turn_step())
665            .unwrap_or((0, 0));
666
667        writer.append(&Record::Call(Box::new(CallRecord {
668            seq: call_seq,
669            ts: now_ms(),
670            session_id: params.origin.as_ref().map(|o| o.session_id.clone()),
671            parent_session_id: params
672                .origin
673                .as_ref()
674                .and_then(|o| o.parent_session_id.clone()),
675            agent_type: params.origin.as_ref().and_then(|o| o.agent_type.clone()),
676            turn_id: params.origin.as_ref().and_then(|o| o.turn_id.clone()),
677            turn,
678            step,
679            purpose: params
680                .origin
681                .as_ref()
682                .and_then(|o| o.purpose())
683                .map(str::to_string),
684            // The provider as configured, when routing named one. Falling back
685            // to the api type keeps single-provider recordings readable, but it
686            // cannot distinguish two OpenAI-compatible endpoints — which is why
687            // the routed path supplies the id.
688            provider: self.provider_id.clone().unwrap_or_else(|| {
689                match self.inner.api_type() {
690                    ApiType::Anthropic => "anthropic",
691                    ApiType::OpenAIChat => "openai_chat",
692                    ApiType::OpenAIResponses => "openai_responses",
693                }
694                .into()
695            }),
696            api_type: self.inner.api_type(),
697            params: RecordedParams {
698                model: params.model.clone(),
699                max_tokens: params.max_tokens,
700                thinking_mode: params.thinking_mode.clone(),
701                effort: params.effort,
702                cache_edits: params.cache_edits.clone(),
703                search_max_uses: params.provider_search.map(|s| s.max_uses),
704            },
705            input_map: params.input_map.clone(),
706            system,
707            tools: tools_id,
708            messages: message_ids,
709        })))?;
710        writer.flush()
711    }
712
713    fn replay(
714        &self,
715        config: &RecorderConfig,
716        name: &str,
717        live_session: &str,
718        purpose: Option<&str>,
719        shape: RequestShape,
720    ) -> Result<ModelStream, ModelError> {
721        let mut replays = self
722            .shared
723            .replays
724            .lock()
725            .unwrap_or_else(|e| e.into_inner());
726        let state = match replays.get_mut(name) {
727            Some(state) => state,
728            None => {
729                let recording = reader::load_for_replay(&config.root.join(name), name)?;
730                replays
731                    .entry(name.to_string())
732                    .or_insert(ReplayState::new(recording))
733            }
734        };
735
736        let sessions = state.recorded_sessions.len();
737        let Some(recorded_session) = state.bind(live_session) else {
738            return Err(ModelError::protocol(format!(
739                "recorder: recording {name:?} holds {sessions} session(s), \
740                 live run introduced another ({live_session:?})"
741            )));
742        };
743        let Some(at) = state.next_of(&recorded_session, purpose) else {
744            let same_kind = state
745                .calls_of(&recorded_session)
746                .iter()
747                .filter(|c| c.request.purpose.as_deref() == purpose)
748                .count();
749            return Err(exhausted_error(name, &recorded_session, purpose, same_kind));
750        };
751        let call = state.calls_of(&recorded_session)[at].clone();
752        state.mark_replayed(&recorded_session, at);
753
754        let differences = diverges(&call.request, &shape);
755        if !differences.is_empty() {
756            let report = format!(
757                "recorder: call #{} of session {:?} diverges from recording {:?}:\n  {}",
758                at + 1,
759                recorded_session,
760                name,
761                differences.join("\n  ")
762            );
763            match config.on_divergence {
764                Divergence::Strict => return Err(ModelError::protocol(report)),
765                Divergence::Warn => tracing::warn!("{report}"),
766            }
767        }
768
769        if let Some(end) = &call.end {
770            if let Outcome::Error { error } = &end.outcome {
771                return Err(error.clone().into_model_error());
772            }
773        }
774
775        let events: Vec<Result<ModelEvent, ModelError>> =
776            call.response.iter().cloned().map(Ok).collect();
777        Ok(Box::new(futures::stream::iter(events)))
778    }
779}
780
781fn exhausted_error(
782    name: &str,
783    recorded_session: &str,
784    purpose: Option<&str>,
785    same_kind: usize,
786) -> ModelError {
787    match purpose {
788        Some(wanted) if may_go_unreplayed(wanted) => ModelError::not_recorded(format!(
789            "recording {name:?} has no unreplayed {wanted:?} call for session \
790             {recorded_session:?}"
791        )),
792        Some(wanted) => ModelError::protocol(format!(
793            "recorder: recording {name:?} has {same_kind} {wanted:?} call(s) for \
794             session {recorded_session:?}, live run asked for #{}",
795            same_kind + 1
796        )),
797        None => ModelError::protocol(format!(
798            "recorder: recording {name:?} has {same_kind} conversation call(s) for \
799             session {recorded_session:?}, live run asked for #{}",
800            same_kind + 1
801        )),
802    }
803}
804
805/// Whether a call of this purpose may be missing on either side of a replay.
806///
807/// Naming a session is not part of its conversation: a recording made where
808/// the scene did not name, or before naming was recorded at all, still
809/// replays a run that does — the run just goes unnamed — and a recorded
810/// title call a run does not ask for is left unreplayed without the run
811/// being reported as having stopped short.
812fn may_go_unreplayed(purpose: &str) -> bool {
813    purpose == base::interface::model::call_purpose::TITLE
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819    use base::interface::model::ModelErrorKind;
820    use base::interface::model::ThinkingMode;
821    use base::interface::model::{call_purpose, CallOrigin};
822    use base::prompt::BlockRole;
823    use futures::StreamExt;
824
825    /// Replays a fixed script, or fails to open when `open_error` is set.
826    struct ScriptedModel {
827        events: Vec<ModelEvent>,
828        open_error: bool,
829    }
830
831    impl ScriptedModel {
832        fn ok(events: Vec<ModelEvent>) -> Arc<dyn Model> {
833            Arc::new(Self {
834                events,
835                open_error: false,
836            })
837        }
838
839        fn overloaded() -> Arc<dyn Model> {
840            Arc::new(Self {
841                events: vec![],
842                open_error: true,
843            })
844        }
845    }
846
847    #[async_trait]
848    impl Model for ScriptedModel {
849        fn api_type(&self) -> ApiType {
850            ApiType::Anthropic
851        }
852        async fn stream(
853            &self,
854            _: Vec<PromptBlock>,
855            _: Vec<ToolDef>,
856            _: Vec<ModelMessage>,
857            _: StreamParams,
858            _: CancellationToken,
859        ) -> Result<ModelStream, ModelError> {
860            if self.open_error {
861                return Err(ModelError::overloaded());
862            }
863            let events: Vec<Result<ModelEvent, ModelError>> =
864                self.events.iter().cloned().map(Ok).collect();
865            Ok(Box::new(futures::stream::iter(events)))
866        }
867    }
868
869    fn script() -> Vec<ModelEvent> {
870        vec![
871            ModelEvent::TextDelta { text: "Hel".into() },
872            ModelEvent::TextDelta { text: "lo".into() },
873            ModelEvent::TextDelta { text: "!".into() },
874            ModelEvent::EndTurn {
875                stop_reason: "end_turn".into(),
876                usage: Usage {
877                    input_tokens: 11,
878                    output_tokens: 3,
879                    ..Default::default()
880                },
881            },
882        ]
883    }
884
885    fn config(
886        mode: RecorderMode,
887        root: &std::path::Path,
888        on_divergence: Divergence,
889    ) -> RecorderConfig {
890        RecorderConfig {
891            mode,
892            name: Some("run".into()),
893            root: root.to_path_buf(),
894            on_divergence,
895        }
896    }
897
898    fn prompt(text: &str) -> Vec<PromptBlock> {
899        vec![PromptBlock {
900            role: BlockRole::System,
901            content: text.into(),
902            cache_strategy: None,
903            name: None,
904            origin: Default::default(),
905        }]
906    }
907
908    fn tools() -> Vec<ToolDef> {
909        vec![ToolDef::new("Bash", "run", serde_json::json!({}))]
910    }
911
912    fn params(session: &str, step: u32) -> StreamParams {
913        StreamParams {
914            model: "test-model".into(),
915            max_tokens: 100,
916            thinking_mode: ThinkingMode::Off,
917            effort: None,
918            cache_edits: vec![],
919            origin: Some(CallOrigin::turn(session, 0, step)),
920            input_map: None,
921            provider_search: None,
922            usage_tap: Default::default(),
923        }
924    }
925
926    async fn drain(stream: ModelStream) -> Vec<ModelEvent> {
927        stream.filter_map(|e| async { e.ok() }).collect().await
928    }
929
930    #[tokio::test]
931    async fn unconfigured_recorder_writes_nothing() {
932        let root = tempfile::tempdir().unwrap();
933        let recorder = RecorderModel::new(ScriptedModel::ok(script()), None, "test");
934        let stream = recorder
935            .stream(
936                prompt("sys"),
937                tools(),
938                vec![],
939                params("S1", 0),
940                CancellationToken::new(),
941            )
942            .await
943            .unwrap();
944        assert_eq!(drain(stream).await.len(), 4);
945        assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0);
946    }
947
948    #[tokio::test]
949    async fn record_then_replay_reproduces_the_event_stream() {
950        let root = tempfile::tempdir().unwrap();
951
952        let recorder = RecorderModel::new(
953            ScriptedModel::ok(script()),
954            Some(config(
955                RecorderMode::Record,
956                root.path(),
957                Divergence::Strict,
958            )),
959            "test",
960        );
961        let recorded = drain(
962            recorder
963                .stream(
964                    prompt("sys"),
965                    tools(),
966                    vec![],
967                    params("S1", 0),
968                    CancellationToken::new(),
969                )
970                .await
971                .unwrap(),
972        )
973        .await;
974        drop(recorder);
975
976        // The replaying model must never reach the inner one.
977        let replayer = RecorderModel::new(
978            ScriptedModel::ok(vec![]),
979            Some(config(
980                RecorderMode::Replay,
981                root.path(),
982                Divergence::Strict,
983            )),
984            "test",
985        );
986        let replayed = drain(
987            replayer
988                .stream(
989                    prompt("sys"),
990                    tools(),
991                    vec![],
992                    params("S1", 0),
993                    CancellationToken::new(),
994                )
995                .await
996                .unwrap(),
997        )
998        .await;
999
1000        assert_eq!(format!("{replayed:?}"), format!("{recorded:?}"));
1001        assert_eq!(replayed.len(), 4);
1002    }
1003
1004    #[tokio::test]
1005    async fn token_boundaries_survive_a_record_replay_round_trip() {
1006        let root = tempfile::tempdir().unwrap();
1007        let recorder = RecorderModel::new(
1008            ScriptedModel::ok(script()),
1009            Some(config(
1010                RecorderMode::Record,
1011                root.path(),
1012                Divergence::Strict,
1013            )),
1014            "test",
1015        );
1016        drain(
1017            recorder
1018                .stream(
1019                    prompt("sys"),
1020                    tools(),
1021                    vec![],
1022                    params("S1", 0),
1023                    CancellationToken::new(),
1024                )
1025                .await
1026                .unwrap(),
1027        )
1028        .await;
1029        drop(recorder);
1030
1031        let recording = reader::load(&root.path().join("run")).unwrap();
1032        let texts: Vec<&str> = recording.calls[0]
1033            .response
1034            .iter()
1035            .filter_map(|e| match e {
1036                ModelEvent::TextDelta { text } => Some(text.as_str()),
1037                _ => None,
1038            })
1039            .collect();
1040        assert_eq!(texts, vec!["Hel", "lo", "!"], "deltas must not be merged");
1041    }
1042
1043    #[tokio::test]
1044    async fn a_recorded_failure_replays_as_a_failure() {
1045        let root = tempfile::tempdir().unwrap();
1046        let recorder = RecorderModel::new(
1047            ScriptedModel::overloaded(),
1048            Some(config(
1049                RecorderMode::Record,
1050                root.path(),
1051                Divergence::Strict,
1052            )),
1053            "test",
1054        );
1055        let err = recorder
1056            .stream(
1057                prompt("sys"),
1058                tools(),
1059                vec![],
1060                params("S1", 0),
1061                CancellationToken::new(),
1062            )
1063            .await
1064            .err()
1065            .expect("expected an error");
1066        assert_eq!(err.kind, ModelErrorKind::Overloaded);
1067        drop(recorder);
1068
1069        let replayer = RecorderModel::new(
1070            ScriptedModel::ok(script()),
1071            Some(config(
1072                RecorderMode::Replay,
1073                root.path(),
1074                Divergence::Strict,
1075            )),
1076            "test",
1077        );
1078        let replayed = replayer
1079            .stream(
1080                prompt("sys"),
1081                tools(),
1082                vec![],
1083                params("S1", 0),
1084                CancellationToken::new(),
1085            )
1086            .await;
1087        assert!(
1088            matches!(replayed, Err(ref e) if e.kind == ModelErrorKind::Overloaded),
1089            "a recorded overload must replay as an overload, not as a success"
1090        );
1091    }
1092
1093    #[tokio::test]
1094    async fn divergence_names_the_field_that_moved() {
1095        let root = tempfile::tempdir().unwrap();
1096        let recorder = RecorderModel::new(
1097            ScriptedModel::ok(script()),
1098            Some(config(
1099                RecorderMode::Record,
1100                root.path(),
1101                Divergence::Strict,
1102            )),
1103            "test",
1104        );
1105        drain(
1106            recorder
1107                .stream(
1108                    prompt("original system prompt"),
1109                    tools(),
1110                    vec![],
1111                    params("S1", 0),
1112                    CancellationToken::new(),
1113                )
1114                .await
1115                .unwrap(),
1116        )
1117        .await;
1118        drop(recorder);
1119
1120        let replayer = RecorderModel::new(
1121            ScriptedModel::ok(vec![]),
1122            Some(config(
1123                RecorderMode::Replay,
1124                root.path(),
1125                Divergence::Strict,
1126            )),
1127            "test",
1128        );
1129        let err = replayer
1130            .stream(
1131                prompt("a different system prompt"),
1132                tools(),
1133                vec![],
1134                params("S1", 0),
1135                CancellationToken::new(),
1136            )
1137            .await
1138            .err()
1139            .expect("expected an error");
1140        let message = err.to_string();
1141        assert!(
1142            message.contains("system[0]"),
1143            "the report must point at the field, got: {message}"
1144        );
1145    }
1146
1147    #[tokio::test]
1148    async fn warn_mode_plays_the_recording_despite_divergence() {
1149        let root = tempfile::tempdir().unwrap();
1150        let recorder = RecorderModel::new(
1151            ScriptedModel::ok(script()),
1152            Some(config(
1153                RecorderMode::Record,
1154                root.path(),
1155                Divergence::Strict,
1156            )),
1157            "test",
1158        );
1159        drain(
1160            recorder
1161                .stream(
1162                    prompt("original"),
1163                    tools(),
1164                    vec![],
1165                    params("S1", 0),
1166                    CancellationToken::new(),
1167                )
1168                .await
1169                .unwrap(),
1170        )
1171        .await;
1172        drop(recorder);
1173
1174        let replayer = RecorderModel::new(
1175            ScriptedModel::ok(vec![]),
1176            Some(config(RecorderMode::Replay, root.path(), Divergence::Warn)),
1177            "test",
1178        );
1179        let replayed = drain(
1180            replayer
1181                .stream(
1182                    prompt("changed"),
1183                    tools(),
1184                    vec![],
1185                    params("S1", 0),
1186                    CancellationToken::new(),
1187                )
1188                .await
1189                .unwrap(),
1190        )
1191        .await;
1192        assert_eq!(replayed.len(), 4);
1193    }
1194
1195    #[tokio::test]
1196    async fn a_stream_dropped_mid_response_records_a_cancelled_outcome() {
1197        let root = tempfile::tempdir().unwrap();
1198        let recorder = RecorderModel::new(
1199            ScriptedModel::ok(script()),
1200            Some(config(
1201                RecorderMode::Record,
1202                root.path(),
1203                Divergence::Strict,
1204            )),
1205            "test",
1206        );
1207        {
1208            let mut stream = recorder
1209                .stream(
1210                    prompt("sys"),
1211                    tools(),
1212                    vec![],
1213                    params("S1", 0),
1214                    CancellationToken::new(),
1215                )
1216                .await
1217                .unwrap();
1218            let _first = stream.next().await;
1219        }
1220        drop(recorder);
1221
1222        let recording = reader::load(&root.path().join("run")).unwrap();
1223        let end = recording.calls[0]
1224            .end
1225            .as_ref()
1226            .expect("call must be closed");
1227        assert_eq!(end.outcome, Outcome::Cancelled);
1228    }
1229
1230    #[tokio::test]
1231    async fn a_stream_dropped_after_its_final_event_records_the_call_as_answered() {
1232        let root = tempfile::tempdir().unwrap();
1233        let recorder = RecorderModel::new(
1234            ScriptedModel::ok(script()),
1235            Some(config(
1236                RecorderMode::Record,
1237                root.path(),
1238                Divergence::Strict,
1239            )),
1240            "test",
1241        );
1242        {
1243            let mut stream = recorder
1244                .stream(
1245                    prompt("sys"),
1246                    tools(),
1247                    vec![],
1248                    params("S1", 0),
1249                    CancellationToken::new(),
1250                )
1251                .await
1252                .unwrap();
1253            while let Some(event) = stream.next().await {
1254                if matches!(event, Ok(ModelEvent::EndTurn { .. })) {
1255                    break;
1256                }
1257            }
1258        }
1259        drop(recorder);
1260
1261        let recording = reader::load(&root.path().join("run")).unwrap();
1262        let end = recording.calls[0]
1263            .end
1264            .as_ref()
1265            .expect("call must be closed");
1266        assert_eq!(end.outcome, Outcome::Ok);
1267        assert!(end.stop_reason.is_some());
1268    }
1269
1270    #[tokio::test]
1271    async fn the_request_is_on_disk_before_the_response_arrives() {
1272        let root = tempfile::tempdir().unwrap();
1273        let recorder = RecorderModel::new(
1274            ScriptedModel::ok(script()),
1275            Some(config(
1276                RecorderMode::Record,
1277                root.path(),
1278                Divergence::Strict,
1279            )),
1280            "test",
1281        );
1282        let _stream = recorder
1283            .stream(
1284                prompt("sys"),
1285                tools(),
1286                vec![],
1287                params("S1", 0),
1288                CancellationToken::new(),
1289            )
1290            .await
1291            .unwrap();
1292
1293        let content = std::fs::read_to_string(root.path().join("run").join("calls.jsonl")).unwrap();
1294        assert!(
1295            content.contains(r#""type":"call""#),
1296            "the request must be durable before the stream is consumed"
1297        );
1298    }
1299
1300    #[tokio::test]
1301    async fn unchanged_request_parts_are_stored_once() {
1302        let root = tempfile::tempdir().unwrap();
1303        let recorder = RecorderModel::new(
1304            ScriptedModel::ok(script()),
1305            Some(config(
1306                RecorderMode::Record,
1307                root.path(),
1308                Divergence::Strict,
1309            )),
1310            "test",
1311        );
1312        for step in 0..3 {
1313            drain(
1314                recorder
1315                    .stream(
1316                        prompt("stable system prompt"),
1317                        tools(),
1318                        vec![],
1319                        params("S1", step),
1320                        CancellationToken::new(),
1321                    )
1322                    .await
1323                    .unwrap(),
1324            )
1325            .await;
1326        }
1327        drop(recorder);
1328
1329        let recording = reader::load(&root.path().join("run")).unwrap();
1330        assert_eq!(recording.calls.len(), 3);
1331        // One blob for the single system block, one for the tool table.
1332        let blobs = std::fs::read_dir(root.path().join("run").join("blobs"))
1333            .unwrap()
1334            .count();
1335        assert_eq!(blobs, 2, "identical request parts must dedup across calls");
1336    }
1337
1338    #[tokio::test]
1339    async fn each_session_records_into_its_own_directory() {
1340        let root = tempfile::tempdir().unwrap();
1341        let recorder = RecorderModel::new(
1342            ScriptedModel::ok(script()),
1343            Some(RecorderConfig {
1344                mode: RecorderMode::Record,
1345                name: None,
1346                root: root.path().to_path_buf(),
1347                on_divergence: Divergence::Strict,
1348            }),
1349            "test",
1350        );
1351        for session in ["parent", "subagent"] {
1352            drain(
1353                recorder
1354                    .stream(
1355                        prompt("sys"),
1356                        tools(),
1357                        vec![],
1358                        params(session, 0),
1359                        CancellationToken::new(),
1360                    )
1361                    .await
1362                    .unwrap(),
1363            )
1364            .await;
1365        }
1366        drop(recorder);
1367
1368        assert!(root.path().join("parent").join("calls.jsonl").exists());
1369        assert!(root.path().join("subagent").join("calls.jsonl").exists());
1370        assert_eq!(
1371            reader::load(&root.path().join("parent"))
1372                .unwrap()
1373                .calls
1374                .len(),
1375            1
1376        );
1377    }
1378
1379    /// The header is what lets a directory of recordings be read as one tree.
1380    #[tokio::test]
1381    async fn a_sub_agents_header_names_its_parent_and_kind() {
1382        let root = tempfile::tempdir().unwrap();
1383        let recorder = RecorderModel::new(
1384            ScriptedModel::ok(vec![]),
1385            Some(RecorderConfig {
1386                mode: RecorderMode::Record,
1387                name: None,
1388                root: root.path().to_path_buf(),
1389                on_divergence: Divergence::Strict,
1390            }),
1391            "test",
1392        );
1393        let mut child = params("child", 0);
1394        child.origin = child
1395            .origin
1396            .map(|o| o.with_lineage(Some("parent".into()), Some("code-reviewer".into())));
1397        drain(
1398            recorder
1399                .stream(
1400                    prompt("sys"),
1401                    tools(),
1402                    vec![],
1403                    child,
1404                    CancellationToken::new(),
1405                )
1406                .await
1407                .unwrap(),
1408        )
1409        .await;
1410        drop(recorder);
1411
1412        let header = reader::load(&root.path().join("child")).unwrap().header;
1413        assert_eq!(header.parent.as_deref(), Some("parent"));
1414        assert_eq!(header.agent_type.as_deref(), Some("code-reviewer"));
1415    }
1416
1417    /// An auxiliary call belongs to the session that made it, not to a shared
1418    /// name that concurrent sessions would then truncate out from under it.
1419    #[tokio::test]
1420    async fn an_auxiliary_call_is_filed_under_its_own_session() {
1421        let root = tempfile::tempdir().unwrap();
1422        let recorder = RecorderModel::new(
1423            ScriptedModel::ok(vec![]),
1424            Some(RecorderConfig {
1425                mode: RecorderMode::Record,
1426                name: None,
1427                root: root.path().to_path_buf(),
1428                on_divergence: Divergence::Strict,
1429            }),
1430            "test",
1431        );
1432        let mut aux = params("S9", 0);
1433        aux.origin = Some(CallOrigin::auxiliary("S9", "compact"));
1434        drain(
1435            recorder
1436                .stream(
1437                    prompt("sys"),
1438                    tools(),
1439                    vec![],
1440                    aux,
1441                    CancellationToken::new(),
1442                )
1443                .await
1444                .unwrap(),
1445        )
1446        .await;
1447        drop(recorder);
1448
1449        assert!(
1450            !root.path().join("unattributed").exists(),
1451            "auxiliary calls must not land in a shared directory"
1452        );
1453        let call = &reader::load(&root.path().join("S9")).unwrap().calls[0].request;
1454        assert_eq!(call.purpose.as_deref(), Some("compact"));
1455        assert_eq!(
1456            (call.turn, call.step),
1457            (0, 0),
1458            "a call outside a turn has no turn coordinates to report"
1459        );
1460    }
1461
1462    /// A parent and its sub-agent recording under one name interleave on disk,
1463    /// and the order they interleave in is scheduling luck. Replay must hand
1464    /// each session its own calls in its own order, not the file's order.
1465    #[tokio::test]
1466    async fn interleaved_sessions_replay_as_separate_slices() {
1467        let root = tempfile::tempdir().unwrap();
1468        let config = |mode| RecorderConfig {
1469            mode,
1470            // One shared name: this is the setup that interleaves.
1471            name: Some("run".into()),
1472            root: root.path().to_path_buf(),
1473            on_divergence: Divergence::Strict,
1474        };
1475
1476        let recorder = RecorderModel::new(
1477            ScriptedModel::ok(vec![ModelEvent::TextDelta { text: "x".into() }]),
1478            Some(config(RecorderMode::Record)),
1479            "test",
1480        );
1481        // parent, child, child, parent — the child's calls land between the
1482        // parent's, exactly as a real delegation would.
1483        for (session, step) in [("P", 0), ("C", 0), ("C", 1), ("P", 1)] {
1484            let mut p = params(session, step);
1485            p.origin = Some(CallOrigin::turn(session, 0, step));
1486            drain(
1487                recorder
1488                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
1489                    .await
1490                    .unwrap(),
1491            )
1492            .await;
1493        }
1494        drop(recorder);
1495
1496        let recording = reader::load(&root.path().join("run")).unwrap();
1497        assert_eq!(recording.calls.len(), 4);
1498
1499        // Replaying the child first must still get the child's two calls, even
1500        // though the parent's call is first in the file.
1501        let replayer = RecorderModel::new(
1502            ScriptedModel::ok(vec![]),
1503            Some(config(RecorderMode::Replay)),
1504            "test",
1505        );
1506        for step in [0, 1] {
1507            let mut p = params("C", step);
1508            p.origin = Some(CallOrigin::turn("C", 0, step));
1509            let events = drain(
1510                replayer
1511                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
1512                    .await
1513                    .unwrap(),
1514            )
1515            .await;
1516            assert_eq!(events.len(), 1, "child call #{step} should replay");
1517        }
1518        // A third child call is one more than the child ever made.
1519        let mut extra = params("C", 2);
1520        extra.origin = Some(CallOrigin::turn("C", 0, 2));
1521        let Err(err) = replayer
1522            .stream(
1523                prompt("sys"),
1524                tools(),
1525                vec![],
1526                extra,
1527                CancellationToken::new(),
1528            )
1529            .await
1530        else {
1531            panic!("a third child call has nothing to replay against")
1532        };
1533        assert!(
1534            err.to_string()
1535                .contains("2 conversation call(s) for session"),
1536            "the error should name the session that ran out: {err}"
1537        );
1538    }
1539
1540    /// Live session ids are freshly random every run, so the ids in a recording
1541    /// are never the ids of the run replaying it. Binding therefore falls back
1542    /// to first-call order — and since that is the *production* path, exact-id
1543    /// matching alone proving out is not enough.
1544    #[tokio::test]
1545    async fn sessions_with_new_ids_bind_in_first_call_order() {
1546        let root = tempfile::tempdir().unwrap();
1547        let config = |mode| RecorderConfig {
1548            mode,
1549            name: Some("run".into()),
1550            root: root.path().to_path_buf(),
1551            on_divergence: Divergence::Warn,
1552        };
1553
1554        let recorder = RecorderModel::new(
1555            ScriptedModel::ok(vec![ModelEvent::TextDelta { text: "x".into() }]),
1556            Some(config(RecorderMode::Record)),
1557            "test",
1558        );
1559        // Parent calls first, then its child — the order a live run guarantees.
1560        for (session, step) in [("REC-parent", 0), ("REC-child", 0), ("REC-parent", 1)] {
1561            let mut p = params(session, step);
1562            p.origin = Some(CallOrigin::turn(session, 0, step));
1563            drain(
1564                recorder
1565                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
1566                    .await
1567                    .unwrap(),
1568            )
1569            .await;
1570        }
1571        drop(recorder);
1572
1573        let replayer = RecorderModel::new(
1574            ScriptedModel::ok(vec![]),
1575            Some(config(RecorderMode::Replay)),
1576            "test",
1577        );
1578        // Entirely different ids, same order of first call.
1579        let mut consumed = Vec::new();
1580        for (session, step) in [("LIVE-a", 0), ("LIVE-b", 0), ("LIVE-a", 1)] {
1581            let mut p = params(session, step);
1582            p.origin = Some(CallOrigin::turn(session, 0, step));
1583            let events = drain(
1584                replayer
1585                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
1586                    .await
1587                    .unwrap(),
1588            )
1589            .await;
1590            consumed.push(events.len());
1591        }
1592        assert_eq!(
1593            consumed,
1594            vec![1, 1, 1],
1595            "each live session should have replayed its counterpart's calls"
1596        );
1597
1598        // `LIVE-a` claimed the parent (2 calls), so a third call on it is one
1599        // past the end — proof it bound to the parent and not the child.
1600        let mut extra = params("LIVE-a", 2);
1601        extra.origin = Some(CallOrigin::turn("LIVE-a", 0, 2));
1602        let Err(err) = replayer
1603            .stream(
1604                prompt("sys"),
1605                tools(),
1606                vec![],
1607                extra,
1608                CancellationToken::new(),
1609            )
1610            .await
1611        else {
1612            panic!("the parent's slice holds only two calls")
1613        };
1614        assert!(
1615            err.to_string().contains("REC-parent"),
1616            "the error should name the recorded session it bound to: {err}"
1617        );
1618    }
1619
1620    /// An override edits the replayed response without touching the recording,
1621    /// which is what makes "what if the model had said X" a reviewable file
1622    /// rather than a destroyed fixture.
1623    #[tokio::test]
1624    async fn an_override_replaces_a_response_and_leaves_the_recording_alone() {
1625        let root = tempfile::tempdir().unwrap();
1626        let config = |mode| RecorderConfig {
1627            mode,
1628            name: Some("run".into()),
1629            root: root.path().to_path_buf(),
1630            on_divergence: Divergence::Strict,
1631        };
1632
1633        let recorder = RecorderModel::new(
1634            ScriptedModel::ok(vec![ModelEvent::TextDelta {
1635                text: "recorded".into(),
1636            }]),
1637            Some(config(RecorderMode::Record)),
1638            "test",
1639        );
1640        drain(
1641            recorder
1642                .stream(
1643                    prompt("sys"),
1644                    tools(),
1645                    vec![],
1646                    params("S1", 0),
1647                    CancellationToken::new(),
1648                )
1649                .await
1650                .unwrap(),
1651        )
1652        .await;
1653        drop(recorder);
1654
1655        let before = std::fs::read_to_string(root.path().join("run").join("calls.jsonl")).unwrap();
1656        std::fs::write(
1657            root.path().join("run").join(override_doc::OVERRIDE_FILE),
1658            r#"{"patches":[{"at":0,"response":[{"kind":"text_delta","text":"edited"}]}]}"#,
1659        )
1660        .unwrap();
1661
1662        let replayer = RecorderModel::new(
1663            ScriptedModel::ok(vec![]),
1664            Some(config(RecorderMode::Replay)),
1665            "test",
1666        );
1667        let events = drain(
1668            replayer
1669                .stream(
1670                    prompt("sys"),
1671                    tools(),
1672                    vec![],
1673                    params("S1", 0),
1674                    CancellationToken::new(),
1675                )
1676                .await
1677                .unwrap(),
1678        )
1679        .await;
1680        assert_eq!(
1681            format!("{events:?}"),
1682            format!(
1683                "{:?}",
1684                vec![ModelEvent::TextDelta {
1685                    text: "edited".into()
1686                }]
1687            )
1688        );
1689        assert_eq!(
1690            std::fs::read_to_string(root.path().join("run").join("calls.jsonl")).unwrap(),
1691            before,
1692            "the recording itself must be untouched"
1693        );
1694    }
1695
1696    /// A run that stops short of the recording passes every per-call check.
1697    /// The only place to notice is at the end.
1698    #[tokio::test]
1699    async fn a_replay_that_stops_short_is_reported_at_the_end() {
1700        let root = tempfile::tempdir().unwrap();
1701        let config = |mode| RecorderConfig {
1702            mode,
1703            name: Some("run".into()),
1704            root: root.path().to_path_buf(),
1705            on_divergence: Divergence::Strict,
1706        };
1707
1708        let recorder = RecorderModel::new(
1709            ScriptedModel::ok(vec![]),
1710            Some(config(RecorderMode::Record)),
1711            "test",
1712        );
1713        for step in [0, 1] {
1714            drain(
1715                recorder
1716                    .stream(
1717                        prompt("sys"),
1718                        tools(),
1719                        vec![],
1720                        params("S1", step),
1721                        CancellationToken::new(),
1722                    )
1723                    .await
1724                    .unwrap(),
1725            )
1726            .await;
1727        }
1728        drop(recorder);
1729
1730        let shared = Recorder::new();
1731        let replayer = RecorderModel::shared(
1732            ScriptedModel::ok(vec![]),
1733            Some(config(RecorderMode::Replay)),
1734            "test",
1735            shared.clone(),
1736        );
1737        // Only one of the two recorded calls.
1738        drain(
1739            replayer
1740                .stream(
1741                    prompt("sys"),
1742                    tools(),
1743                    vec![],
1744                    params("S1", 0),
1745                    CancellationToken::new(),
1746                )
1747                .await
1748                .unwrap(),
1749        )
1750        .await;
1751
1752        let unconsumed = shared.unconsumed();
1753        assert_eq!(unconsumed.len(), 1, "got {unconsumed:?}");
1754        assert!(
1755            unconsumed[0].contains("replayed 1 of 2"),
1756            "got {unconsumed:?}"
1757        );
1758    }
1759
1760    /// A call that cannot name a session has no recording to belong to, and
1761    /// must pass straight through rather than inventing one.
1762    #[tokio::test]
1763    async fn a_call_with_no_session_is_not_recorded() {
1764        let root = tempfile::tempdir().unwrap();
1765        let recorder = RecorderModel::new(
1766            ScriptedModel::ok(vec![]),
1767            Some(RecorderConfig {
1768                mode: RecorderMode::Record,
1769                name: None,
1770                root: root.path().to_path_buf(),
1771                on_divergence: Divergence::Strict,
1772            }),
1773            "test",
1774        );
1775        let mut anonymous = params("ignored", 0);
1776        anonymous.origin = None;
1777        drain(
1778            recorder
1779                .stream(
1780                    prompt("sys"),
1781                    tools(),
1782                    vec![],
1783                    anonymous,
1784                    CancellationToken::new(),
1785                )
1786                .await
1787                .unwrap(),
1788        )
1789        .await;
1790        drop(recorder);
1791
1792        assert_eq!(
1793            std::fs::read_dir(root.path()).unwrap().count(),
1794            0,
1795            "nothing should have been written"
1796        );
1797    }
1798
1799    #[tokio::test]
1800    async fn replaying_past_the_end_of_a_recording_says_so() {
1801        let root = tempfile::tempdir().unwrap();
1802        let recorder = RecorderModel::new(
1803            ScriptedModel::ok(script()),
1804            Some(config(
1805                RecorderMode::Record,
1806                root.path(),
1807                Divergence::Strict,
1808            )),
1809            "test",
1810        );
1811        drain(
1812            recorder
1813                .stream(
1814                    prompt("sys"),
1815                    tools(),
1816                    vec![],
1817                    params("S1", 0),
1818                    CancellationToken::new(),
1819                )
1820                .await
1821                .unwrap(),
1822        )
1823        .await;
1824        drop(recorder);
1825
1826        let replayer = RecorderModel::new(
1827            ScriptedModel::ok(vec![]),
1828            Some(config(
1829                RecorderMode::Replay,
1830                root.path(),
1831                Divergence::Strict,
1832            )),
1833            "test",
1834        );
1835        for _ in 0..1 {
1836            drain(
1837                replayer
1838                    .stream(
1839                        prompt("sys"),
1840                        tools(),
1841                        vec![],
1842                        params("S1", 0),
1843                        CancellationToken::new(),
1844                    )
1845                    .await
1846                    .unwrap(),
1847            )
1848            .await;
1849        }
1850        let err = replayer
1851            .stream(
1852                prompt("sys"),
1853                tools(),
1854                vec![],
1855                params("S1", 1),
1856                CancellationToken::new(),
1857            )
1858            .await
1859            .err()
1860            .expect("expected an error");
1861        assert!(err.to_string().contains("asked for #2"), "{err}");
1862    }
1863
1864    fn title_params(session: &str) -> StreamParams {
1865        let mut p = params(session, 0);
1866        p.origin = Some(CallOrigin::auxiliary(
1867            session,
1868            base::interface::model::call_purpose::TITLE,
1869        ));
1870        p
1871    }
1872
1873    fn text(events: &[ModelEvent]) -> String {
1874        events
1875            .iter()
1876            .filter_map(|e| match e {
1877                ModelEvent::TextDelta { text } => Some(text.as_str()),
1878                _ => None,
1879            })
1880            .collect()
1881    }
1882
1883    /// Each call answered by a model of its own, all into one recording.
1884    async fn record_calls(root: &std::path::Path, calls: Vec<(StreamParams, &str)>) {
1885        record_prompted_calls(
1886            root,
1887            calls
1888                .into_iter()
1889                .map(|(params, answer)| (params, "sys", answer))
1890                .collect(),
1891        )
1892        .await;
1893    }
1894
1895    async fn record_prompted_calls(root: &std::path::Path, calls: Vec<(StreamParams, &str, &str)>) {
1896        let shared = Recorder::new();
1897        for (params, system, answer) in calls {
1898            let recorder = RecorderModel::shared(
1899                ScriptedModel::ok(vec![ModelEvent::TextDelta {
1900                    text: answer.into(),
1901                }]),
1902                Some(config(RecorderMode::Record, root, Divergence::Strict)),
1903                "test",
1904                shared.clone(),
1905            );
1906            drain(
1907                recorder
1908                    .stream(
1909                        prompt(system),
1910                        tools(),
1911                        vec![],
1912                        params,
1913                        CancellationToken::new(),
1914                    )
1915                    .await
1916                    .unwrap(),
1917            )
1918            .await;
1919        }
1920    }
1921
1922    /// Naming is not part of the conversation: a recording made without it
1923    /// replays a run that names, and even a strict replay only reports the
1924    /// naming call as absent instead of as a divergence or an overshoot.
1925    #[tokio::test]
1926    async fn a_title_call_the_recording_lacks_is_not_recorded_even_under_strict_replay() {
1927        let root = tempfile::tempdir().unwrap();
1928        record_calls(root.path(), vec![(params("S1", 0), "answer")]).await;
1929
1930        let shared = Recorder::new();
1931        let replayer = RecorderModel::shared(
1932            ScriptedModel::overloaded(),
1933            Some(config(
1934                RecorderMode::Replay,
1935                root.path(),
1936                Divergence::Strict,
1937            )),
1938            "test",
1939            shared.clone(),
1940        );
1941        let turn = drain(
1942            replayer
1943                .stream(
1944                    prompt("sys"),
1945                    tools(),
1946                    vec![],
1947                    params("S1", 0),
1948                    CancellationToken::new(),
1949                )
1950                .await
1951                .unwrap(),
1952        )
1953        .await;
1954        assert_eq!(text(&turn), "answer");
1955
1956        match replayer
1957            .stream(
1958                prompt("sys"),
1959                tools(),
1960                vec![],
1961                title_params("S1"),
1962                CancellationToken::new(),
1963            )
1964            .await
1965        {
1966            Err(e) if e.kind == ModelErrorKind::NotRecorded => {}
1967            Err(e) => panic!("expected NotRecorded, got {e}"),
1968            Ok(_) => panic!("a title call the recording lacks was answered"),
1969        }
1970        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
1971    }
1972
1973    #[tokio::test]
1974    async fn a_recorded_title_call_replays_in_its_place() {
1975        let root = tempfile::tempdir().unwrap();
1976        record_calls(
1977            root.path(),
1978            vec![
1979                (params("S1", 0), "answer"),
1980                (title_params("S1"), "a title"),
1981                (params("S1", 1), "second"),
1982            ],
1983        )
1984        .await;
1985        let calls = reader::load(&root.path().join("run")).unwrap().calls;
1986        assert_eq!(calls[1].request.purpose.as_deref(), Some("title"));
1987
1988        let shared = Recorder::new();
1989        let replayer = RecorderModel::shared(
1990            ScriptedModel::overloaded(),
1991            Some(config(
1992                RecorderMode::Replay,
1993                root.path(),
1994                Divergence::Strict,
1995            )),
1996            "test",
1997            shared.clone(),
1998        );
1999        let mut answers = Vec::new();
2000        for params in [params("S1", 0), title_params("S1"), params("S1", 1)] {
2001            let events = drain(
2002                replayer
2003                    .stream(
2004                        prompt("sys"),
2005                        tools(),
2006                        vec![],
2007                        params,
2008                        CancellationToken::new(),
2009                    )
2010                    .await
2011                    .unwrap(),
2012            )
2013            .await;
2014            answers.push(text(&events));
2015        }
2016        assert_eq!(answers, ["answer", "a title", "second"]);
2017        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
2018    }
2019
2020    /// The other direction: a run that does not name is not handed the
2021    /// recorded title as the answer to its next call, and is not reported as
2022    /// having stopped short for leaving it unasked.
2023    #[tokio::test]
2024    async fn a_recorded_title_call_the_run_does_not_ask_for_is_passed_over() {
2025        let root = tempfile::tempdir().unwrap();
2026        record_calls(
2027            root.path(),
2028            vec![
2029                (params("S1", 0), "answer"),
2030                (title_params("S1"), "a title"),
2031                (params("S1", 1), "second"),
2032                (title_params("S1"), "a late title"),
2033            ],
2034        )
2035        .await;
2036
2037        let shared = Recorder::new();
2038        let replayer = RecorderModel::shared(
2039            ScriptedModel::overloaded(),
2040            Some(config(
2041                RecorderMode::Replay,
2042                root.path(),
2043                Divergence::Strict,
2044            )),
2045            "test",
2046            shared.clone(),
2047        );
2048        let mut answers = Vec::new();
2049        for step in [0, 1] {
2050            let events = drain(
2051                replayer
2052                    .stream(
2053                        prompt("sys"),
2054                        tools(),
2055                        vec![],
2056                        params("S1", step),
2057                        CancellationToken::new(),
2058                    )
2059                    .await
2060                    .unwrap(),
2061            )
2062            .await;
2063            answers.push(text(&events));
2064        }
2065        assert_eq!(answers, ["answer", "second"]);
2066        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
2067    }
2068
2069    fn aux_params(session: &str, purpose: &str) -> StreamParams {
2070        let mut p = params(session, 0);
2071        p.origin = Some(CallOrigin::auxiliary(session, purpose));
2072        p
2073    }
2074
2075    /// A strict replayer whose inner model would answer `"live"` — a replay
2076    /// that reaches it shows up in the answer.
2077    fn strict_replayer(root: &std::path::Path, shared: Arc<Recorder>) -> RecorderModel {
2078        RecorderModel::shared(
2079            ScriptedModel::ok(vec![ModelEvent::TextDelta {
2080                text: "live".into(),
2081            }]),
2082            Some(config(RecorderMode::Replay, root, Divergence::Strict)),
2083            "test",
2084            shared,
2085        )
2086    }
2087
2088    async fn ask(
2089        replayer: &RecorderModel,
2090        system: &str,
2091        params: StreamParams,
2092    ) -> Result<String, ModelError> {
2093        let stream = replayer
2094            .stream(
2095                prompt(system),
2096                tools(),
2097                vec![],
2098                params,
2099                CancellationToken::new(),
2100            )
2101            .await?;
2102        Ok(text(&drain(stream).await))
2103    }
2104
2105    /// Memory extraction runs in the background, so its call can land between
2106    /// a turn and that turn's naming call. The naming call still finds its
2107    /// recording, and the next turn is not handed the extraction's answer.
2108    #[tokio::test]
2109    async fn a_title_call_recorded_after_a_memory_extraction_replays_from_the_recording() {
2110        let root = tempfile::tempdir().unwrap();
2111        record_calls(
2112            root.path(),
2113            vec![
2114                (params("S1", 0), "answer"),
2115                (aux_params("S1", call_purpose::MEMORY), "memories"),
2116                (title_params("S1"), "a title"),
2117                (params("S1", 1), "second"),
2118            ],
2119        )
2120        .await;
2121
2122        let shared = Recorder::new();
2123        let replayer = strict_replayer(root.path(), shared.clone());
2124        let mut answers = Vec::new();
2125        for params in [
2126            params("S1", 0),
2127            title_params("S1"),
2128            params("S1", 1),
2129            aux_params("S1", call_purpose::MEMORY),
2130        ] {
2131            answers.push(ask(&replayer, "sys", params).await.unwrap());
2132        }
2133        assert_eq!(answers, ["answer", "a title", "second", "memories"]);
2134        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
2135    }
2136
2137    #[tokio::test]
2138    async fn auxiliary_calls_replayed_in_another_order_each_get_their_own_response() {
2139        let root = tempfile::tempdir().unwrap();
2140        record_calls(
2141            root.path(),
2142            vec![
2143                (aux_params("S1", call_purpose::MEMORY), "first memories"),
2144                (params("S1", 0), "answer"),
2145                (aux_params("S1", call_purpose::COMPACT), "summary"),
2146                (aux_params("S1", call_purpose::MEMORY), "second memories"),
2147                (title_params("S1"), "a title"),
2148            ],
2149        )
2150        .await;
2151
2152        let shared = Recorder::new();
2153        let replayer = strict_replayer(root.path(), shared.clone());
2154        let mut answers = Vec::new();
2155        for params in [
2156            title_params("S1"),
2157            aux_params("S1", call_purpose::COMPACT),
2158            params("S1", 0),
2159            aux_params("S1", call_purpose::MEMORY),
2160            aux_params("S1", call_purpose::MEMORY),
2161        ] {
2162            answers.push(ask(&replayer, "sys", params).await.unwrap());
2163        }
2164        assert_eq!(
2165            answers,
2166            [
2167                "a title",
2168                "summary",
2169                "answer",
2170                "first memories",
2171                "second memories"
2172            ]
2173        );
2174        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
2175    }
2176
2177    #[tokio::test]
2178    async fn conversation_calls_out_of_their_recorded_order_diverge_under_strict_replay() {
2179        let root = tempfile::tempdir().unwrap();
2180        record_prompted_calls(
2181            root.path(),
2182            vec![
2183                (params("S1", 0), "first prompt", "first"),
2184                (aux_params("S1", call_purpose::MEMORY), "sys", "memories"),
2185                (params("S1", 1), "second prompt", "second"),
2186            ],
2187        )
2188        .await;
2189
2190        let replayer = strict_replayer(root.path(), Recorder::new());
2191        let err = ask(&replayer, "second prompt", params("S1", 1))
2192            .await
2193            .expect_err("a conversation call out of order must diverge");
2194        assert!(
2195            err.to_string().contains("diverges") && err.to_string().contains("system[0]"),
2196            "{err}"
2197        );
2198    }
2199
2200    #[tokio::test]
2201    async fn an_auxiliary_call_the_recording_lacks_fails_without_reaching_the_model() {
2202        let root = tempfile::tempdir().unwrap();
2203        record_calls(
2204            root.path(),
2205            vec![(params("S1", 0), "answer"), (params("S1", 1), "second")],
2206        )
2207        .await;
2208
2209        let replayer = strict_replayer(root.path(), Recorder::new());
2210        assert_eq!(
2211            ask(&replayer, "sys", params("S1", 0)).await.unwrap(),
2212            "answer"
2213        );
2214        match ask(&replayer, "sys", aux_params("S1", call_purpose::MEMORY)).await {
2215            Err(e) if e.kind == ModelErrorKind::Protocol => {
2216                assert!(e.message.contains("\"memory\""), "{}", e.message)
2217            }
2218            Err(e) => panic!("expected an internal error, got {e}"),
2219            Ok(answer) => panic!("a memory call the recording lacks was answered: {answer:?}"),
2220        }
2221        assert_eq!(
2222            ask(&replayer, "sys", params("S1", 1)).await.unwrap(),
2223            "second",
2224            "the failed auxiliary call must not take the next conversation call"
2225        );
2226    }
2227
2228    #[tokio::test]
2229    async fn a_recorded_memory_extraction_the_run_does_not_ask_for_is_reported_at_the_end() {
2230        let root = tempfile::tempdir().unwrap();
2231        record_calls(
2232            root.path(),
2233            vec![
2234                (params("S1", 0), "answer"),
2235                (aux_params("S1", call_purpose::MEMORY), "memories"),
2236            ],
2237        )
2238        .await;
2239
2240        let shared = Recorder::new();
2241        let replayer = strict_replayer(root.path(), shared.clone());
2242        assert_eq!(
2243            ask(&replayer, "sys", params("S1", 0)).await.unwrap(),
2244            "answer"
2245        );
2246        let unconsumed = shared.unconsumed();
2247        assert_eq!(unconsumed.len(), 1, "got {unconsumed:?}");
2248        assert!(
2249            unconsumed[0].contains("replayed 1 of 2"),
2250            "got {unconsumed:?}"
2251        );
2252    }
2253}