repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

fix(specs): session recording smart filter, speed-0 special case, step numbering

dcfe3b80d4045696c86b1fc89216602edd3dbbd2

HallucyGenie Agent <agent@hallucygenie.local> ·

SSH signature · not checked

Browse filesCompare 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)

+782 / −43 text lines

Diff layout

docs/spec-sm-006-core.md

Modified

+704 / −42 text lines

@@ -37,6 +37,8 @@ 1. `smith-core/Cargo.toml`
3737tracing = { workspace = true }
3838thiserror = { workspace = true }
3939uuid = { workspace = true, features = ["v7"] }
40zstd = { workspace = true } # trace file compression
41sha2 = { workspace = true } # payload/file hashing for trace
4143[dev-dependencies]
4244tokio = { workspace = true, features = ["full"] }
@@ -50,23 +52,32 @@ 2. `smith-core/src/lib.rs`
5052pub mod session;
5153pub mod session_format;
5254pub mod tools;
53pub mod hooks;
5456pub mod events;
5557pub mod secret_proxy;
5658pub mod system_prompt;
5759pub mod compaction;
5860pub mod cost;
61pub mod trace;
62pub mod replay;
60pub use agent::{Agent, AgentContext, AgentEvent, AgentState, AgentLoopConfig};
64pub use agent::{
65 Agent, AgentContext, AgentEvent, AgentState, AgentLoopConfig,
66 ToolExecutionMode, QueueMode,
67 BeforeToolCallResult, AfterToolCallResult,
68 BeforeToolCallContext, AfterToolCallContext,
69 ShouldStopAfterTurnContext, AgentLoopTurnUpdate,
70};
6171pub use session::{Session, SessionEntry, SessionStore, SessionInfo};
6272pub use session_format::SessionCodec;
6373pub use tools::ToolRegistry;
64pub use hooks::{HookRegistration, HookContext, HookResult};
6574pub use events::EngineEvent;
6675pub use secret_proxy::{SecretProxy, SecretId, InMemorySecretProxy};
6776pub use system_prompt::SystemPromptBuilder;
6877pub use compaction::{CompactionSettings, CompactionExecutor, TokenEstimator, HeuristicEstimator};
6978pub use cost::CostTracker;
79pub use trace::{TraceEntry, TraceCodec, TraceRecorder, FileTraceRecorder, TraceWriter, TraceFileHeader, AgentStateSnapshot};
80pub use replay::{ReplayEngine, ReplaySpeed, ReplayMode, ReplayStep, ReplayDiff, ReplaySummary};
7081```
7283### 3. `smith-core/src/agent.rs` — The Agent Loop
@@ -109,28 +120,155 @@ 3. `smith-core/src/agent.rs` — The Agent Loop
109120 MessageEnd { message: Message, usage: ProviderUsage, stop_reason: StopReason },
111122 // Tool execution
112 ToolExecutionStart { tool_call_id: String, tool_name: String, args: serde_json::Value },
123 ToolExecutionStart { tool_call_id: String, tool_name: String, args_json: String },
113124 ToolExecutionEnd { tool_call_id: String, tool_name: String, result: Vec<ContentBlock>, is_error: bool },
114125 ToolExecutionUpdate { tool_call_id: String, tool_name: String, partial: String },
116 // Streaming deltas
117 ThinkingDelta { delta: String },
127 // Streaming deltas (for TUI real-time updates)
118128 TextDelta { delta: String },
129 ThinkingDelta { delta: String },
120131 // Error
121132 Error { message: String },
124/// Configuration for the agent loop
135/// Convert an AgentEvent to a SessionEntry for the LLM conversation log.
136/// Returns None for events that don't belong in the conversation context
137/// (e.g., streaming deltas, errors).
138impl AgentEvent {
139 pub fn to_session_entry(&self, timestamp: u64) -> Option<SessionEntry> {
140 match self {
141 AgentEvent::AgentStart => None,
142 AgentEvent::AgentEnd { messages } => None, // Intentionally not stored — session end is implicit from last entry
143 AgentEvent::TurnStart { .. } => None,
144 AgentEvent::TurnEnd { turn_index, message, tool_results } => {
145 // TurnEnd is a lifecycle marker; Assistant and ToolResult
146 // entries are produced by MessageEnd and ToolExecutionEnd.
147 None
148 }
149 AgentEvent::MessageStart { .. } => None,
150 AgentEvent::MessageUpdate { .. } => None,
151 AgentEvent::MessageEnd { message, usage, stop_reason } => {
152 Some(SessionEntry::Assistant {
153 id: EntryId::new(),
154 parent_id: None,
155 content: message.content.clone(),
156 usage: usage.clone(),
157 provider: String::new(), // caller post-processes from AgentStateSnapshot
158 model: String::new(), // caller post-processes from AgentStateSnapshot
159 stop_reason: stop_reason.clone(),
160 timestamp,
161 })
162 }
163 AgentEvent::ToolExecutionStart { .. } => None,
164 AgentEvent::ToolExecutionEnd { tool_call_id, tool_name, result, is_error } => {
165 Some(SessionEntry::ToolResult {
166 id: EntryId::new(),
167 parent_id: None,
168 tool_call_id: tool_call_id.clone(),
169 tool_name: tool_name.clone(),
170 content: result.clone(),
171 is_error: *is_error,
172 timestamp,
173 })
174 }
175 AgentEvent::ToolExecutionUpdate { .. } => None,
176 AgentEvent::TextDelta { .. } => None,
177 AgentEvent::ThinkingDelta { .. } => None,
178 AgentEvent::Error { .. } => None,
179 }
180 }
181}
183/// Result from before_tool_call hook.
184#[derive(Clone, Debug, Default)]
185pub struct BeforeToolCallResult {
186 pub block: bool,
187 pub reason: Option<String>,
188}
190/// Result from after_tool_call hook.
191#[derive(Clone, Debug, Default)]
192pub 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>,
197}
199/// Context passed to `before_tool_call`.
200pub struct BeforeToolCallContext {
201 pub assistant_message: Message,
202 pub tool_call: ContentBlock, // ToolCall variant
203 pub args: serde_json::Value,
204 pub agent_context: AgentContext,
205}
207/// Context passed to `after_tool_call`.
208pub struct AfterToolCallContext {
209 pub assistant_message: Message,
210 pub tool_call: ContentBlock,
211 pub args: serde_json::Value,
212 pub result: AgentToolResult,
213 pub is_error: bool,
214 pub agent_context: AgentContext,
215}
217/// Context passed to `should_stop_after_turn`.
218pub struct ShouldStopAfterTurnContext {
219 pub message: Message,
220 pub tool_results: Vec<ContentBlock>,
221 pub agent_context: AgentContext,
222 pub new_messages: Vec<Message>,
223}
225/// Update returned by `prepare_next_turn` hook.
226#[derive(Clone, Debug)]
227pub struct AgentLoopTurnUpdate {
228 pub model_id: Option<String>,
229 pub thinking_level: Option<ThinkingLevel>,
230 pub context: Option<AgentContext>,
231}
233/// Tool execution concurrency mode.
234#[derive(Clone, Debug, Copy, PartialEq, Eq)]
235pub enum ToolExecutionMode {
236 Sequential,
237 Parallel,
238}
240/// Queue drain mode for steering/follow-up messages.
241#[derive(Clone, Debug, Copy, PartialEq, Eq)]
242pub enum QueueMode {
243 All,
244 OneAtATime,
245}
247/// Configuration for a single agent loop invocation.
125248pub struct AgentLoopConfig {
126249 pub model_id: String,
127250 pub provider_id: String,
128251 pub thinking_level: ThinkingLevel,
129252 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).
130271 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>>,
136274/// Stateful agent wrapper (like pi's Agent class)
@@ -151,6 +289,18 @@ 3. `smith-core/src/agent.rs` — The Agent Loop
151289 pub thinking_level: ThinkingLevel,
152290 pub is_streaming: bool,
153291 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>>,
156306impl Agent {
@@ -167,21 +317,57 @@ 3. `smith-core/src/agent.rs` — The Agent Loop
168318The core loop:
169319```
1701. Convert messages to LLM format (convert_to_llm)
1712. Optionally transform context (transform_context)
1723. Build ProviderRequest
1734. Call stream_fn(request) → get event stream
1745. Process ProviderEvents:
3201. Record trace: EnvSnapshot (cwd, env) if first turn
3212. Convert messages to LLM format (convert_to_llm)
3223. Optionally transform context (transform_context)
323 - Record trace: PluginEvent::Context if transform changes messages
3244. Build ProviderRequest
325 - Record trace: ProviderRequest { provider_id, model_id, payload_hash }
3265. Call stream_fn(request) → get event stream
3276. Process ProviderEvents:
175328 - TextDelta → emit AgentEvent::TextDelta, accumulate
176329 - ToolCall → queue tool call
177330 - ThinkingDelta → emit AgentEvent::ThinkingDelta
178 - Done → finalize assistant message, execute queued tools
1796. 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 messages
1837. If stop_reason == ToolUse, goto 1 (next turn)
1848. If stop_reason == EndTurn, emit AgentEnd
331 - Done → finalize assistant message
3327. Record trace: ProviderResponse { status, payload_hash }
3338. Emit TurnStart
334 - Record trace: AgentEvent::TurnStart
3359. 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 schema
338 c. before_tool_call hook → if block, emit error tool result
339 - Record trace: PluginEventResult::ToolCallBlock
340 d. Execute tool (AgentTool::execute) with abort signal
341 e. after_tool_call hook → apply overrides (content/details/is_error/terminate)
342 - Record trace: PluginEventResult::ToolResultOverride
343 f. Record trace: ToolEnd { result_hash, is_error }
344 g. Emit ToolExecutionStart/Update/End
345 - Record trace: AgentEvent for each
346 h. Add tool result to messages
347 i. **Early termination check:** If all finalized tools in this batch
348 had `terminate=true` (from after_tool_call or original result),
349 emit `AgentEnd` and exit immediately.
35010. Emit TurnEnd
351 - Record trace: AgentEvent::TurnEnd
35211. Record trace: Snapshot { agent_state } (every 10s or on compaction)
35312. should_stop_after_turn hook → if true, emit AgentEnd and exit
354 - Record trace: PluginEventResult::ShouldStopAfterTurn
35513. prepare_next_turn hook → apply context/model/thinking overrides
356 - Record trace: PluginEventResult::PrepareNextTurn
35714. If stop_reason == ToolUse, goto 2 (next turn)
35815. 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 AgentEnd
364 - Record trace: AgentEvent::AgentEnd
365 d. Else goto 2
367**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.
185371```
187373### 4. `smith-core/src/events.rs` — Engine Event Bus
@@ -338,24 +524,12 @@ 8. `smith-core/src/hooks.rs`
339525### 8. `smith-core/src/hooks.rs`
341Hook system for intercepting events. Maps to plugin SDK events.
343```rust
344pub struct HookRegistration {
345 pub event: String,
346 pub handler: Box<dyn Fn(&HookContext) -> HookResult + Send + Sync>,
347}
349pub struct HookContext {
350 pub event: String,
351 pub data: serde_json::Value,
352}
354pub enum HookResult {
355 Pass,
356 Modify { data: serde_json::Value },
357}
358```
527> **Note:** The legacy `hooks.rs` HookRegistration/HookResult system was removed.
528> All behavior mutation now happens through `AgentLoopConfig` typed hooks
529> (`before_tool_call`, `after_tool_call`, `should_stop_after_turn`, `prepare_next_turn`).
530> Plugin SDK event handlers in smith-harness return `PluginEventResult` values
531> which the harness translates into these hook results.
532> See SM-009 §Event Bridge for the plugin-side event result system.
360534### 9. `smith-core/src/system_prompt.rs`
492666```
668### 13. `smith-core/src/trace.rs` — Session Recording and Replay
670Deterministic replay requires capturing every event that affects state.
671The session log (`SessionEntry`) remains conversation-only for the LLM.
672The trace log (`TraceEntry`) captures everything: UI events, plugin events,
673provider requests/responses, system signals, and periodic snapshots.
675#### 13.1 Trace File Format
677Trace files are stored alongside session files in the XDG data directory:
679```
680data_dir/smith/
681 sessions/
682 {session-id}.session ← SessionEntry CBOR-seq (LLM context)
683 {session-id}.trace ← TraceEntry CBOR-seq (full replay log)
684```
686Trace file wire format:
688```
689┌───────────────────── Header (fixed 64 bytes) ─────────────────────┐
690│ magic: [u8; 4] = b"SMTH" │
691│ version: u16 = 1 │
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└────────────────────────────────────────────────────────────────────┘
701```
703```rust
704/// Trace file header. Fixed 64 bytes at file start.
705#[derive(Clone, Debug, Serialize, Deserialize)]
706pub struct TraceFileHeader {
707 pub magic: [u8; 4], // b"SMTH"
708 pub version: u16, // 1
709 pub flags: u16, // 0x01 = zstd compressed entries
710 pub session_id: [u8; 16], // UUID v7
711 pub start_timestamp_ns: u64,
712 pub reserved: [u8; 32],
713}
715impl TraceFileHeader {
716 pub const MAGIC: [u8; 4] = *b"SMTH";
717 pub const FLAG_COMPRESSED: u16 = 0x01;
718 pub const SIZE: usize = 64;
719}
720```
722#### 13.2 Trace Types
724```rust
725use std::sync::Arc;
726use tokio::sync::mpsc;
728/// Central recording trait. All subsystems call into a single recorder.
729pub trait TraceRecorder: Send + Sync {
730 /// Record a trace entry with monotonic nanosecond timestamp.
731 fn record(&self, entry: TraceEntry);
732 /// Flush pending entries to disk.
733 fn flush(&self) -> Result<()>;
734}
736/// File-backed trace recorder. Append-only CBOR-seq with optional zstd.
737pub struct FileTraceRecorder {
738 path: PathBuf,
739 header: TraceFileHeader,
740 tx: mpsc::UnboundedSender<TraceEntry>,
741}
743impl FileTraceRecorder {
744 /// Create new trace file with header. Returns recorder + writer handle.
745 /// If `compressed` is true, entries are individually zstd-compressed.
746 pub fn new(
747 path: PathBuf,
748 session_id: [u8; 16],
749 compressed: bool,
750 ) -> Result<(Self, TraceWriter)>;
752 /// Open existing trace file for appending (reads header, validates magic).
753 pub fn open(path: PathBuf) -> Result<(Self, TraceWriter)>;
754}
756/// Background writer task. Receives entries via channel, appends to file.
757pub struct TraceWriter;
759/// A single trace entry. Append-only, immutable.
760#[derive(Clone, Debug, Serialize, Deserialize, minicbor::Encode, minicbor::Decode)]
761pub enum TraceEntry {
762 // === Agent loop events (also in SessionEntry, but with precise timing) ===
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> },
769 // === TUI events ===
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 },
774 // === Plugin events ===
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 },
780 // === Provider interception ===
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 },
784 // === Tool execution ===
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 },
788 // === System events ===
789 SystemSignal { timestamp_ns: u64, signal: String },
790 EnvSnapshot { timestamp_ns: u64, cwd: String, env_vars: Vec<(String, String)> }, // API keys hashed: KEY=sha256:abc...
791 FileHashSnapshot { timestamp_ns: u64, files: Vec<(String, String)> }, // (path, sha256)
793 // === Snapshots (periodic state capture for deterministic replay) ===
794 Snapshot { timestamp_ns: u64, agent_state: AgentStateSnapshot }, // rng_seed omitted — smith does not use RNG in v1
795}
797/// Lightweight agent state snapshot for deterministic replay.
798#[derive(Clone, Debug, Serialize, Deserialize, minicbor::Encode, minicbor::Decode)]
799pub 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>,
805}
806```
808#### 13.3 Trace Codec
810```rust
811/// Trace codec — length-prefixed CBOR-seq with optional zstd compression.
812pub struct TraceCodec;
814impl TraceCodec {
815 /// Encode entries to CBOR-seq bytes (uncompressed).
816 pub fn encode(entries: &[TraceEntry]) -> Result<Vec<u8>>;
818 /// Decode CBOR-seq bytes to entries (fault-tolerant, same rules as SessionCodec).
819 pub fn decode(data: &[u8]) -> (Vec<TraceEntry>, Vec<DecodeError>);
821 /// Append a single entry to writer. If header has compression flag,
822 /// each entry is individually zstd-compressed: [u32 BE len][zstd(CBOR)].
823 pub fn append_entry(
824 writer: &mut impl Write,
825 entry: &TraceEntry,
826 compressed: bool,
827 ) -> Result<()>;
829 /// Read entries from a trace file (reads header, validates magic, decodes body).
830 pub fn read_file(path: &Path) -> Result<(TraceFileHeader, Vec<TraceEntry>, Vec<DecodeError>)>;
831}
832```
834**Compression trade-off:** Individual entry zstd compression (level 3) gives ~60-70% size
835reduction on typical traces. Each entry compressed independently preserves random access —
836a reader can skip an entry by reading the length prefix and seeking past. Block-level
837compression (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 executions
848(`read`, `write`, `edit`, `bash` tools). Not a full directory scan — tracked via
849a `touched_files: HashSet<PathBuf>` in the trace recorder.
851**EnvSnapshot scope:** `CWD`, `PATH`, `HOME`, `TERM`, `SHELL`, plus any vars
852prefixed with `SMITH_`. Provider API keys and other secrets are captured as
853`NAME=sha256:<hash>` — the value is hashed, not stored plaintext. This prevents
854secret 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 results
862- 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 times
873- Exact memory layout or heap state
874- 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:
878By re-executing tool calls in a controlled environment (same files, same env),
879the replay engine can diff old vs new tool outputs, isolating changes caused
880by code modifications vs. external state differences.
882#### 13.6 Smart Filter — TraceEntry → SessionEntry
884The smart filter produces the LLM-visible `SessionEntry` list from `TraceEntry`.
885Only 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 |
898```rust
899impl TraceEntry {
900 /// Filter trace entries to produce SessionEntry for LLM context.
901 pub fn to_session_entries(entries: &[TraceEntry]) -> Vec<SessionEntry> {
902 let mut result = Vec::new();
903 for e in entries {
904 match e {
905 TraceEntry::AgentEvent { timestamp_ns, event } => {
906 if let Some(se) = event.to_session_entry(*timestamp_ns) {
907 result.push(se);
908 }
909 }
910 TraceEntry::TurnEnd { timestamp_ns, messages } => {
911 // Steering/follow-up messages become user entries
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()),
915 _ => None,
916 }))
917 .collect::<Vec<_>>()
918 .join("\n");
919 if !text.is_empty() {
920 result.push(SessionEntry::User {
921 id: EntryId::new(),
922 parent_id: None,
923 content: vec![ContentBlock::Text { text }],
924 timestamp: *timestamp_ns,
925 });
926 }
927 }
928 TraceEntry::ToolStart { timestamp_ns, tool_name, args_json }
929 if tool_name == "bash" =>
930 {
931 // Extract command string from JSON args {"command":"ls",...}
932 let command = serde_json::from_str::<serde_json::Value>(args_json)
933 .ok()
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 {
937 id: EntryId::new(),
938 parent_id: None,
939 command,
940 output: String::new(), // output stored in ToolEnd, not session log
941 timestamp: *timestamp_ns,
942 });
943 }
944 TraceEntry::Snapshot { timestamp_ns, agent_state } => {
945 // Emit both ModelChange and ThinkingLevelChange from agent state
946 result.push(SessionEntry::ModelChange {
947 id: EntryId::new(),
948 parent_id: None,
949 provider: agent_state.provider_id.clone(),
950 model_id: agent_state.model_id.clone(),
951 timestamp: *timestamp_ns,
952 });
953 result.push(SessionEntry::ThinkingLevelChange {
954 id: EntryId::new(),
955 parent_id: None,
956 level: agent_state.thinking_level,
957 timestamp: *timestamp_ns,
958 });
959 }
960 _ => {} // TUI, plugin, provider events excluded from LLM context
961 }
962 }
963 result
964 }
965}
966```
968#### 13.7 Replay Engine
970The replay engine reconstructs a session from a trace log, feeding events into
971a reconstructed agent at configurable speed. Used for debugging, testing, and
972regression comparison.
974```rust
975/// Replay engine. Reads trace entries and reconstructs the session.
976pub struct ReplayEngine {
977 trace: Vec<TraceEntry>,
978 header: TraceFileHeader,
979 speed: ReplaySpeed,
980 mode: ReplayMode,
981 /// Current entry index for replay. Set by `seek_to_turn`.
982 cursor: usize,
983}
985/// Replay speed control.
986pub enum ReplaySpeed {
987 /// Max speed — process events as fast as possible, ignore timing.
988 Max,
989 /// Real-time — respect original inter-event timing from timestamps.
990 RealTime,
991 /// Custom multiplier — scale original timing by factor (2.0 = 2x speed).
992 Factor(f64),
993}
995/// Replay mode.
996pub enum ReplayMode {
997 /// Normal replay — reconstruct and display events.
998 Normal,
999 /// Compare mode — intercept tool calls, re-execute with current code,
1000 /// diff old vs new outputs. Requires controlled test environment.
1001 Compare {
1002 /// Directory containing the file state for replay.
1003 /// Should match the original session's CWD structure.
1004 sandbox_dir: PathBuf,
1005 /// Tool names to intercept for comparison (empty = all).
1006 tools: Vec<String>,
1007 /// Whether to continue on diff failures.
1008 continue_on_diff: bool,
1009 },
1012/// Result of a single replay step.
1013pub struct ReplayStep {
1014 pub entry: TraceEntry,
1015 pub timestamp_ns: u64,
1016 /// In compare mode: diff between old and new tool output, if any.
1017 pub diff: Option<ReplayDiff>,
1020/// Diff between original and replayed tool output.
1021pub struct ReplayDiff {
1022 pub tool_call_id: String,
1023 pub tool_name: String,
1024 /// Original output hash (from trace).
1025 pub original_hash: String,
1026 /// New output hash (from re-execution).
1027 pub new_hash: String,
1028 /// Unified diff of the output text, if textual.
1029 pub text_diff: Option<String>,
1032/// Summary produced at replay completion.
1033pub 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>,
1039 /// In compare mode: whether any diffs were found.
1040 pub has_regressions: bool,
1043impl ReplayEngine {
1044 /// Create replay engine from a trace file.
1045 pub fn from_file(
1046 path: &Path,
1047 speed: ReplaySpeed,
1048 mode: ReplayMode,
1049 ) -> Result<Self>;
1051 /// Run the replay. Calls `on_step` for each processed entry.
1052 ///
1053 /// The callback is synchronous (`Fn`) and must not block. Use it for
1054 /// lightweight work only (log, channel send, flag check). Heavy work
1055 /// (disk I/O, network) should be done in a separate task, or the replay
1056 /// will stall. Return `false` to abort the replay early.
1057 pub async fn run<F>(&mut self, on_step: F) -> Result<ReplaySummary>
1058 where
1059 F: Fn(ReplayStep) -> bool; // return false to abort
1061 /// Seek to the first entry of a specific turn.
1062 /// Sets internal cursor so subsequent `run()` begins at this position.
1063 /// Returns the entry index into `self.trace` where the turn starts.
1064 pub fn seek_to_turn(&mut self, turn_index: usize) -> Result<usize>;
1066 /// Extract the session entries from the trace (smart filter).
1067 pub fn extract_session(&self) -> Vec<SessionEntry>;
1069 /// Extract provider request/response pairs matched by request_id.
1070 /// Unmatched requests (no response recorded, e.g., crash mid-stream)
1071 /// are returned as `(request, None)`.
1072 pub fn extract_provider_trace(&self) -> Vec<(TraceEntry, Option<TraceEntry>)>;
1074```
1076**Replay execution flow:**
10771. Read trace file → decode header + entries.
10782. Optional: `seek_to_turn` to skip ahead.
10793. 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.
10834. For each entry:
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.
10875. 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.
4941112## Tests
1114- **Trace recording**
1115 - Mock TraceRecorder records all agent events
1116 - Verify TraceCodec roundtrip (encode → decode)
1117 - FileTraceRecorder appends without blocking
1118 - Smart filter produces correct SessionEntry subset
1119 - TraceFileHeader write/read roundtrip
1120 - TraceCodec with zstd compression roundtrip
1121 - EnvSnapshot captures selective env vars
1122 - FileHashSnapshot captures only touched files
1123 - Snapshot emission on 10s interval and model change
1124- **Replay engine**
1125 - ReplayEngine::from_file loads trace correctly
1126 - Max speed replay processes all entries without delays
1127 - RealTime replay respects inter-event timing
1128 - Factor replay scales timing correctly
1129 - seek_to_turn skips to correct position
1130 - extract_session produces same entries as live session
1131 - extract_provider_trace pairs request/response correctly
1132- **Compare mode**
1133 - Read tool re-execution matches original output (same files)
1134 - Write tool re-execution produces diff when content changed
1135 - Compare mode continues on diff with continue_on_diff: true
1136 - Compare mode stops on first diff with continue_on_diff: false
4961137- **Agent loop with mock stream** — most important test
4971138 - Mock StreamFn returns TextDelta + Done
4981139 - Agent emits AgentStart, MessageStart, TextDelta, MessageEnd, AgentEnd
5011142 - Mock StreamFn returns ToolCall + Done
5021143 - Agent executes tool, adds result, loops again
5031144 - Second loop returns EndTurn
1145- **before_tool_call blocking**
1146 - Mock before_tool_call returns block=true
1147 - Tool not executed; error result added to messages
1148- **after_tool_call mutation**
1149 - Mock after_tool_call overrides content/details/is_error
1150 - Modified result added to messages
1151- **should_stop_after_turn**
1152 - Hook returns true after N turns
1153 - Agent emits AgentEnd and exits cleanly
1154- **prepare_next_turn**
1155 - Hook returns new model_id/thinking_level
1156 - Next turn uses updated config
1157- **ToolExecutionMode::Parallel**
1158 - Multiple tool calls execute concurrently
1159 - Results collected and added in source order
1160- **QueueMode::OneAtATime**
1161 - Steering queue drains one message per turn
1162 - Follow-up queue drains one message per turn
5041163- **Session creation and entry addition**
5051164- **Session fork creates correct tree**
5061165- **SecretProxy hides and restores secrets**
5181177- [ ] Create `smith-core/src/session.rs` (SessionEntry canonical definition)
5191178- [ ] Create `smith-core/src/session_format.rs` (CBOR codec)
5201179- [ ] Create `smith-core/src/tools.rs` (ToolRegistry)
521- [ ] Create `smith-core/src/hooks.rs`
5221180- [ ] Create `smith-core/src/events.rs` (EngineEvent wrapping AgentEvent)
5231181- [ ] Create `smith-core/src/secret_proxy.rs`
5241182- [ ] Create `smith-core/src/system_prompt.rs` (expanded)
5251183- [ ] Create `smith-core/src/compaction.rs` (TokenEstimator)
5261184- [ ] 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)
5271187- [ ] Write agent loop tests (mock stream function)
5281188- [ ] 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)
5291191- [ ] Verify: `cargo check -p smith-core`
5301192- [ ] 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

242412. **`smith eval --session <id>`** — attach to session for eval
252513. **`smith rpc`** — JSON-RPC via stdio
262614. **`smith help [topic]`** — documentation browser
2715. **Global flags:** `--model`, `--provider`, `--session`, `--config`, `--no-config`
2715. **`smith replay <session-id>`** — replay session from trace log
2816. **`smith replay <session-id> --speed 2`** — replay at 2x speed
2917. **`smith replay <session-id> --compare`** — compare old vs new tool outputs
3018. **Global flags:** `--model`, `--provider`, `--session`, `--config`, `--no-config`
2932## Deliverables
144147 #[arg(long)]
145148 guide: Option<String>,
146149 },
151 /// Replay a session from trace log
152 Replay {
153 /// Session id or name
154 session: String,
156 /// Replay speed multiplier (1.0 = real-time, 0 = max speed)
157 #[arg(long, default_value = "1.0")]
158 speed: f64,
160 /// Compare mode: re-execute tools and diff outputs
161 #[arg(long)]
162 compare: bool,
164 /// Sandbox directory for compare mode (must match original CWD structure)
165 #[arg(long)]
166 sandbox: Option<PathBuf>,
168 /// Stop after N turns (0 = full replay)
169 #[arg(long)]
170 turns: Option<usize>,
172 /// Start from turn N (0 = from beginning)
173 #[arg(long, default_value = "0")]
174 from_turn: usize,
176 /// Output format: text, json, summary
177 #[arg(long, default_value = "text")]
178 format: String,
180 /// Continue on diff failures in compare mode
181 #[arg(long, default_value = "true")]
182 continue_on_diff: bool,
183 },
148185```
195232 Some(Commands::Help { topic, search, list, examples, example, guide }) => {
196233 run_help(topic, search, list, examples, example, guide)
197234 }
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).await
237 }
198238 }
200240```
215255`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):
2581. Resolve session id via `SessionStore`
2592. Load trace file from `{data_dir}/sessions/{id}.trace`
2603. Convert speed flag: `speed == 0.0` → `ReplaySpeed::Max`, `speed == 1.0` → `ReplaySpeed::RealTime`, else `ReplaySpeed::Factor(speed)`
2614. Create `ReplayEngine::from_file` with resolved speed and mode
2625. Run replay loop:
263 - Each entry → `ReplayStep` → formatted output to stdout
264 - Speed control: max (no delays), real-time, or factor (N× speed)
265 - Progress indicator: `[42/187] Turn 3 — ToolResult(bash)`
2666. In compare mode (`--compare`):
267 - Intercept `ToolEnd` entries → re-execute tool in sandbox directory
268 - Compare result hash vs original → emit `ReplayDiff` if different
269 - Continue or stop on diff based on `--continue-on-diff` flag
2707. Output formats:
271 - Default: human-readable step-by-step log
272 - `--format json`: JSONL stream of `ReplayStep` objects
273 - `--format summary`: only final `ReplaySummary`
2748. On completion, print `ReplaySummary` (total entries, diffs, regressions)
276Compare mode example:
277```bash
278# Replay session, re-execute tools against current codebase, show diffs
279smith replay abc123 --compare --sandbox /tmp/smith-test-env --format json
281# Quick replay at 5x speed, no comparison
282smith replay abc123 --speed 5.0 --format summary
284# Replay only turns 10-20
285smith replay abc123 --speed 0 --from-turn 10 --turns 10
286```
217288## Tests
219290- CLI parsing: all subcommands parse correctly
230301- `smith session dump --last 5` limits to last 5 entries
231302- `smith session dump --output out.jsonl` writes to file
232303- `smith --no-config` skips config loading
304- `smith replay abc123` replays session from trace
305- `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× speed
307- `smith replay abc123 --compare --sandbox /tmp/test` replays with tool comparison
308- `smith replay abc123 --format json` outputs JSONL replay steps
309- `smith replay abc123 --from-turn 5 --turns 3` replays turns 5-7 only
234311## Steps