README Source History Refs Reviews Compare Notes Search Review guide fix(specs): session recording smart filter, speed-0 special case, step numbering dcfe3b80d4045696c86b1fc89216602edd3dbbd2
HallucyGenie Agent <agent@hallucygenie.local > · 21 May 2026
SSH signature · not checked
Browse files Compare with HEAD
- Fix TraceEntry::to_session_entries: remove invalid flat_map/flatten/return pattern
- Use explicit for loop with result.push() for all trace-to-session mapping
- Fix ContentBlock text extraction: filter to Text variants only, no to_string()
- Fix Snapshot arm: emit both ModelChange and ThinkingLevelChange
- Fix BashExecution comment: clarify output is in ToolEnd, not session log
- Fix ASCII diagram: reserved [u8; 32] matches struct definition
- Fix SM-010 run_replay: add --speed 0.0 → ReplaySpeed::Max special case
- Fix SM-010 run_replay step numbering (duplicate 5. → 6., 7. → 8.)
Changed files (2) Diff layout Auto Unified Split
docs/spec-sm-006-core.md Modified +704 / −42 text lines
37 37 tracing = { workspace = true }tracing = { workspace = true }38 38 thiserror = { workspace = true }thiserror = { workspace = true }39 39 uuid = { workspace = true, features = ["v7"] }uuid = { workspace = true, features = ["v7"] }
40 + zstd = { workspace = true } # trace file compression41 + sha2 = { workspace = true } # payload/file hashing for trace41 43 [dev-dependencies][dev-dependencies]42 44 tokio = { workspace = true, features = ["full"] }tokio = { workspace = true, features = ["full"] }50 52 pub mod session;pub mod session;51 53 pub mod session_format;pub mod session_format;52 54 pub mod tools;pub mod tools;54 56 pub mod events;pub mod events;55 57 pub mod secret_proxy;pub mod secret_proxy;56 58 pub mod system_prompt;pub mod system_prompt;57 59 pub mod compaction;pub mod compaction;58 60 pub mod cost;pub mod cost;60 - pub use agent::{ Agent, AgentContext, AgentEvent, AgentState, AgentLoopConfig}; 65 + Agent, AgentContext, AgentEvent, AgentState, AgentLoopConfig, 66 + ToolExecutionMode, QueueMode,67 + BeforeToolCallResult, AfterToolCallResult,68 + BeforeToolCallContext, AfterToolCallContext,69 + ShouldStopAfterTurnContext, AgentLoopTurnUpdate,61 71 pub use session::{Session, SessionEntry, SessionStore, SessionInfo};pub use session::{Session, SessionEntry, SessionStore, SessionInfo};62 72 pub use session_format::SessionCodec;pub use session_format::SessionCodec;63 73 pub use tools::ToolRegistry;pub use tools::ToolRegistry;64 - pub use hooks::{HookRegistration, HookContext, HookResult};
65 74 pub use events::EngineEvent;pub use events::EngineEvent;66 75 pub use secret_proxy::{SecretProxy, SecretId, InMemorySecretProxy};pub use secret_proxy::{SecretProxy, SecretId, InMemorySecretProxy};67 76 pub use system_prompt::SystemPromptBuilder;pub use system_prompt::SystemPromptBuilder;68 77 pub use compaction::{CompactionSettings, CompactionExecutor, TokenEstimator, HeuristicEstimator};pub use compaction::{CompactionSettings, CompactionExecutor, TokenEstimator, HeuristicEstimator};69 78 pub use cost::CostTracker;pub use cost::CostTracker;
79 + pub use trace::{TraceEntry, TraceCodec, TraceRecorder, FileTraceRecorder, TraceWriter, TraceFileHeader, AgentStateSnapshot};80 + pub use replay::{ReplayEngine, ReplaySpeed, ReplayMode, ReplayStep, ReplayDiff, ReplaySummary};72 83 ### 3. `smith-core/src/agent.rs` — The Agent Loop### 3. `smith-core/src/agent.rs` — The Agent Loop109 120 MessageEnd { message: Message, usage: ProviderUsage, stop_reason: StopReason }, MessageEnd { message: Message, usage: ProviderUsage, stop_reason: StopReason },111 122 // Tool execution // Tool execution112 - ToolExecutionStart { tool_call_id: String, tool_name: String, args : serde_json::Value },123 + ToolExecutionStart { tool_call_id: String, tool_name: String, args_json : String },113 124 ToolExecutionEnd { tool_call_id: String, tool_name: String, result: Vec<ContentBlock>, is_error: bool }, ToolExecutionEnd { tool_call_id: String, tool_name: String, result: Vec<ContentBlock>, is_error: bool },114 125 ToolExecutionUpdate { tool_call_id: String, tool_name: String, partial: String }, ToolExecutionUpdate { tool_call_id: String, tool_name: String, partial: String },117 - ThinkingDelta { delta: String },127 + // Streaming deltas (for TUI real-time updates)118 128 TextDelta { delta: String }, TextDelta { delta: String },
129 + ThinkingDelta { delta: String },121 132 Error { message: String }, Error { message: String },124 - /// Configuration for the agent loop135 + /// Convert an AgentEvent to a SessionEntry for the LLM conversation log.136 + /// Returns None for events that don't belong in the conversation context137 + /// (e.g., streaming deltas, errors).139 + pub fn to_session_entry(&self, timestamp: u64) -> Option<SessionEntry > {141 + AgentEvent::AgentStart => None,142 + AgentEvent::AgentEnd { messages } => None, // Intentionally not stored — session end is implicit from last entry143 + AgentEvent::TurnStart { .. } => None,144 + AgentEvent::TurnEnd { turn_index, message, tool_results } => {145 + // TurnEnd is a lifecycle marker; Assistant and ToolResult146 + // entries are produced by MessageEnd and ToolExecutionEnd.149 + AgentEvent::MessageStart { .. } => None,150 + AgentEvent::MessageUpdate { .. } => None,151 + AgentEvent::MessageEnd { message, usage, stop_reason } => {152 + Some(SessionEntry::Assistant {155 + content: message.content.clone(),156 + usage: usage.clone(),157 + provider: String::new(), // caller post-processes from AgentStateSnapshot158 + model: String::new(), // caller post-processes from AgentStateSnapshot159 + stop_reason: stop_reason.clone(),163 + AgentEvent::ToolExecutionStart { .. } => None,164 + AgentEvent::ToolExecutionEnd { tool_call_id, tool_name, result, is_error } => {165 + Some(SessionEntry::ToolResult {168 + tool_call_id: tool_call_id.clone(),169 + tool_name: tool_name.clone(),170 + content: result.clone(),171 + is_error: *is_error,175 + AgentEvent::ToolExecutionUpdate { .. } => None,176 + AgentEvent::TextDelta { .. } => None,177 + AgentEvent::ThinkingDelta { .. } => None,178 + AgentEvent::Error { .. } => None,183 + /// Result from before_tool_call hook.184 + #[derive(Clone, Debug, Default)] 185 + pub struct BeforeToolCallResult {187 + pub reason: Option<String >,190 + /// Result from after_tool_call hook.191 + #[derive(Clone, Debug, Default)] 192 + pub struct AfterToolCallResult {193 + pub content: Option<Vec <ContentBlock>>,194 + pub details: Option<serde_json::Value >,195 + pub is_error: Option<bool >,196 + pub terminate: Option<bool >,199 + /// Context passed to `before_tool_call`.200 + pub struct BeforeToolCallContext {201 + pub assistant_message: Message,202 + pub tool_call: ContentBlock, // ToolCall variant203 + pub args: serde_json::Value,204 + pub agent_context: AgentContext,207 + /// Context passed to `after_tool_call`.208 + pub struct AfterToolCallContext {209 + pub assistant_message: Message,210 + pub tool_call: ContentBlock,211 + pub args: serde_json::Value,212 + pub result: AgentToolResult,214 + pub agent_context: AgentContext,217 + /// Context passed to `should_stop_after_turn`.218 + pub struct ShouldStopAfterTurnContext {219 + pub message: Message,220 + pub tool_results: Vec<ContentBlock >,221 + pub agent_context: AgentContext,222 + pub new_messages: Vec<Message >,225 + /// Update returned by `prepare_next_turn` hook.226 + #[derive(Clone, Debug)] 227 + pub struct AgentLoopTurnUpdate {228 + pub model_id: Option<String >,229 + pub thinking_level: Option<ThinkingLevel >,230 + pub context: Option<AgentContext >,233 + /// Tool execution concurrency mode.234 + #[derive(Clone, Debug, Copy, PartialEq, Eq)] 235 + pub enum ToolExecutionMode {240 + /// Queue drain mode for steering/follow-up messages.241 + #[derive(Clone, Debug, Copy, PartialEq, Eq)] 247 + /// Configuration for a single agent loop invocation.125 248 pub struct AgentLoopConfig {pub struct AgentLoopConfig {126 249 pub model_id: String, pub model_id: String,127 250 pub provider_id: String, pub provider_id: String,128 251 pub thinking_level: ThinkingLevel, pub thinking_level: ThinkingLevel,129 252 pub max_tokens: Option<u32 >, pub max_tokens: Option<u32 >,
253 + pub system_prompt: String,254 + pub tool_execution: ToolExecutionMode,255 + pub queue_mode: QueueMode,257 + /// Called before each tool execution.258 + /// Return `block: true` to prevent execution; loop emits error tool result.259 + pub before_tool_call: Option<Box<dyn Fn(&BeforeToolCallContext, Option<&tokio::sync::watch::Receiver<bool>>) -> BeforeToolCallResult + Send + Sync>>,260 + /// Called after tool finishes, before events emitted.261 + /// Return overrides for content/details/is_error/terminate.262 + pub after_tool_call: Option<Box<dyn Fn(&AfterToolCallContext, Option<&tokio::sync::watch::Receiver<bool>>) -> AfterToolCallResult + Send + Sync>>,263 + /// Called after each turn completes. Return true to emit `agent_end` and exit.264 + pub should_stop_after_turn: Option<Box<dyn Fn(&ShouldStopAfterTurnContext) -> bool + Send + Sync>>,265 + /// Called after `turn_end`, before deciding next provider request.266 + /// Return replacement context/model/thinking for next turn.267 + pub prepare_next_turn: Option<Box<dyn Fn(&ShouldStopAfterTurnContext) -> Option<AgentLoopTurnUpdate> + Send + Sync>>,268 + /// Transform messages before each LLM call.269 + pub transform_context: Option<Box<dyn Fn(Vec<Message>, Option<&tokio::sync::watch::Receiver<bool>>) -> Vec<Message> + Send + Sync>>,270 + /// Convert messages to LLM-compatible format (default: filter to user/assistant/tool_result).130 271 pub convert_to_llm: Box<dyn Fn(Vec<Message>) -> Vec<Message> + Send + Sync>, pub convert_to_llm: Box<dyn Fn(Vec<Message>) -> Vec<Message > + Send + Sync>,131 - pub transform_context: Option<Box <dyn Fn(Vec<Message>) -> Vec<Message > + Send + Sync>>,132 - pub get_api_key: Option<Box <dyn Fn(&str) -> Option<String > + Send + Sync>>,133 - pub after_tool_call: Option<Box <dyn Fn(&str, &AgentToolResult) -> Option<AgentToolResult > + Send + Sync>>,
136 274 /// Stateful agent wrapper (like pi's Agent class)/// Stateful agent wrapper (like pi's Agent class)151 289 pub thinking_level: ThinkingLevel, pub thinking_level: ThinkingLevel,152 290 pub is_streaming: bool, pub is_streaming: bool,153 291 pub abort_signal: tokio::sync::watch::Sender<bool>, pub abort_signal: tokio::sync::watch::Sender<bool>,
292 + /// Tool call ids currently executing.293 + pub pending_tool_calls: std::collections::HashSet<String>,294 + /// Error message from most recent failed/aborted turn, if any.295 + pub error_message: Option<String>,296 + /// Partial assistant message for current streamed response, if any.297 + pub streaming_message: Option<Message>,298 + /// Pending user messages queued for steering.299 + pub steering_queue: Vec<Message>,300 + /// Pending user messages queued for follow-up.301 + pub follow_up_queue: Vec<Message>,302 + /// Trace recorder for deterministic replay.303 + pub trace: Option<Arc<dyn TraceRecorder>>,156 306 impl Agent {impl Agent {168 318 The core loop:The core loop:170 - 1 . Convert messages to LLM format (convert_to_llm)171 - 2 . Optionally transform context (transform_context)172 - 3 . Build ProviderRequest173 - 4 . Call stream_fn(request) → get event stream174 - 5 . Process ProviderEvents:320 + 1. Record trace: EnvSnapshot (cwd, env) if first turn321 + 2 . Convert messages to LLM format (convert_to_llm)322 + 3 . Optionally transform context (transform_context)323 + - Record trace: PluginEvent::Context if transform changes messages324 + 4 . Build ProviderRequest325 + - Record trace: ProviderRequest { provider_id, model_id, payload_hash }326 + 5 . Call stream_fn(request) → get event stream327 + 6 . Process ProviderEvents:175 328 - TextDelta → emit AgentEvent::TextDelta, accumulate - TextDelta → emit AgentEvent::TextDelta, accumulate176 329 - ToolCall → queue tool call - ToolCall → queue tool call177 330 - ThinkingDelta → emit AgentEvent::ThinkingDelta - ThinkingDelta → emit AgentEvent::ThinkingDelta178 - - Done → finalize assistant message, execute queued tools179 - 6. For each tool call:180 - a. Execute tool (AgentTool::execute)181 - b. after_tool_call hook (can modify result)182 - c. Add tool result to messages183 - 7. If stop_reason == ToolUse, goto 1 (next turn)184 - 8. If stop_reason == EndTurn, emit AgentEnd331 + - Done → finalize assistant message332 + 7. Record trace: ProviderResponse { status, payload_hash }334 + - Record trace: AgentEvent::TurnStart335 + 9. For each tool call (respecting tool_execution mode):336 + a. Record trace: ToolStart { tool_call_id, tool_name, args }337 + b. Validate arguments against tool schema338 + c. before_tool_call hook → if block, emit error tool result339 + - Record trace: PluginEventResult::ToolCallBlock340 + d. Execute tool (AgentTool::execute) with abort signal341 + e. after_tool_call hook → apply overrides (content/details/is_error/terminate)342 + - Record trace: PluginEventResult::ToolResultOverride343 + f. Record trace: ToolEnd { result_hash, is_error }344 + g. Emit ToolExecutionStart/Update/End345 + - Record trace: AgentEvent for each346 + h. Add tool result to messages347 + i. **Early termination check:** If all finalized tools in this batch348 + had `terminate=true` (from after_tool_call or original result),349 + emit `AgentEnd` and exit immediately.351 + - Record trace: AgentEvent::TurnEnd352 + 11. Record trace: Snapshot { agent_state } (every 10s or on compaction)353 + 12. should_stop_after_turn hook → if true, emit AgentEnd and exit354 + - Record trace: PluginEventResult::ShouldStopAfterTurn355 + 13. prepare_next_turn hook → apply context/model/thinking overrides356 + - Record trace: PluginEventResult::PrepareNextTurn357 + 14. If stop_reason == ToolUse, goto 2 (next turn)358 + 15. If stop_reason == EndTurn:359 + a. Drain steering queue (respecting queue_mode)360 + - Record trace: SteeringDrain { messages }361 + b. Drain follow-up queue (respecting queue_mode)362 + - Record trace: FollowUpDrain { messages }363 + c. If messages drained, emit AgentEnd364 + - Record trace: AgentEvent::AgentEnd367 + **Queue drain semantics:**368 + - `QueueMode::All` — drain entire queue into messages, then proceed.369 + - `QueueMode::OneAtATime` — drain exactly one message, process it in next turn.370 + - Steering messages are prepended (higher priority) before follow-up messages.187 373 ### 4. `smith-core/src/events.rs` — Engine Event Bus ### 4. `smith-core/src/events.rs` — Engine Event Bus 339 525 ### 8. `smith-core/src/hooks.rs` ### 8. `smith-core/src/hooks.rs` 341 - Hook system for intercepting events. Maps to plugin SDK events.344 - pub struct HookRegistration {346 - pub handler: Box <dyn Fn (& HookContext) -> HookResult + Send + Sync >,349 - pub struct HookContext {351 - pub data: serde_json::Value,354 - pub enum HookResult {356 - Modify { data: serde_json::Value },527 + > **Note:** The legacy `hooks.rs` HookRegistration/HookResult system was removed.528 + > All behavior mutation now happens through `AgentLoopConfig` typed hooks529 + > (`before_tool_call`, `after_tool_call`, `should_stop_after_turn`, `prepare_next_turn`).530 + > Plugin SDK event handlers in smith-harness return `PluginEventResult` values531 + > which the harness translates into these hook results.532 + > See SM-009 §Event Bridge for the plugin-side event result system.360 534 ### 9. `smith-core/src/system_prompt.rs` ### 9. `smith-core/src/system_prompt.rs`
668 + ### 13. `smith-core/src/trace.rs` — Session Recording and Replay670 + Deterministic replay requires capturing every event that affects state.671 + The session log (`SessionEntry`) remains conversation-only for the LLM.672 + The trace log (`TraceEntry`) captures everything: UI events, plugin events,673 + provider requests/responses, system signals, and periodic snapshots.675 + #### 13.1 Trace File Format677 + Trace files are stored alongside session files in the XDG data directory:682 + {session-id}.session ← SessionEntry CBOR-seq (LLM context)683 + {session-id}.trace ← TraceEntry CBOR-seq (full replay log)686 + Trace file wire format:689 + ┌───────────────────── Header (fixed 64 bytes) ─────────────────────┐690 + │ magic: [u8; 4] = b"SMTH" │692 + │ flags: u16 = 0x01 (compressed) | 0x00 (raw) │693 + │ session_id: [u8; 16] (UUID v7 bytes) │694 + │ start_timestamp_ns: u64 (monotonic clock base) │695 + │ (entry count is not stored in header — iterate body to count) │696 + │ reserved: [u8; 32] │697 + ├───────────────────── Body ─────────────────────────────────────────┤698 + │ [u32 BE len][CBOR TraceEntry bytes ][u32 BE len][CBOR TraceEntry ]...│699 + │ (each entry optionally zstd-compressed when flag 0x01 set) │700 + └────────────────────────────────────────────────────────────────────┘704 + /// Trace file header. Fixed 64 bytes at file start.705 + #[derive(Clone, Debug, Serialize, Deserialize)]706 + pub struct TraceFileHeader {707 + pub magic: [u8; 4], // b"SMTH"708 + pub version: u16, // 1709 + pub flags: u16, // 0x01 = zstd compressed entries710 + pub session_id: [u8; 16], // UUID v7711 + pub start_timestamp_ns: u64,712 + pub reserved: [u8; 32],715 + impl TraceFileHeader {716 + pub const MAGIC: [u8; 4] = *b"SMTH";717 + pub const FLAG_COMPRESSED: u16 = 0x01;718 + pub const SIZE: usize = 64;722 + #### 13.2 Trace Types 726 + use tokio::sync::mpsc;729 + pub trait TraceRecorder : Send + Sync {731 + fn record (& self, entry: TraceEntry);733 + fn flush (& self) -> Result <()>;737 + pub struct FileTraceRecorder {739 + header: TraceFileHeader,740 + tx: mpsc::UnboundedSender<TraceEntry>,743 + impl FileTraceRecorder {748 + session_id: [u8 ; 16],750 + ) -> Result <(Self , TraceWriter)>;753 + pub fn open (path: PathBuf) -> Result <(Self , TraceWriter)>;757 + pub struct TraceWriter ;760 + #[derive(Clone, Debug, Serialize, Deserialize, minicbor::Encode, minicbor::Decode)]761 + pub enum TraceEntry {763 + AgentEvent { timestamp_ns: u64 , event: AgentEvent },764 + TurnStart { timestamp_ns: u64 , turn_index: usize },765 + TurnEnd { timestamp_ns: u64 , turn_index: usize , messages: Vec <Message> },766 + SteeringDrain { timestamp_ns: u64 , messages: Vec <Message> },767 + FollowUpDrain { timestamp_ns: u64 , messages: Vec <Message> },770 + TuiEvent { timestamp_ns: u64 , event: TuiEvent },771 + FocusChange { timestamp_ns: u64 , widget_id: String , focused: bool },772 + Scroll { timestamp_ns: u64 , widget_id: String , offset: usize },775 + PluginEvent { timestamp_ns: u64 , event: PluginEvent },776 + PluginEventResult { timestamp_ns: u64 , event_name: String , result: PluginEventResult },777 + PluginLoaded { timestamp_ns: u64 , path: String , success: bool },778 + PluginError { timestamp_ns: u64 , path: String , error: String },781 + ProviderRequest { timestamp_ns: u64 , request_id: u64 , provider_id: String , model_id: String , payload_hash: String },782 + ProviderResponse { timestamp_ns: u64 , request_id: u64 , provider_id: String , model_id: String , status: u16 , payload_hash: String },785 + ToolStart { timestamp_ns: u64 , tool_call_id: String , tool_name: String , args_json: String },786 + ToolEnd { timestamp_ns: u64 , tool_call_id: String , tool_name: String , result_hash: String , is_error: bool },789 + SystemSignal { timestamp_ns: u64 , signal: String },790 + EnvSnapshot { timestamp_ns: u64 , cwd: String , env_vars: Vec <(String, String)> }, 791 + FileHashSnapshot { timestamp_ns: u64 , files: Vec <(String, String)> }, 794 + Snapshot { timestamp_ns: u64 , agent_state: AgentStateSnapshot }, 798 + #[derive(Clone, Debug, Serialize, Deserialize, minicbor::Encode, minicbor::Decode)]799 + pub struct AgentStateSnapshot {800 + pub message_count: usize ,801 + pub model_id: String,802 + pub provider_id: String,803 + pub thinking_level: ThinkingLevel,804 + pub pending_tool_calls: Vec <String >,808 + #### 13.3 Trace Codec 812 + pub struct TraceCodec ;816 + pub fn encode (entries: & [TraceEntry]) -> Result <Vec <u8 >>;819 + pub fn decode (data: & [u8 ]) -> (Vec <TraceEntry>, Vec <DecodeError>);823 + pub fn append_entry (824 + writer: &mut impl Write,830 + pub fn read_file (path: & Path) -> Result <(TraceFileHeader, Vec <TraceEntry>, Vec <DecodeError>)>;834 + **Compression trade-off:** Individual entry zstd compression (level 3) gives ~60-70% size835 + reduction on typical traces. Each entry compressed independently preserves random access —836 + a reader can skip an entry by reading the length prefix and seeking past. Block-level837 + compression (compressing N entries together) would give better ratios but loses random access.839 + #### 13.4 Snapshot Strategy 841 + | Snapshot Type | When Captured | Purpose |842 + |--------------|---------------|----------|843 + | `EnvSnapshot` | Session start, every 5 minutes | Record cwd + env vars for replay env reconstruction |844 + | `FileHashSnapshot` | Session start, before/after each tool execution | Detect file changes for comparison mode |845 + | `Snapshot` (agent state) | Every 10s, on compaction, on model change | Agent state checkpoint for fast-forward during replay |847 + **FileHashSnapshot scope:** Only files in CWD that were touched by tool executions848 + (`read`, `write`, `edit`, `bash` tools). Not a full directory scan — tracked via849 + a `touched_files: HashSet<PathBuf>` in the trace recorder.851 + **EnvSnapshot scope:** `CWD`, `PATH`, `HOME`, `TERM`, `SHELL`, plus any vars852 + prefixed with `SMITH_`. Provider API keys and other secrets are captured as853 + `NAME=sha256:<hash>` — the value is hashed, not stored plaintext. This prevents854 + secret leakage in trace files while still allowing replay env reconstruction.856 + #### 13.5 Determinism Guarantees 858 + **Guaranteed deterministic (same trace → same replay output):**859 + - Agent event ordering (monotonic nanosecond timestamps)860 + - Provider request/response pairing (by payload hash)861 + - Plugin event dispatch order and results862 + - Tool execution order (sequential mode) or per-turn grouping (parallel mode)863 + - SessionEntry derivation (smart filter is pure function over TraceEntry)865 + **Best-effort (may differ between live and replay):**866 + - Exact LLM responses (provider may return different text for same payload)867 + - File system state at tool execution time (files may have changed)868 + - Timing (wall-clock durations may differ, but ordering preserved)869 + - Plugin handler execution speed (Lua GC pauses may vary)871 + **Not captured (out of scope for v1):**872 + - Network latency/response times873 + - Exact memory layout or heap state874 + - External process state (tools that spawn subprocesses)875 + - Random number generation (smith doesn't use RNG in agent loop)877 + **Comparison mode** bridges the determinism gap for regression testing:878 + By re-executing tool calls in a controlled environment (same files, same env),879 + the replay engine can diff old vs new tool outputs, isolating changes caused880 + by code modifications vs. external state differences.882 + #### 13.6 Smart Filter — TraceEntry → SessionEntry 884 + The smart filter produces the LLM-visible `SessionEntry` list from `TraceEntry`.885 + Only conversation-relevant entries pass through:887 + | TraceEntry | SessionEntry | Notes |888 + |------------|-------------|-------|889 + | `AgentEvent { AgentEvent::TextDelta, .. }` | filtered (aggregated into Assistant) | Text deltas accumulated into full message |890 + | `AgentEvent { AgentEvent::ToolExecutionEnd, .. }` | `ToolResult` | Tool results become session entries |891 + | `AgentEvent { AgentEvent::MessageEnd, .. }` | `Assistant` | Finalized assistant messages |892 + | `TurnEnd` (steering message detected) | `User` | Steering/follow-up messages become user entries |893 + | `ToolStart` (bash) | `BashExecution` | Bash tool calls record command + output |894 + | `Snapshot` (model change) | `ModelChange` | Model changes recorded |895 + | `Snapshot` (thinking change) | `ThinkingLevelChange` | Thinking level changes recorded |896 + | All other TraceEntry variants | _filtered out_ | TUI, plugin, provider events excluded from LLM context |901 + pub fn to_session_entries (entries: & [TraceEntry]) -> Vec <SessionEntry> {902 + let mut result = Vec ::new();905 + TraceEntry::AgentEvent { timestamp_ns, event } => {906 + if let Some (se) = event.to_session_entry (* timestamp_ns) {910 + TraceEntry::TurnEnd { timestamp_ns, messages } => {912 + let text: String = messages.iter ()913 + .flat_map (|m| m.content.iter ().filter_map (|c| match c {914 + ContentBlock::Text(t) => Some (t.as_str ()),917 + .collect::<Vec <_ >>()919 + if ! text.is_empty () {920 + result.push (SessionEntry::User {923 + content: vec! [ContentBlock::Text { text }],924 + timestamp: * timestamp_ns,928 + TraceEntry::ToolStart { timestamp_ns, tool_name, args_json }929 + if tool_name == "bash" => 932 + let command = serde_json::from_str::<serde_json::Value>(args_json)934 + .and_then (|v| v.get ("command" ).and_then (|c| c.as_str ().map (|s| s.to_string ())))935 + .unwrap_or_else (|| args_json.clone ());936 + result.push (SessionEntry::BashExecution {940 + output: String ::new(), 941 + timestamp: * timestamp_ns,944 + TraceEntry::Snapshot { timestamp_ns, agent_state } => {946 + result.push (SessionEntry::ModelChange {949 + provider: agent_state.provider_id.clone (),950 + model_id: agent_state.model_id.clone (),951 + timestamp: * timestamp_ns,953 + result.push (SessionEntry::ThinkingLevelChange {956 + level: agent_state.thinking_level,957 + timestamp: * timestamp_ns,968 + #### 13.7 Replay Engine 970 + The replay engine reconstructs a session from a trace log, feeding events into971 + a reconstructed agent at configurable speed. Used for debugging, testing, and972 + regression comparison.976 + pub struct ReplayEngine {977 + trace: Vec <TraceEntry>,978 + header: TraceFileHeader,986 + pub enum ReplaySpeed {996 + pub enum ReplayMode {1004 + sandbox_dir: PathBuf,1006 + tools: Vec <String >,1008 + continue_on_diff: bool ,1013 + pub struct ReplayStep {1014 + pub entry: TraceEntry,1015 + pub timestamp_ns: u64 ,1017 + pub diff: Option <ReplayDiff>,1021 + pub struct ReplayDiff {1022 + pub tool_call_id: String,1023 + pub tool_name: String,1025 + pub original_hash: String,1027 + pub new_hash: String,1029 + pub text_diff: Option <String >,1033 + pub struct ReplaySummary {1034 + pub total_entries: usize ,1035 + pub duration_ms: u64 ,1036 + pub agent_events: usize ,1037 + pub tool_executions: usize ,1038 + pub diffs: Vec <ReplayDiff>,1040 + pub has_regressions: bool ,1047 + speed: ReplaySpeed,1057 + pub async fn run <F>(&mut self, on_step: F) -> Result <ReplaySummary>1059 + F: Fn(ReplayStep) -> bool ; 1064 + pub fn seek_to_turn (&mut self, turn_index: usize ) -> Result <usize >;1067 + pub fn extract_session (& self) -> Vec <SessionEntry>;1072 + pub fn extract_provider_trace (& self) -> Vec <(TraceEntry, Option <TraceEntry>)>;1076 + **Replay execution flow:**1077 + 1. Read trace file → decode header + entries.1078 + 2. Optional: `seek_to_turn` to skip ahead.1079 + 3. Iterate entries in order:1080 + - **Max speed:** process immediately, no delays.1081 + - **RealTime:** compute delta from previous entry's `timestamp_ns`, `tokio::time::sleep`.1082 + - **Factor:** compute delta, divide by factor, sleep.1084 + - **Normal mode:** call `on_step(ReplayStep { entry, timestamp, diff: None })`.1085 + - **Compare mode:** on `ToolEnd` entries, re-execute the tool in sandbox,1086 + compare result hash. Call `on_step` with `diff` if hashes differ.1087 + 5. On completion, return `ReplaySummary`.1089 + **Compare mode requirements:**1090 + - Sandbox directory must contain files matching the original session's CWD.1091 + - Environment should match (provider keys not needed — tool outputs are re-executed locally).1092 + - Read-only tools (`read`, `find`, `grep`, `ls`) can always be compared.1093 + - Write tools (`write`, `edit`, `bash`) modify the sandbox — subsequent tools see modified state.1094 + - Diffs are reported but do not stop replay (unless `continue_on_diff: false`).1096 + **Replay output formats** (for CLI consumption):1097 + - `--format text` — human-readable step-by-step log with timestamps.1098 + - `--format json` — JSONL stream of `ReplayStep` objects.1099 + - `--format summary` — only `ReplaySummary` at the end.1101 + #### 13.8 Design Decisions 1103 + - **Single `TraceRecorder` trait** — all subsystems (agent, TUI, plugins, provider) call into one recorder.1104 + - **Background writer task** — recording never blocks the agent loop or TUI render thread.1105 + - **Provider payloads hashed, not stored** — SHA-256 for privacy and size. Full payloads can be captured with a config flag for deep debugging, but default is hash-only.1106 + - **Monotonic nanosecond timestamps** — `std::time::Instant::elapsed().as_nanos()` for ordering, not wall clock.1107 + - **Optional zstd compression** — per-entry, preserving random access. Trades ~10% worse compression vs block-level for seekability.1108 + - **FileHashSnapshot is incremental** — only files touched by tools, not full directory scans.1109 + - **EnvSnapshot is selective** — only relevant env vars, not full environment.1110 + - **Compare mode is sandboxed** — never re-executes against real filesystem unless explicitly configured.
1114 + - **Trace recording**1115 + - Mock TraceRecorder records all agent events1116 + - Verify TraceCodec roundtrip (encode → decode)1117 + - FileTraceRecorder appends without blocking1118 + - Smart filter produces correct SessionEntry subset1119 + - TraceFileHeader write/read roundtrip1120 + - TraceCodec with zstd compression roundtrip1121 + - EnvSnapshot captures selective env vars1122 + - FileHashSnapshot captures only touched files1123 + - Snapshot emission on 10s interval and model change1125 + - ReplayEngine::from_file loads trace correctly1126 + - Max speed replay processes all entries without delays1127 + - RealTime replay respects inter-event timing1128 + - Factor replay scales timing correctly1129 + - seek_to_turn skips to correct position1130 + - extract_session produces same entries as live session1131 + - extract_provider_trace pairs request/response correctly1133 + - Read tool re-execution matches original output (same files)1134 + - Write tool re-execution produces diff when content changed1135 + - Compare mode continues on diff with continue_on_diff: true1136 + - Compare mode stops on first diff with continue_on_diff: false496 1137 - **Agent loop with mock stream** — most important test- **Agent loop with mock stream** — most important test497 1138 - Mock StreamFn returns TextDelta + Done - Mock StreamFn returns TextDelta + Done498 1139 - Agent emits AgentStart, MessageStart, TextDelta, MessageEnd, AgentEnd - Agent emits AgentStart, MessageStart, TextDelta, MessageEnd, AgentEnd501 1142 - Mock StreamFn returns ToolCall + Done - Mock StreamFn returns ToolCall + Done502 1143 - Agent executes tool, adds result, loops again - Agent executes tool, adds result, loops again503 1144 - Second loop returns EndTurn - Second loop returns EndTurn
1145 + - **before_tool_call blocking**1146 + - Mock before_tool_call returns block=true1147 + - Tool not executed; error result added to messages1148 + - **after_tool_call mutation**1149 + - Mock after_tool_call overrides content/details/is_error1150 + - Modified result added to messages1151 + - **should_stop_after_turn**1152 + - Hook returns true after N turns1153 + - Agent emits AgentEnd and exits cleanly1154 + - **prepare_next_turn**1155 + - Hook returns new model_id/thinking_level1156 + - Next turn uses updated config1157 + - **ToolExecutionMode::Parallel**1158 + - Multiple tool calls execute concurrently1159 + - Results collected and added in source order1160 + - **QueueMode::OneAtATime**1161 + - Steering queue drains one message per turn1162 + - Follow-up queue drains one message per turn504 1163 - **Session creation and entry addition**- **Session creation and entry addition**505 1164 - **Session fork creates correct tree**- **Session fork creates correct tree**506 1165 - **SecretProxy hides and restores secrets**- **SecretProxy hides and restores secrets**518 1177 - [ ] Create `smith-core/src/session.rs` (SessionEntry canonical definition)- [ ] Create `smith-core/src/session.rs` (SessionEntry canonical definition)519 1178 - [ ] Create `smith-core/src/session_format.rs` (CBOR codec)- [ ] Create `smith-core/src/session_format.rs` (CBOR codec)520 1179 - [ ] Create `smith-core/src/tools.rs` (ToolRegistry)- [ ] Create `smith-core/src/tools.rs` (ToolRegistry)521 - - [ ] Create `smith-core/src/hooks.rs`
522 1180 - [ ] Create `smith-core/src/events.rs` (EngineEvent wrapping AgentEvent)- [ ] Create `smith-core/src/events.rs` (EngineEvent wrapping AgentEvent)523 1181 - [ ] Create `smith-core/src/secret_proxy.rs`- [ ] Create `smith-core/src/secret_proxy.rs`524 1182 - [ ] Create `smith-core/src/system_prompt.rs` (expanded)- [ ] Create `smith-core/src/system_prompt.rs` (expanded)525 1183 - [ ] Create `smith-core/src/compaction.rs` (TokenEstimator)- [ ] Create `smith-core/src/compaction.rs` (TokenEstimator)526 1184 - [ ] Create `smith-core/src/cost.rs` (CostTracker)- [ ] Create `smith-core/src/cost.rs` (CostTracker)
1185 + - [ ] Create `smith-core/src/trace.rs` (TraceEntry, TraceCodec, TraceRecorder, TraceFileHeader)1186 + - [ ] Create `smith-core/src/replay.rs` (ReplayEngine, ReplaySpeed, ReplayMode, ReplayStep, ReplayDiff, ReplaySummary)527 1187 - [ ] Write agent loop tests (mock stream function)- [ ] Write agent loop tests (mock stream function)528 1188 - [ ] Write session/tool/hook/cost tests- [ ] Write session/tool/hook/cost tests
1189 + - [ ] Write trace recording tests (codec, header, compression, snapshots)1190 + - [ ] Write replay engine tests (speed modes, compare mode, fast-forward)529 1191 - [ ] Verify: `cargo check -p smith-core`- [ ] Verify: `cargo check -p smith-core`530 1192 - [ ] Test: `cargo test -p smith-core`- [ ] Test: `cargo test -p smith-core`531 - - [ ] Commit: `jj describe -m "feat(SM-006): smith-core — agent loop, session, events, cost, compaction"`1193 + - [ ] Commit: `jj describe -m "feat(SM-006): smith-core — agent loop, session, events, cost, compaction, trace, replay "`No final newline docs/spec-sm-010-cli.md Modified +78 / −1 text lines
24 24 12. **`smith eval --session <id>`** — attach to session for eval12. **`smith eval --session <id>`** — attach to session for eval25 25 13. **`smith rpc`** — JSON-RPC via stdio13. **`smith rpc`** — JSON-RPC via stdio26 26 14. **`smith help [topic]`** — documentation browser14. **`smith help [topic]`** — documentation browser27 - 15 . **Global flags:** `--model`, `--provider`, `--session`, `--config`, `--no-config`27 + 15. **`smith replay <session-id>`** — replay session from trace log28 + 16. **`smith replay <session-id> --speed 2`** — replay at 2x speed29 + 17. **`smith replay <session-id> --compare`** — compare old vs new tool outputs30 + 18 . **Global flags:** `--model`, `--provider`, `--session`, `--config`, `--no-config`29 32 ## Deliverables ## Deliverables 144 147 #[arg(long)] #[arg(long)]145 148 guide: Option<String>, guide: Option<String>,
151 + /// Replay a session from trace log153 + /// Session id or name156 + /// Replay speed multiplier (1.0 = real-time, 0 = max speed)157 + #[arg(long, default_value = "1.0")]160 + /// Compare mode: re-execute tools and diff outputs164 + /// Sandbox directory for compare mode (must match original CWD structure)166 + sandbox: Option<PathBuf>,168 + /// Stop after N turns (0 = full replay)170 + turns: Option<usize>,172 + /// Start from turn N (0 = from beginning)173 + #[arg(long, default_value = "0")]176 + /// Output format: text, json, summary177 + #[arg(long, default_value = "text")]180 + /// Continue on diff failures in compare mode181 + #[arg(long, default_value = "true")]182 + continue_on_diff: bool,195 232 Some(Commands::Help { topic, search, list, examples, example, guide }) => { Some(Commands::Help { topic, search, list, examples, example, guide }) => {196 233 run_help(topic, search, list, examples, example, guide) run_help(topic, search, list, examples, example, guide)
235 + Some(Commands::Replay { session, speed, compare, sandbox, turns, from_turn, format, continue_on_diff }) => {236 + run_replay(&session, speed, compare, sandbox, turns, from_turn, &format, continue_on_diff, &cli).await215 255 `run_session` resolves the session id (latest if not provided), reads entries via `SessionStore`, and formats `Dump` as JSONL.`run_session` resolves the session id (latest if not provided), reads entries via `SessionStore`, and formats `Dump` as JSONL.
257 + `run_replay` — replays a session from its trace log using `ReplayEngine` (SM-006 §13.7):258 + 1. Resolve session id via `SessionStore`259 + 2. Load trace file from `{data_dir}/sessions/{id}.trace`260 + 3. Convert speed flag: `speed == 0.0` → `ReplaySpeed::Max`, `speed == 1.0` → `ReplaySpeed::RealTime`, else `ReplaySpeed::Factor(speed)`261 + 4. Create `ReplayEngine::from_file` with resolved speed and mode263 + - Each entry → `ReplayStep` → formatted output to stdout264 + - Speed control: max (no delays), real-time, or factor (N× speed)265 + - Progress indicator: `[42/187] Turn 3 — ToolResult(bash)`266 + 6. In compare mode (`--compare`):267 + - Intercept `ToolEnd` entries → re-execute tool in sandbox directory268 + - Compare result hash vs original → emit `ReplayDiff` if different269 + - Continue or stop on diff based on `--continue-on-diff` flag271 + - Default: human-readable step-by-step log272 + - `--format json`: JSONL stream of `ReplayStep` objects273 + - `--format summary`: only final `ReplaySummary`274 + 8. On completion, print `ReplaySummary` (total entries, diffs, regressions)276 + Compare mode example:279 + smith replay abc123 --compare --sandbox /tmp/smith-test-env --format json282 + smith replay abc123 --speed 5.0 --format summary285 + smith replay abc123 --speed 0 --from-turn 10 --turns 10219 290 - CLI parsing: all subcommands parse correctly- CLI parsing: all subcommands parse correctly230 301 - `smith session dump --last 5` limits to last 5 entries- `smith session dump --last 5` limits to last 5 entries231 302 - `smith session dump --output out.jsonl` writes to file- `smith session dump --output out.jsonl` writes to file232 303 - `smith --no-config` skips config loading- `smith --no-config` skips config loading
304 + - `smith replay abc123` replays session from trace305 + - `smith replay abc123 --speed 0` replays at max speed (0 is special-cased to Max)306 + - `smith replay abc123 --speed 2.0` replays at 2× speed307 + - `smith replay abc123 --compare --sandbox /tmp/test` replays with tool comparison308 + - `smith replay abc123 --format json` outputs JSONL replay steps309 + - `smith replay abc123 --from-turn 5 --turns 3` replays turns 5-7 only