//! Replay evidence derived from durable session state (`SMH-SPEC-SPEC0001`,
//! Sessions).
//!
//! A trace is an ordered, provider-free reconstruction of what a session
//! recorded. It is derived only from persisted entry records, never from
//! decoded content, so the same session file always produces the same trace,
//! byte for byte.
mod lifecycle;
use crate::session::{
COMPACTION_KIND, EntryContent, EntryFrame, EntryKind, SessionHeader, TOOL_MUTATION_KIND,
};
use crate::store::SessionReader;
use serde::Deserialize;
use smith::error::Result;
use smith::id::{SessionId, ToolCallId};
/// Replay-relevant trace record (durable replay evidence).
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct TraceRecord {
/// Timestamp of the recorded event, in Unix milliseconds.
pub timestamp_ms: i64,
/// Session the event belongs to.
pub session_id: SessionId,
/// Event kind.
pub kind: TraceKind,
/// Stable reference to the recorded event.
pub event_ref: String,
}
/// Kind of replay event.
#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub enum TraceKind {
/// Session created.
SessionCreated,
/// Entry added.
EntryAdded,
/// Message streamed.
MessageStreamed,
/// Tool call emitted.
ToolCallEmitted,
/// Raw tool result observed; not authoritative effect completion.
ToolResultReceived,
/// Authoritative tool completion: explicit durable metadata or a replayed
/// incomplete lifecycle synthesized as `unknown`.
ToolMutationCompleted,
/// Explicit host child invocation admitted.
ChildInvocationStarted,
/// Explicit host child invocation durably completed.
ChildInvocationCompleted,
/// Primitive admitted under an explicit child invocation.
NestedEffectStarted,
/// Primitive durably completed under an explicit child invocation.
NestedEffectCompleted,
/// Host lifecycle handler intent acknowledged.
LifecycleInvocationStarted,
/// Host lifecycle handler outcome acknowledged, not mutation evidence.
LifecycleInvocationCompleted,
/// Handler outcome missing: unknown and never automatically retried.
LifecycleInvocationIncomplete,
/// Primitive intent acknowledged under a lifecycle handler.
LifecycleEffectStarted,
/// Primitive result and mutation evidence acknowledged.
LifecycleEffectCompleted,
/// Primitive completion missing: mutation remains unknown.
LifecycleEffectIncomplete,
/// Compaction occurred.
Compaction,
/// Replay started.
ReplayStarted,
/// Replay completed.
ReplayCompleted,
}
/// Visit durable trace records for the selected history in source order.
///
/// Each entry contributes the record kind matching what it recorded, so tool
/// activity and compaction remain visible rather than collapsing into a
/// generic entry event. A raw result is authoritative only when its matching
/// mutation metadata is present; otherwise replay emits a completed `unknown`
/// mutation record. One pending lifecycle is retained while history is streamed
/// through [`SessionReader::replay_at`], never a whole-history call map.
///
/// # Errors
///
/// Returns a reader validation, storage, ancestry, or visitor error.
pub fn trace(
reader: &SessionReader,
frame_bytes_max: usize,
visit: impl FnMut(TraceRecord) -> Result<()>,
) -> Result<()> {
let header = reader.header(frame_bytes_max)?;
trace_selected(reader, &header, frame_bytes_max, visit).map(|_| ())
}
/// Replay durable selected history without a provider, yielding each record
/// in source order.
///
/// Replay is framed by exactly one start and completion record. Its completion
/// timestamp and entry count derive from the durable selected tip, never live
/// effective context.
///
/// # Errors
///
/// Returns a reader validation, storage, ancestry, or visitor error.
pub fn replay(
reader: &SessionReader,
frame_bytes_max: usize,
mut visit: impl FnMut(TraceRecord) -> Result<()>,
) -> Result<()> {
let header = reader.header(frame_bytes_max)?;
visit(TraceRecord {
timestamp_ms: 0,
session_id: header.session_id,
kind: TraceKind::ReplayStarted,
event_ref: format!("session:{}", header.session_id),
})?;
let (count, timestamp_ms) = trace_selected(reader, &header, frame_bytes_max, &mut visit)?;
visit(TraceRecord {
timestamp_ms,
session_id: header.session_id,
kind: TraceKind::ReplayCompleted,
event_ref: format!("entries:{count}"),
})
}
fn trace_selected(
reader: &SessionReader,
header: &SessionHeader,
frame_bytes_max: usize,
mut visit: impl FnMut(TraceRecord) -> Result<()>,
) -> Result<(usize, i64)> {
visit(TraceRecord {
timestamp_ms: 0,
session_id: header.session_id,
kind: TraceKind::SessionCreated,
event_ref: format!("branch:{}", header.branch_id),
})?;
let Some(tip) = reader.selected_tip(frame_bytes_max)? else {
return Ok((0, 0));
};
let mut count = 0;
let mut timestamp_ms = 0;
// `(call_id, has_result)`: exactly one live tool lifecycle.
// ToolSession serializes effects and refuses subsequent effects after a
// completion-recording failure, so another lifecycle closes the prior one.
let mut pending = None;
let mut lifecycle = lifecycle::PendingLifecycle::default();
reader.replay_at(tip, frame_bytes_max, |entry| {
timestamp_ms = entry.timestamp_ms;
count += 1;
match entry.kind {
EntryKind::ToolCall { call_id } => {
flush_incomplete(
header.session_id,
entry.timestamp_ms,
&mut pending,
&mut visit,
)?;
visit(record_for(header.session_id, &entry, None))?;
pending = Some((call_id, false));
}
EntryKind::ToolResult { call_id, .. } => {
if pending
.is_some_and(|(pending_id, has_result)| pending_id != call_id || has_result)
{
flush_incomplete(
header.session_id,
entry.timestamp_ms,
&mut pending,
&mut visit,
)?;
}
visit(record_for(header.session_id, &entry, None))?;
pending = Some((call_id, true));
}
EntryKind::Meta { .. } => {
if let Some(record) = lifecycle.observe(header.session_id, &entry)? {
visit(record)?;
return Ok(());
}
if let Some(record) = causal_record(header.session_id, &entry)? {
visit(record)?;
return Ok(());
}
let mutation = mutation_detail(&entry)?;
if mutation.as_ref().map(|detail| detail.call_id) == pending.map(|(id, _)| id) {
pending = None;
}
visit(record_for(header.session_id, &entry, mutation.as_ref()))?;
}
EntryKind::Message { .. } => {
visit(record_for(header.session_id, &entry, None))?;
}
}
Ok(())
})?;
lifecycle.finish(header.session_id, timestamp_ms, &mut visit)?;
flush_incomplete(header.session_id, timestamp_ms, &mut pending, &mut visit)?;
Ok((count, timestamp_ms))
}
fn causal_record(session_id: SessionId, entry: &EntryFrame) -> Result