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