feat(prototypes): P14 replay engine + P15 hot reload
e1e4d331914fc257e7b80e589b0a6f3840138967
HallucyGenie Agent <agent@hallucygenie.local> ·
SSH signature · not checked
Browse filesCompare with HEAD
P14: ReplayEngine with 55-entry synthetic trace, 10 tests
- ReplaySpeed Max/RealTime/Factor with tokio sleep
- ReplayMode Normal + Compare (tool re-exec hash diff)
- seek_to_turn, extract_session (smart filter), extract_provider_trace
- 13 TraceEntry variants, CBOR+zstd TraceCodec roundtrip
P15: Hot reload with 10 tests
- Lua plugin v1→v2 hot swap with hook replacement
- Session state preserved across reloads
- Rollback on syntax error (v3) and missing hook (v4)
- Trace: PluginLoaded/PluginEvent/PluginError events
- 10 consecutive reloads with alternating v2/v5
Changed files (6)
prototypes/p14-replay-engine/Cargo.lock
Addednew file mode 100644+443 / −0 text lines
8+source = "registry+https://github.com/rust-lang/crates.io-index" 9+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" 17+source = "registry+https://github.com/rust-lang/crates.io-index" 18+checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" 29+source = "registry+https://github.com/rust-lang/crates.io-index" 30+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" 35+source = "registry+https://github.com/rust-lang/crates.io-index" 36+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" 46+source = "registry+https://github.com/rust-lang/crates.io-index" 47+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" 52+source = "registry+https://github.com/rust-lang/crates.io-index" 53+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" 62+source = "registry+https://github.com/rust-lang/crates.io-index" 63+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" 71+source = "registry+https://github.com/rust-lang/crates.io-index" 72+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" 75+name = "crypto-common" 77+source = "registry+https://github.com/rust-lang/crates.io-index" 78+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" 87+source = "registry+https://github.com/rust-lang/crates.io-index" 88+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" 95+name = "find-msvc-tools" 97+source = "registry+https://github.com/rust-lang/crates.io-index" 98+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" 101+name = "generic-array" 103+source = "registry+https://github.com/rust-lang/crates.io-index" 104+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" 113+source = "registry+https://github.com/rust-lang/crates.io-index" 114+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" 124+source = "registry+https://github.com/rust-lang/crates.io-index" 125+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" 136+source = "registry+https://github.com/rust-lang/crates.io-index" 137+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" 147+source = "registry+https://github.com/rust-lang/crates.io-index" 148+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" 153+source = "registry+https://github.com/rust-lang/crates.io-index" 154+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" 163+source = "registry+https://github.com/rust-lang/crates.io-index" 164+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" 169+source = "registry+https://github.com/rust-lang/crates.io-index" 170+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" 173+name = "p14-replay-engine" 186+name = "pin-project-lite" 188+source = "registry+https://github.com/rust-lang/crates.io-index" 189+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" 194+source = "registry+https://github.com/rust-lang/crates.io-index" 195+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" 200+source = "registry+https://github.com/rust-lang/crates.io-index" 201+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" 209+source = "registry+https://github.com/rust-lang/crates.io-index" 210+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" 218+source = "registry+https://github.com/rust-lang/crates.io-index" 219+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" 227+source = "registry+https://github.com/rust-lang/crates.io-index" 228+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" 233+source = "registry+https://github.com/rust-lang/crates.io-index" 234+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" 244+source = "registry+https://github.com/rust-lang/crates.io-index" 245+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" 254+source = "registry+https://github.com/rust-lang/crates.io-index" 255+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" 263+source = "registry+https://github.com/rust-lang/crates.io-index" 264+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" 273+source = "registry+https://github.com/rust-lang/crates.io-index" 274+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" 280+name = "serde_derive" 282+source = "registry+https://github.com/rust-lang/crates.io-index" 283+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" 293+source = "registry+https://github.com/rust-lang/crates.io-index" 294+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" 306+source = "registry+https://github.com/rust-lang/crates.io-index" 307+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" 317+source = "registry+https://github.com/rust-lang/crates.io-index" 318+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" 323+source = "registry+https://github.com/rust-lang/crates.io-index" 324+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" 334+source = "registry+https://github.com/rust-lang/crates.io-index" 335+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" 342+name = "tokio-macros" 344+source = "registry+https://github.com/rust-lang/crates.io-index" 345+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" 355+source = "registry+https://github.com/rust-lang/crates.io-index" 356+checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de" 359+name = "unicode-ident" 361+source = "registry+https://github.com/rust-lang/crates.io-index" 362+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" 365+name = "version_check" 367+source = "registry+https://github.com/rust-lang/crates.io-index" 368+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" 372+version = "0.11.1+wasi-snapshot-preview1" 373+source = "registry+https://github.com/rust-lang/crates.io-index" 374+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" 378+version = "1.0.3+wasi-0.2.9" 379+source = "registry+https://github.com/rust-lang/crates.io-index" 380+checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" 388+source = "registry+https://github.com/rust-lang/crates.io-index" 389+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" 394+source = "registry+https://github.com/rust-lang/crates.io-index" 395+checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" 401+name = "zerocopy-derive" 403+source = "registry+https://github.com/rust-lang/crates.io-index" 404+checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" 414+source = "registry+https://github.com/rust-lang/crates.io-index" 415+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" 420+source = "registry+https://github.com/rust-lang/crates.io-index" 421+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" 429+source = "registry+https://github.com/rust-lang/crates.io-index" 430+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" 437+version = "2.0.16+zstd.1.5.7" 438+source = "registry+https://github.com/rust-lang/crates.io-index" 439+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" prototypes/p14-replay-engine/Cargo.toml
Addednew file mode 100644+13 / −0 text lines
2+name = "p14-replay-engine" 8+serde = { version = "1", features = ["derive"] } 13+tokio = { version = "1", features = ["rt-multi-thread", "macros"] } prototypes/p14-replay-engine/src/main.rs
Addednew file mode 100644+741 / −0 text lines
14+#![allow(missing_docs, unused_variables, unused_assignments)] 16+use serde::{Deserialize, Serialize}; 17+use std::collections::HashMap; 18+use std::io::{Cursor, Read, Write}; 22+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] 23+pub struct EntryId(pub String); 25+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 26+pub enum Role { System, User, Assistant, Tool } 28+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 29+pub enum StopReason { EndTurn, ToolUse, OverMaxTokens, Aborted, StopSequence, Error } 31+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] 32+pub enum ContentBlock { 34+ ToolCall { id: String, name: String, arguments: String }, 35+ ToolResult { id: String, result: String, is_error: bool }, 36+ Thinking { content: String }, 39+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] 40+pub struct ProviderUsage { 41+ pub input_tokens: u64, 42+ pub output_tokens: u64, 43+ pub cache_read_tokens: Option<u64>, 44+ pub cache_write_tokens: Option<u64>, 45+ pub total_tokens: Option<u64>, 50+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] 51+pub enum SessionEntry { 52+ Session { version: u32, created: u64 }, 53+ User { id: EntryId, parent_id: Option<EntryId>, content: Vec<ContentBlock>, timestamp: u64 }, 54+ Assistant { id: EntryId, parent_id: Option<EntryId>, content: Vec<ContentBlock>, usage: ProviderUsage, provider: String, model: String, stop_reason: StopReason, timestamp: u64 }, 55+ ToolResult { id: EntryId, parent_id: Option<EntryId>, tool_call_id: String, tool_name: String, content: Vec<ContentBlock>, is_error: bool, timestamp: u64 }, 56+ Compaction { id: EntryId, parent_id: Option<EntryId>, summary: String, first_kept_id: EntryId, tokens_before: u64, read_files: Vec<String>, modified_files: Vec<String>, timestamp: u64 }, 57+ Unknown { id: EntryId, data: Vec<u8>, timestamp: u64 }, 62+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] 64+ AgentEvent { timestamp_ns: u64, event: String }, 65+ TurnStart { timestamp_ns: u64, turn_number: u32, model: String, provider: String }, 66+ TurnEnd { timestamp_ns: u64, turn_number: u32, stop_reason: String }, 67+ ToolStart { timestamp_ns: u64, tool_call_id: String, tool_name: String, args_json: String }, 68+ ToolEnd { timestamp_ns: u64, tool_call_id: String, tool_name: String, result_hash: String, is_error: bool }, 69+ ProviderRequest { timestamp_ns: u64, request_id: String, model: String, prompt_tokens: u64 }, 70+ ProviderResponse { timestamp_ns: u64, request_id: String, completion_tokens: u64, finish_reason: String }, 71+ PluginLoaded { timestamp_ns: u64, path: String, success: bool }, 72+ PluginEvent { timestamp_ns: u64, plugin: String, event: String }, 73+ PluginError { timestamp_ns: u64, plugin: String, error: String }, 74+ EnvSnapshot { timestamp_ns: u64, cwd: String, env_vars: Vec<(String, String)> }, 75+ FileHashSnapshot { timestamp_ns: u64, files: Vec<(String, String)> }, 76+ Snapshot { timestamp_ns: u64, message_count: u32, model: String, pending_tools: u32 }, 81+#[derive(Clone, Debug)] 82+pub struct TraceFileHeader { 86+ pub session_id: [u8; 16], 87+ pub start_timestamp_ns: u64, 88+ pub reserved: [u8; 32], 91+impl TraceFileHeader { 92+ pub const MAGIC: [u8; 4] = *b"SMTH"; 93+ pub const VERSION: u16 = 1; 94+ pub const FLAG_COMPRESSED: u16 = 0x01; 95+ pub const SIZE: usize = 64; 97+ pub fn new(session_id: [u8; 16], start_ts: u64, compressed: bool) -> Self { 98+ Self { magic: Self::MAGIC, version: Self::VERSION, flags: if compressed { Self::FLAG_COMPRESSED } else { 0 }, session_id, start_timestamp_ns: start_ts, reserved: [0u8; 32] } 101+ pub fn write(&self, w: &mut impl Write) -> std::io::Result<()> { 102+ w.write_all(&self.magic)?; 103+ w.write_all(&self.version.to_be_bytes())?; 104+ w.write_all(&self.flags.to_be_bytes())?; 105+ w.write_all(&self.session_id)?; 106+ w.write_all(&self.start_timestamp_ns.to_be_bytes())?; 107+ w.write_all(&self.reserved)?; 111+ pub fn read(r: &mut impl Read) -> std::io::Result<Self> { 112+ let mut magic = [0u8; 4]; r.read_exact(&mut magic)?; 113+ if magic != Self::MAGIC { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad magic")); } 114+ let mut buf = [0u8; 2]; r.read_exact(&mut buf)?; let version = u16::from_be_bytes(buf); 115+ if version != Self::VERSION { return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad version")); } 116+ let mut buf = [0u8; 2]; r.read_exact(&mut buf)?; let flags = u16::from_be_bytes(buf); 117+ let mut session_id = [0u8; 16]; r.read_exact(&mut session_id)?; 118+ let mut buf = [0u8; 8]; r.read_exact(&mut buf)?; let start = u64::from_be_bytes(buf); 119+ let mut reserved = [0u8; 32]; r.read_exact(&mut reserved)?; 120+ Ok(Self { magic, version, flags, session_id, start_timestamp_ns: start, reserved }) 126+fn encode_lp(entries: &[TraceEntry]) -> Vec<u8> { 127+ let mut buf = Vec::new(); 129+ let mut cbor = Vec::new(); 130+ ciborium::ser::into_writer(e, &mut cbor).unwrap(); 131+ let payload = zstd::encode_all(&cbor[..], 3).unwrap(); 132+ buf.extend_from_slice(&(payload.len() as u32).to_be_bytes()); 133+ buf.extend_from_slice(&payload); 138+fn decode_lp(data: &[u8]) -> Vec<TraceEntry> { 139+ let mut cursor = &data[..]; 140+ let mut out = Vec::new(); 141+ while !cursor.is_empty() { 142+ let mut len_buf = [0u8; 4]; cursor.read_exact(&mut len_buf).unwrap(); 143+ let len = u32::from_be_bytes(len_buf) as usize; 144+ let dec = zstd::decode_all(&cursor[..len]).unwrap(); 145+ out.push(ciborium::de::from_reader(&dec[..]).unwrap()); 146+ cursor = &cursor[len..]; 153+#[derive(Clone, Debug)] 154+pub enum ReplaySpeed { 160+#[derive(Clone, Debug)] 161+pub enum ReplayMode { 163+ Compare { sandbox_dir: String, continue_on_diff: bool }, 166+#[derive(Clone, Debug, serde::Serialize)] 167+pub struct ReplayDiff { 168+ pub tool_call_id: String, 169+ pub tool_name: String, 170+ pub original_hash: String, 171+ pub new_hash: String, 172+ pub text_diff: String, 175+#[derive(Clone, Debug)] 176+pub struct ReplayStep { 177+ pub entry: TraceEntry, 178+ pub timestamp_ns: u64, 180+ pub diff: Option<ReplayDiff>, 183+#[derive(Clone, Debug, Default, serde::Serialize)] 184+pub struct ReplaySummary { 185+ pub total_entries: usize, 186+ pub duration_ms: u64, 187+ pub agent_events: usize, 188+ pub tool_executions: usize, 190+ pub provider_requests: usize, 192+ pub snapshots: usize, 193+ pub diffs: Vec<ReplayDiff>, 198+pub struct ReplayEngine { 199+ entries: Vec<TraceEntry>, 201+ turn_indices: Vec<usize>, 205+ pub fn from_entries(entries: Vec<TraceEntry>, start_ts: u64) -> Self { 206+ let turn_indices: Vec<usize> = entries.iter().enumerate() 207+ .filter(|(_, e)| matches!(e, TraceEntry::TurnStart { .. })) 210+ Self { entries, start_ts, turn_indices } 214+ pub fn from_bytes(data: &[u8], start_ts: u64) -> Self { 215+ let entries = decode_lp(data); 216+ Self::from_entries(entries, start_ts) 220+ pub fn len(&self) -> usize { self.entries.len() } 223+ pub fn seek_to_turn(&self, turn: usize) -> &[TraceEntry] { 224+ if turn >= self.turn_indices.len() { 225+ return &self.entries[self.entries.len()..]; 227+ &self.entries[self.turn_indices[turn]..] 231+ pub fn turn_count(&self) -> usize { self.turn_indices.len() } 235+ pub fn run<F>(&self, speed: &ReplaySpeed, mode: &ReplayMode, mut on_step: F) -> ReplaySummary 236+ where F: FnMut(&ReplayStep) -> bool 238+ let mut summary = ReplaySummary::default(); 239+ let start = std::time::Instant::now(); 240+ let mut prev_ts = self.start_ts; 243+ let mut pending_tools: HashMap<String, (String, String)> = HashMap::new(); 245+ for (idx, entry) in self.entries.iter().enumerate() { 246+ let ts = get_ts(entry); 247+ let mut diff = None; 251+ ReplaySpeed::Max => {}, 252+ ReplaySpeed::RealTime => { 253+ let gap_ns = ts.saturating_sub(prev_ts); 254+ std::thread::sleep(std::time::Duration::from_nanos(gap_ns)); 256+ ReplaySpeed::Factor(f) => { 257+ let gap_ns = ts.saturating_sub(prev_ts); 258+ let scaled = (gap_ns as f64 / *f) as u64; 259+ std::thread::sleep(std::time::Duration::from_nanos(scaled)); 265+ if let ReplayMode::Compare { sandbox_dir, .. } = mode { 267+ TraceEntry::ToolStart { tool_call_id, tool_name, args_json, .. } => { 268+ pending_tools.insert(tool_call_id.clone(), (tool_name.clone(), args_json.clone())); 270+ TraceEntry::ToolEnd { tool_call_id, tool_name, result_hash, is_error: _, .. } => { 271+ if let Some((name, args)) = pending_tools.remove(tool_call_id) { 272+ let new_hash = simulate_tool_exec(sandbox_dir, &name, &args); 273+ if new_hash != *result_hash { 274+ let d = ReplayDiff { 275+ tool_call_id: tool_call_id.clone(), 277+ original_hash: result_hash.clone(), 278+ new_hash: new_hash.clone(), 279+ text_diff: format!("original={} new={}", result_hash, &new_hash), 281+ diff = Some(d.clone()); 282+ summary.diffs.push(d); 290+ summary.total_entries += 1; 293+ TraceEntry::AgentEvent { .. } => summary.agent_events += 1, 294+ TraceEntry::ToolEnd { .. } => summary.tool_executions += 1, 295+ TraceEntry::TurnStart { .. } => summary.turns += 1, 296+ TraceEntry::ProviderRequest { .. } => summary.provider_requests += 1, 297+ TraceEntry::ProviderResponse { .. } => summary.provider_requests += 1, 298+ TraceEntry::PluginLoaded { .. } | TraceEntry::PluginEvent { .. } | TraceEntry::PluginError { .. } => summary.plugins += 1, 299+ TraceEntry::EnvSnapshot { .. } | TraceEntry::FileHashSnapshot { .. } | TraceEntry::Snapshot { .. } => summary.snapshots += 1, 300+ TraceEntry::TurnEnd { .. } => {}, 301+ TraceEntry::ToolStart { .. } => {}, 304+ let step = ReplayStep { entry: entry.clone(), timestamp_ns: ts, index: idx, diff }; 305+ if !on_step(&step) { break; } 308+ summary.duration_ms = start.elapsed().as_millis() as u64; 313+ pub fn extract_session(&self) -> Vec<SessionEntry> { 314+ let mut out = Vec::new(); 316+ let mut msg_count = 0u32; 318+ for entry in &self.entries { 320+ let id = EntryId(format!("e{}", eid)); 321+ let parent = if out.is_empty() { None } else { Some(EntryId(format!("e{}", eid - 1))) }; 322+ let ts = get_ts(entry) / 1_000_000; 325+ TraceEntry::AgentEvent { event, .. } if event == "SessionStart" => { 326+ out.push(SessionEntry::Session { version: 1, created: ts }); 328+ TraceEntry::TurnStart { turn_number, .. } if *turn_number == 0 => { 330+ out.push(SessionEntry::User { 331+ id: EntryId(format!("e{}", eid)), parent_id: None, 332+ content: vec![ContentBlock::Text(format!("[User message for turn 0]"))], 336+ TraceEntry::ProviderResponse { request_id, completion_tokens, finish_reason, .. } => { 338+ out.push(SessionEntry::Assistant { 339+ id, parent_id: parent, 340+ content: vec![ContentBlock::Text(format!("[Response {} tokens, {}]", completion_tokens, finish_reason))], 341+ usage: ProviderUsage { 342+ input_tokens: 50, output_tokens: *completion_tokens, 343+ cache_read_tokens: None, cache_write_tokens: None, total_tokens: Some(50 + completion_tokens), 345+ provider: "minimax".into(), model: "MiniMax-M2.7".into(), 346+ stop_reason: if finish_reason == "stop" { StopReason::EndTurn } else { StopReason::OverMaxTokens }, 350+ TraceEntry::ToolEnd { tool_call_id, tool_name, result_hash, is_error, .. } => { 351+ out.push(SessionEntry::ToolResult { 352+ id, parent_id: parent, 353+ tool_call_id: tool_call_id.clone(), tool_name: tool_name.clone(), 354+ content: vec![ContentBlock::ToolResult { 355+ id: tool_call_id.clone(), result: format!("hash:{}", result_hash), is_error: *is_error, 357+ is_error: *is_error, timestamp: ts, 360+ TraceEntry::Snapshot { message_count, .. } => { 362+ if *message_count > 10 { 363+ out.push(SessionEntry::Compaction { 364+ id, parent_id: parent, 365+ summary: format!("Compacted at {} messages", message_count), 366+ first_kept_id: EntryId(format!("e{}", eid.saturating_sub(5))), 367+ tokens_before: 5000, read_files: vec!["main.rs".into()], modified_files: vec!["lib.rs".into()], 374+ let data = format!("{:?}", entry); 375+ out.push(SessionEntry::Unknown { 376+ id, data: data.into_bytes(), timestamp: ts, 385+ pub fn extract_provider_trace(&self) -> Vec<(TraceEntry, Option<TraceEntry>)> { 386+ let mut reqs: HashMap<String, TraceEntry> = HashMap::new(); 387+ let mut out = Vec::new(); 389+ for entry in &self.entries { 391+ TraceEntry::ProviderRequest { request_id, .. } => { 392+ reqs.insert(request_id.clone(), entry.clone()); 394+ TraceEntry::ProviderResponse { request_id, .. } => { 395+ let req = reqs.remove(request_id).unwrap_or_else(|| { 396+ TraceEntry::AgentEvent { timestamp_ns: 0, event: "[missing request]".into() } 398+ out.push((req, Some(entry.clone()))); 404+ for (_, req) in reqs.drain() { 405+ out.push((req, None)); 413+fn get_ts(e: &TraceEntry) -> u64 { 415+ TraceEntry::AgentEvent { timestamp_ns, .. } => *timestamp_ns, 416+ TraceEntry::TurnStart { timestamp_ns, .. } => *timestamp_ns, 417+ TraceEntry::TurnEnd { timestamp_ns, .. } => *timestamp_ns, 418+ TraceEntry::ToolStart { timestamp_ns, .. } => *timestamp_ns, 419+ TraceEntry::ToolEnd { timestamp_ns, .. } => *timestamp_ns, 420+ TraceEntry::ProviderRequest { timestamp_ns, .. } => *timestamp_ns, 421+ TraceEntry::ProviderResponse { timestamp_ns, .. } => *timestamp_ns, 422+ TraceEntry::PluginLoaded { timestamp_ns, .. } => *timestamp_ns, 423+ TraceEntry::PluginEvent { timestamp_ns, .. } => *timestamp_ns, 424+ TraceEntry::PluginError { timestamp_ns, .. } => *timestamp_ns, 425+ TraceEntry::EnvSnapshot { timestamp_ns, .. } => *timestamp_ns, 426+ TraceEntry::FileHashSnapshot { timestamp_ns, .. } => *timestamp_ns, 427+ TraceEntry::Snapshot { timestamp_ns, .. } => *timestamp_ns, 432+fn simulate_tool_exec(sandbox_dir: &str, tool_name: &str, args: &str) -> String { 433+ use sha2::{Sha256, Digest}; 434+ let mut hasher = Sha256::new(); 435+ hasher.update(sandbox_dir.as_bytes()); 436+ hasher.update(tool_name.as_bytes()); 437+ hasher.update(args.as_bytes()); 439+ hasher.update(b"re-exec-v2"); 440+ let hash = hasher.finalize(); 441+ format!("sha256:{:x}", hash)[..16].to_string() 445+fn original_tool_hash(tool_name: &str, args: &str) -> String { 446+ use sha2::{Sha256, Digest}; 447+ let mut hasher = Sha256::new(); 448+ hasher.update(tool_name.as_bytes()); 449+ hasher.update(args.as_bytes()); 450+ let hash = hasher.finalize(); 451+ format!("sha256:{:x}", hash)[..16].to_string() 456+fn generate_trace() -> Vec<TraceEntry> { 457+ let mut entries = Vec::new(); 458+ let base_ts = 1_715_000_000_000_000u64; 459+ let mut ts = base_ts; 462+ entries.push(TraceEntry::AgentEvent { timestamp_ns: ts, event: "SessionStart".into() }); ts += 1_000_000; 465+ entries.push(TraceEntry::EnvSnapshot { 466+ timestamp_ns: ts, cwd: "/home/user/smith".into(), 467+ env_vars: vec![("HOME".into(), "/home/user".into()), ("SHELL".into(), "/bin/bash".into())], 471+ entries.push(TraceEntry::PluginLoaded { timestamp_ns: ts, path: "formatter.lua".into(), success: true }); ts += 2_000_000; 472+ entries.push(TraceEntry::PluginEvent { timestamp_ns: ts, plugin: "formatter".into(), event: "registered".into() }); ts += 1_000_000; 476+ ("bash", r#"{"cmd":"ls -la"}"#), 477+ ("read_file", r#"{"path":"src/main.rs"}"#), 478+ ("grep", r#"{"pattern":"TODO","path":"src/"}"#), 479+ ("write_file", r#"{"path":"src/lib.rs","content":"fn main() {}"}"#), 480+ ("bash", r#"{"cmd":"cargo test"}"#), 481+ ("read_file", r#"{"path":"Cargo.toml"}"#), 482+ ("bash", r#"{"cmd":"git diff"}"#), 487+ entries.push(TraceEntry::TurnStart { 488+ timestamp_ns: ts, turn_number: turn, model: "MiniMax-M2.7".into(), provider: "minimax".into(), 492+ let req_id = format!("req-{}", turn); 493+ entries.push(TraceEntry::ProviderRequest { 494+ timestamp_ns: ts, request_id: req_id.clone(), model: "MiniMax-M2.7".into(), prompt_tokens: (50 + turn * 10) as u64, 495+ }); ts += 3_000_000; 496+ entries.push(TraceEntry::ProviderResponse { 497+ timestamp_ns: ts, request_id: req_id, completion_tokens: (100 + turn * 20) as u64, 498+ finish_reason: if turn == 3 { "length".into() } else { "stop".into() }, 499+ }); ts += 2_000_000; 502+ entries.push(TraceEntry::AgentEvent { timestamp_ns: ts, event: "Thinking".into() }); ts += 1_000_000; 505+ let tool_idx = (turn * 2) as usize; 506+ let tool_count = 1 + (turn % 2) as usize; 507+ for t in 0..tool_count { 508+ let (tname, targs) = tools[(tool_idx + t) % tools.len()]; 509+ let call_id = format!("c{}-{}", turn, t); 510+ let hash = original_tool_hash(tname, targs); 511+ entries.push(TraceEntry::ToolStart { 512+ timestamp_ns: ts, tool_call_id: call_id.clone(), tool_name: tname.to_string(), args_json: targs.to_string(), 513+ }); ts += 5_000_000; 514+ entries.push(TraceEntry::ToolEnd { 515+ timestamp_ns: ts, tool_call_id: call_id, tool_name: tname.to_string(), result_hash: hash, is_error: false, 516+ }); ts += 2_000_000; 521+ entries.push(TraceEntry::FileHashSnapshot { 522+ timestamp_ns: ts, files: vec![ 523+ ("src/main.rs".into(), format!("h{}a", turn)), 524+ ("src/lib.rs".into(), format!("h{}b", turn)), 530+ entries.push(TraceEntry::Snapshot { 531+ timestamp_ns: ts, message_count: (turn + 1) * 3, model: "MiniMax-M2.7".into(), pending_tools: 0, 535+ entries.push(TraceEntry::TurnEnd { 536+ timestamp_ns: ts, turn_number: turn, 537+ stop_reason: if turn == 3 { "length".into() } else { "end_turn".into() }, 538+ }); ts += 1_000_000; 542+ entries.push(TraceEntry::PluginEvent { 543+ timestamp_ns: ts, plugin: "formatter".into(), event: "formatted".into(), 544+ }); ts += 1_000_000; 549+ entries.push(TraceEntry::PluginError { timestamp_ns: ts, plugin: "linter".into(), error: "parse error".into() }); ts += 1_000_000; 552+ entries.push(TraceEntry::EnvSnapshot { 553+ timestamp_ns: ts, cwd: "/home/user/smith".into(), 554+ env_vars: vec![("HOME".into(), "/home/user".into())], 564+ eprintln!("=== P14: Replay Engine ==="); 568+ eprintln!("--- Test 1: Synthetic trace generation ---"); 569+ let entries = generate_trace(); 570+ eprintln!("[OK] Generated {} trace entries", entries.len()); 571+ assert!(entries.len() >= 50, "Need 50+ entries, got {}", entries.len()); 574+ let mut variant_counts: HashMap<&str, usize> = HashMap::new(); 576+ let name = match e { 577+ TraceEntry::AgentEvent { .. } => "AgentEvent", 578+ TraceEntry::TurnStart { .. } => "TurnStart", 579+ TraceEntry::TurnEnd { .. } => "TurnEnd", 580+ TraceEntry::ToolStart { .. } => "ToolStart", 581+ TraceEntry::ToolEnd { .. } => "ToolEnd", 582+ TraceEntry::ProviderRequest { .. } => "ProviderRequest", 583+ TraceEntry::ProviderResponse { .. } => "ProviderResponse", 584+ TraceEntry::PluginLoaded { .. } => "PluginLoaded", 585+ TraceEntry::PluginEvent { .. } => "PluginEvent", 586+ TraceEntry::PluginError { .. } => "PluginError", 587+ TraceEntry::EnvSnapshot { .. } => "EnvSnapshot", 588+ TraceEntry::FileHashSnapshot { .. } => "FileHashSnapshot", 589+ TraceEntry::Snapshot { .. } => "Snapshot", 591+ *variant_counts.entry(name).or_insert(0) += 1; 593+ eprintln!(" Variants: {:?}", variant_counts); 594+ assert!(variant_counts.len() >= 10, "Should cover 10+ variants, got {}", variant_counts.len()); 597+ eprintln!("--- Test 2: TraceCodec roundtrip ---"); 598+ let header = TraceFileHeader::new([0xAB; 16], get_ts(&entries[0]).saturating_sub(1000), true); 599+ let body = encode_lp(&entries); 600+ let mut file = Vec::new(); 601+ header.write(&mut file).unwrap(); 602+ file.extend_from_slice(&body); 603+ eprintln!("[OK] Encoded trace file: {} bytes (header {} + body {})", file.len(), TraceFileHeader::SIZE, body.len()); 605+ let mut cursor = Cursor::new(&file[..]); 606+ let read_header = TraceFileHeader::read(&mut cursor).unwrap(); 607+ assert_eq!(read_header.session_id, [0xAB; 16]); 608+ let remaining = &file[TraceFileHeader::SIZE..]; 609+ let decoded = decode_lp(remaining); 610+ assert_eq!(decoded.len(), entries.len()); 611+ assert_eq!(decoded, entries); 612+ eprintln!("[OK] Decoded {} entries, all match", decoded.len()); 616+ eprintln!("--- Test 3: Replay Max speed ---"); 617+ let engine = ReplayEngine::from_entries(entries.clone(), get_ts(&entries[0])); 618+ assert_eq!(engine.len(), entries.len()); 619+ assert_eq!(engine.turn_count(), 5); 621+ let summary = engine.run(&ReplaySpeed::Max, &ReplayMode::Normal, |_step| true); 622+ eprintln!("[OK] Max replay: {} entries in {}ms", summary.total_entries, summary.duration_ms); 623+ assert_eq!(summary.total_entries, entries.len()); 624+ assert_eq!(summary.turns, 5); 625+ assert_eq!(summary.agent_events, 6); 626+ eprintln!(" agent_events={}, tool_executions={}, turns={}, providers={}, plugins={}, snapshots={}", 627+ summary.agent_events, summary.tool_executions, summary.turns, 628+ summary.provider_requests, summary.plugins, summary.snapshots); 631+ eprintln!("--- Test 4: Factor(1000) speed ---"); 632+ let start = std::time::Instant::now(); 633+ let summary = engine.run(&ReplaySpeed::Factor(1000.0), &ReplayMode::Normal, |_step| true); 634+ let elapsed = start.elapsed(); 637+ eprintln!("[OK] Factor(1000) replay: {} entries in {}ms (wall {}ms)", 638+ summary.total_entries, summary.duration_ms, elapsed.as_millis()); 639+ assert!(elapsed.as_millis() < 500, "Factor(1000) should be fast, took {}ms", elapsed.as_millis()); 642+ eprintln!("--- Test 5: Compare mode ---"); 643+ let compare_summary = engine.run( 645+ &ReplayMode::Compare { sandbox_dir: "/tmp/sandbox".into(), continue_on_diff: true }, 648+ eprintln!("[OK] Compare: {} entries, {} diffs detected", 649+ compare_summary.total_entries, compare_summary.diffs.len()); 651+ assert!(compare_summary.diffs.len() > 0, "Compare mode should detect diffs"); 652+ for d in &compare_summary.diffs { 653+ assert_ne!(d.original_hash, d.new_hash, "Diff should have different hashes"); 654+ eprintln!(" diff: tool={} call={} orig={} new={}", d.tool_name, d.tool_call_id, d.original_hash, d.new_hash); 656+ assert_eq!(compare_summary.tool_executions, 7); 659+ eprintln!("--- Test 6: seek_to_turn ---"); 660+ let slice0 = engine.seek_to_turn(0); 661+ assert!(slice0.len() > 0, "Turn 0 should have entries"); 662+ eprintln!("[OK] seek_to_turn(0): {} entries", slice0.len()); 664+ let slice2 = engine.seek_to_turn(2); 665+ assert!(slice2.len() > 0); 666+ assert!(slice2.len() < slice0.len(), "Turn 2 should have fewer entries than turn 0"); 667+ eprintln!("[OK] seek_to_turn(2): {} entries", slice2.len()); 669+ let slice5 = engine.seek_to_turn(5); 670+ assert!(slice5.is_empty(), "seek_to_turn(5) should be empty (only 5 turns)"); 671+ eprintln!("[OK] seek_to_turn(5): empty (OOB)"); 674+ let seeked = ReplayEngine::from_entries(slice2.to_vec(), get_ts(&slice2[0])); 675+ let seeked_summary = seeked.run(&ReplaySpeed::Max, &ReplayMode::Normal, |_step| true); 676+ eprintln!("[OK] Seeked replay from turn 2: {} entries", seeked_summary.total_entries); 677+ assert!(seeked_summary.turns >= 1, "Should have at least 1 turn from seek"); 680+ eprintln!("--- Test 7: extract_session smart filter ---"); 681+ let session = engine.extract_session(); 682+ eprintln!("[OK] Session entries: {}", session.len()); 683+ assert!(session.len() > 0); 686+ let has_session = session.iter().any(|s| matches!(s, SessionEntry::Session { .. })); 687+ assert!(has_session, "Should have Session header"); 690+ let assistant_count = session.iter().filter(|s| matches!(s, SessionEntry::Assistant { .. })).count(); 691+ assert_eq!(assistant_count, 5, "Should have 5 Assistant entries (5 turns)"); 694+ let tool_count = session.iter().filter(|s| matches!(s, SessionEntry::ToolResult { .. })).count(); 695+ assert_eq!(tool_count, 7, "Should have 7 ToolResult entries"); 697+ eprintln!(" Session={}, User={}, Assistant={}, ToolResult={}, Compaction={}, Unknown={}", 698+ session.iter().filter(|s| matches!(s, SessionEntry::Session { .. })).count(), 699+ session.iter().filter(|s| matches!(s, SessionEntry::User { .. })).count(), 700+ assistant_count, tool_count, 701+ session.iter().filter(|s| matches!(s, SessionEntry::Compaction { .. })).count(), 702+ session.iter().filter(|s| matches!(s, SessionEntry::Unknown { .. })).count(), 706+ eprintln!("--- Test 8: extract_provider_trace ---"); 707+ let pairs = engine.extract_provider_trace(); 708+ eprintln!("[OK] Provider trace pairs: {}", pairs.len()); 709+ assert_eq!(pairs.len(), 5, "5 turns = 5 request/response pairs"); 710+ for (req, resp) in &pairs { 711+ assert!(resp.is_some(), "All requests should have responses"); 712+ eprintln!(" pair: req_ts={} resp_ts={}", 713+ get_ts(req), get_ts(resp.as_ref().unwrap())); 717+ eprintln!("--- Test 9: on_step abort ---"); 718+ let abort_summary = engine.run(&ReplaySpeed::Max, &ReplayMode::Normal, |step| { 721+ eprintln!("[OK] Aborted after {} entries (requested <10)", abort_summary.total_entries); 722+ assert!(abort_summary.total_entries <= 11); 725+ eprintln!("--- Test 10: Summary completeness ---"); 726+ let full = engine.run(&ReplaySpeed::Max, &ReplayMode::Normal, |_s| true); 727+ eprintln!(" Summary: {:?}", serde_json::to_string_pretty(&full).unwrap()); 728+ assert_eq!(full.total_entries, entries.len()); 729+ assert!(full.turns >= 5); 730+ assert!(full.tool_executions >= 7); 731+ assert!(full.provider_requests >= 10); 732+ assert!(full.plugins >= 3); 733+ assert!(full.snapshots >= 4); 736+ eprintln!("=== ALL P14 TESTS PASSED ==="); 737+ eprintln!(" ReplayEngine: 10 tests, all variants covered"); 738+ eprintln!(" Compare mode: {} diffs detected", compare_summary.diffs.len()); 739+ eprintln!(" Smart filter: {} session entries extracted", session.len()); 740+ eprintln!(" Provider pairs: {} matched", pairs.len()); prototypes/p15-hot-reload/Cargo.lock
Addednew file mode 100644+497 / −0 text lines
8+source = "registry+https://github.com/rust-lang/crates.io-index" 9+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" 14+source = "registry+https://github.com/rust-lang/crates.io-index" 15+checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" 20+source = "registry+https://github.com/rust-lang/crates.io-index" 21+checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" 30+source = "registry+https://github.com/rust-lang/crates.io-index" 31+checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" 40+source = "registry+https://github.com/rust-lang/crates.io-index" 41+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" 46+source = "registry+https://github.com/rust-lang/crates.io-index" 47+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" 57+source = "registry+https://github.com/rust-lang/crates.io-index" 58+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" 63+source = "registry+https://github.com/rust-lang/crates.io-index" 64+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" 73+source = "registry+https://github.com/rust-lang/crates.io-index" 74+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" 79+source = "registry+https://github.com/rust-lang/crates.io-index" 80+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" 85+source = "registry+https://github.com/rust-lang/crates.io-index" 86+checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" 91+source = "registry+https://github.com/rust-lang/crates.io-index" 92+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" 102+source = "registry+https://github.com/rust-lang/crates.io-index" 103+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" 110+name = "find-msvc-tools" 112+source = "registry+https://github.com/rust-lang/crates.io-index" 113+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" 118+source = "registry+https://github.com/rust-lang/crates.io-index" 119+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" 129+source = "registry+https://github.com/rust-lang/crates.io-index" 130+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" 135+source = "registry+https://github.com/rust-lang/crates.io-index" 136+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" 139+name = "linux-raw-sys" 141+source = "registry+https://github.com/rust-lang/crates.io-index" 142+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" 147+source = "registry+https://github.com/rust-lang/crates.io-index" 148+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" 156+source = "registry+https://github.com/rust-lang/crates.io-index" 157+checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42" 164+version = "210.5.12+a4f56a4" 165+source = "registry+https://github.com/rust-lang/crates.io-index" 166+checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671" 175+source = "registry+https://github.com/rust-lang/crates.io-index" 176+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" 181+source = "registry+https://github.com/rust-lang/crates.io-index" 182+checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0" 199+source = "registry+https://github.com/rust-lang/crates.io-index" 200+checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93" 212+source = "registry+https://github.com/rust-lang/crates.io-index" 213+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 219+name = "ordered-float" 221+source = "registry+https://github.com/rust-lang/crates.io-index" 222+checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" 228+name = "p15-hot-reload" 241+source = "registry+https://github.com/rust-lang/crates.io-index" 242+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" 249+name = "parking_lot_core" 251+source = "registry+https://github.com/rust-lang/crates.io-index" 252+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" 262+name = "pin-project-lite" 264+source = "registry+https://github.com/rust-lang/crates.io-index" 265+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" 270+source = "registry+https://github.com/rust-lang/crates.io-index" 271+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" 276+source = "registry+https://github.com/rust-lang/crates.io-index" 277+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" 285+source = "registry+https://github.com/rust-lang/crates.io-index" 286+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" 292+name = "redox_syscall" 294+source = "registry+https://github.com/rust-lang/crates.io-index" 295+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" 303+source = "registry+https://github.com/rust-lang/crates.io-index" 304+checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" 309+source = "registry+https://github.com/rust-lang/crates.io-index" 310+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" 322+source = "registry+https://github.com/rust-lang/crates.io-index" 323+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" 328+source = "registry+https://github.com/rust-lang/crates.io-index" 329+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 334+source = "registry+https://github.com/rust-lang/crates.io-index" 335+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" 344+source = "registry+https://github.com/rust-lang/crates.io-index" 345+checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" 354+source = "registry+https://github.com/rust-lang/crates.io-index" 355+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" 361+name = "serde_derive" 363+source = "registry+https://github.com/rust-lang/crates.io-index" 364+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" 374+source = "registry+https://github.com/rust-lang/crates.io-index" 375+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" 387+source = "registry+https://github.com/rust-lang/crates.io-index" 388+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" 393+source = "registry+https://github.com/rust-lang/crates.io-index" 394+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" 399+source = "registry+https://github.com/rust-lang/crates.io-index" 400+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" 410+source = "registry+https://github.com/rust-lang/crates.io-index" 411+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" 418+name = "tokio-macros" 420+source = "registry+https://github.com/rust-lang/crates.io-index" 421+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" 431+source = "registry+https://github.com/rust-lang/crates.io-index" 432+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" 435+name = "unicode-ident" 437+source = "registry+https://github.com/rust-lang/crates.io-index" 438+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" 443+source = "registry+https://github.com/rust-lang/crates.io-index" 444+checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762" 453+name = "windows-link" 455+source = "registry+https://github.com/rust-lang/crates.io-index" 456+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" 461+source = "registry+https://github.com/rust-lang/crates.io-index" 462+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" 470+source = "registry+https://github.com/rust-lang/crates.io-index" 471+checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" 476+source = "registry+https://github.com/rust-lang/crates.io-index" 477+checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" 483+name = "zerocopy-derive" 485+source = "registry+https://github.com/rust-lang/crates.io-index" 486+checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" 496+source = "registry+https://github.com/rust-lang/crates.io-index" 497+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" prototypes/p15-hot-reload/Cargo.toml
Addednew file mode 100644+11 / −0 text lines
2+name = "p15-hot-reload" 7+mlua = { version = "0.10", features = ["vendored", "serialize", "lua54"] } 9+serde = { version = "1", features = ["derive"] } 11+tokio = { version = "1", features = ["rt", "macros"] } prototypes/p15-hot-reload/src/main.rs
Addednew file mode 100644+414 / −0 text lines
15+#![allow(missing_docs, unused_variables, dead_code)] 17+use std::collections::HashMap; 19+use serde::{Deserialize, Serialize}; 23+#[derive(Clone, Debug, Serialize, Deserialize)] 24+pub struct PluginTraceEvent { 25+ pub timestamp_ns: u64, 40+struct PluginInstance { 42+ hooks: HashMap<String, HookEntry>, 47+#[derive(Clone, Debug)] 50+ turns_completed: u32, 56+struct PluginHarness { 57+ current: Option<PluginInstance>, 58+ session: SessionState, 59+ trace: Vec<PluginTraceEvent>, 64+ fn new(workspace: &str) -> Self { 67+ session: SessionState { 70+ last_model: "MiniMax-M2.7".into(), 71+ workspace: workspace.into(), 78+ fn now_ns(&mut self) -> u64 { 79+ self.ts_counter += 1; 83+ fn trace_event(&mut self, kind: &str, plugin: &str, detail: &str, success: bool) { 84+ self.trace.push(PluginTraceEvent { 85+ timestamp_ns: self.ts_counter, 87+ plugin: plugin.into(), 88+ detail: detail.into(), 94+ fn load_plugin(&mut self, name: &str, lua_code: &str) -> Result<(), String> { 95+ let lua = Lua::new(); 98+ if let Err(e) = lua.load(lua_code).exec() { 99+ let ts = self.now_ns(); 100+ self.trace_event("PluginError", name, &format!("syntax error: {}", e), false); 101+ return Err(format!("Lua exec error: {}", e)); 105+ let required_hooks = ["tool_call_transform", "context_transform"]; 106+ let mut hooks = HashMap::new(); 107+ for hook in &required_hooks { 108+ let check: mlua::Result<bool> = lua.load(&format!( 109+ "return type({}) == 'function'", hook 113+ hooks.insert(hook.to_string(), HookEntry { 114+ name: hook.to_string(), 115+ lua_fn_name: hook.to_string(), 116+ version: name.to_string(), 120+ let ts = self.now_ns(); 121+ self.trace_event("PluginError", name, &format!("missing hook: {}", hook), false); 122+ return Err(format!("Missing hook: {}", hook)); 125+ let ts = self.now_ns(); 126+ self.trace_event("PluginError", name, &format!("validation error: {}", e), false); 127+ return Err(format!("Hook check error: {}", e)); 133+ let ts = self.now_ns(); 134+ self.trace_event("PluginLoaded", name, &format!("hooks={}", hooks.len()), true); 136+ let instance = PluginInstance { 139+ version: name.to_string(), 141+ self.current = Some(instance); 144+ let ts = self.now_ns(); 145+ self.trace_event("PluginEvent", name, "activated", true); 151+ fn hot_reload(&mut self, name: &str, lua_code: &str) -> Result<(), String> { 153+ let old = self.current.take(); 154+ let old_version = old.as_ref().map(|o| o.version.clone()).unwrap_or_default(); 156+ match self.load_plugin(name, lua_code) { 158+ let ts = self.now_ns(); 159+ self.trace_event("PluginEvent", name, &format!("replaced {}", old_version), true); 165+ let ts = self.now_ns(); 166+ self.trace_event("PluginEvent", name, &format!("rollback to {}", old_version), false); 173+ fn call_tool_hook(&mut self, tool_name: &str, args: &str) -> Result<String, String> { 174+ match &self.current { 176+ let lua = &inst.lua; 177+ let result: String = lua.load(&format!( 178+ "return tool_call_transform('{}', '{}')", 180+ )).eval().map_err(|e| format!("hook error: {}", e))?; 183+ None => Err("no plugin loaded".into()), 188+ fn call_context_hook(&mut self, context: &str) -> Result<String, String> { 189+ match &self.current { 191+ let result: String = inst.lua.load(&format!( 192+ "return context_transform('{}')", context 193+ )).eval().map_err(|e| format!("hook error: {}", e))?; 196+ None => Err("no plugin loaded".into()), 201+ fn simulate_turn(&mut self, user_msg: &str) { 202+ self.session.message_count += 1; 203+ self.session.last_model = "MiniMax-M2.7".into(); 206+ let tool_result = self.call_tool_hook("bash", user_msg).unwrap_or_else(|e| format!("[hook error: {}]", e)); 207+ let context_result = self.call_context_hook("default").unwrap_or_else(|e| format!("[hook error: {}]", e)); 209+ self.session.turns_completed += 1; 213+ fn current_version(&self) -> &str { 214+ self.current.as_ref().map(|c| c.version.as_str()).unwrap_or("none") 220+fn plugin_v1() -> &'static str { 222+ function tool_call_transform(tool_name, args) 223+ return "[v1] " .. args 226+ function context_transform(ctx) 227+ return "[v1] ctx=" .. ctx 232+fn plugin_v2() -> &'static str { 234+ function tool_call_transform(tool_name, args) 235+ return "[v2] " .. args .. " (enhanced)" 238+ function context_transform(ctx) 239+ return "[v2] ctx=" .. ctx .. " (enhanced)" 244+fn plugin_v3_bad_syntax() -> &'static str { 246+ function tool_call_transform(tool_name, args) 247+ return "[v3] " .. args 248+ -- MISSING CLOSING: syntax error 252+fn plugin_v4_missing_hook() -> &'static str { 254+ function tool_call_transform(tool_name, args) 255+ return "[v4] " .. args 257+ -- context_transform is MISSING 261+fn plugin_v5() -> &'static str { 263+ function tool_call_transform(tool_name, args) 264+ return "[v5] processed: " .. args 267+ function context_transform(ctx) 268+ return "[v5] context: " .. ctx 276+ eprintln!("=== P15: Hot Reload ==="); 280+ eprintln!("--- Test 1: Load v1 plugin ---"); 281+ let mut harness = PluginHarness::new("/tmp/smith"); 282+ harness.load_plugin("v1", plugin_v1()).expect("v1 load"); 283+ assert_eq!(harness.current_version(), "v1"); 284+ eprintln!("[OK] v1 loaded, version={}", harness.current_version()); 287+ eprintln!("--- Test 2: Agent loop with v1 ---"); 288+ let r1 = harness.call_tool_hook("bash", "ls -la").expect("v1 hook"); 289+ assert!(r1.starts_with("[v1]"), "v1 hook should prepend [v1], got: {}", r1); 290+ eprintln!("[OK] v1 tool_hook: {}", r1); 292+ let c1 = harness.call_context_hook("default").expect("v1 ctx"); 293+ assert!(c1.contains("[v1]"), "v1 context should contain [v1]"); 294+ eprintln!("[OK] v1 context_hook: {}", c1); 296+ harness.simulate_turn("hello"); 297+ assert_eq!(harness.session.turns_completed, 1); 298+ eprintln!("[OK] turn 1 complete, session.turns={}", harness.session.turns_completed); 301+ eprintln!("--- Test 3: Hot reload to v2 ---"); 302+ harness.hot_reload("v2", plugin_v2()).expect("v2 reload"); 303+ assert_eq!(harness.current_version(), "v2"); 304+ eprintln!("[OK] v2 loaded, version={}", harness.current_version()); 307+ eprintln!("--- Test 4: Validate v2 hooks ---"); 308+ let r2 = harness.call_tool_hook("bash", "cargo test").expect("v2 hook"); 309+ assert!(r2.starts_with("[v2]"), "v2 hook should prepend [v2], got: {}", r2); 310+ assert!(r2.contains("(enhanced)"), "v2 should contain (enhanced)"); 311+ eprintln!("[OK] v2 tool_hook: {}", r2); 313+ let c2 = harness.call_context_hook("user").expect("v2 ctx"); 314+ assert!(c2.contains("[v2]") && c2.contains("(enhanced)")); 315+ eprintln!("[OK] v2 context_hook: {}", c2); 318+ eprintln!("--- Test 5: Session preserved ---"); 319+ harness.simulate_turn("world"); 320+ assert_eq!(harness.session.turns_completed, 2); 321+ assert_eq!(harness.session.message_count, 2); 322+ assert_eq!(harness.session.workspace, "/tmp/smith"); 323+ eprintln!("[OK] session preserved: turns={}, msgs={}, workspace={}", 324+ harness.session.turns_completed, harness.session.message_count, harness.session.workspace); 327+ eprintln!("--- Test 6: Agent loop continues with v2 ---"); 328+ let r2b = harness.call_tool_hook("grep", "TODO").expect("v2 hook again"); 329+ assert!(r2b.starts_with("[v2]"), "Should still be v2"); 330+ eprintln!("[OK] Still v2 after turn: {}", r2b); 333+ eprintln!("--- Test 7: Rollback on bad syntax ---"); 334+ let result = harness.hot_reload("v3", plugin_v3_bad_syntax()); 335+ assert!(result.is_err(), "v3 should fail to load"); 336+ assert_eq!(harness.current_version(), "v2", "Should rollback to v2"); 337+ eprintln!("[OK] v3 rejected, rolled back to {}", harness.current_version()); 340+ let r_after = harness.call_tool_hook("bash", "test").expect("v2 after rollback"); 341+ assert!(r_after.starts_with("[v2]"), "v2 should work after rollback"); 342+ eprintln!("[OK] v2 hooks work after rollback: {}", r_after); 345+ eprintln!("--- Test 8: Rollback on missing hook ---"); 346+ let result = harness.hot_reload("v4", plugin_v4_missing_hook()); 347+ assert!(result.is_err(), "v4 should fail (missing context_transform)"); 348+ assert_eq!(harness.current_version(), "v2", "Should still be v2"); 349+ eprintln!("[OK] v4 rejected (missing hook), rolled back to {}", harness.current_version()); 352+ eprintln!("--- Test 9: Trace events ---"); 353+ let trace = &harness.trace; 354+ eprintln!("[OK] {} trace events recorded", trace.len()); 356+ let loaded_count = trace.iter().filter(|e| e.kind == "PluginLoaded" && e.success).count(); 357+ let error_count = trace.iter().filter(|e| e.kind == "PluginError").count(); 358+ let event_count = trace.iter().filter(|e| e.kind == "PluginEvent").count(); 360+ eprintln!(" PluginLoaded: {}", loaded_count); 361+ eprintln!(" PluginError: {}", error_count); 362+ eprintln!(" PluginEvent: {}", event_count); 365+ assert!(loaded_count >= 2, "Should have >=2 PluginLoaded events, got {}", loaded_count); 367+ assert!(error_count >= 2, "Should have >=2 PluginError events, got {}", error_count); 370+ for e in trace.iter().filter(|e| e.kind == "PluginError") { 371+ eprintln!(" error: plugin={} detail={}", e.plugin, e.detail); 372+ assert!(!e.success); 376+ let rollback_events: Vec<_> = trace.iter() 377+ .filter(|e| e.kind == "PluginEvent" && e.detail.contains("rollback")) 379+ assert_eq!(rollback_events.len(), 2, "Should have 2 rollback events (v3 + v4)"); 380+ eprintln!("[OK] 2 rollback events confirmed"); 383+ eprintln!("--- Test 10: 10 consecutive reloads ---"); 384+ let initial_turns = harness.session.turns_completed; 385+ let trace_before = trace.len(); 388+ let code = if i % 2 == 0 { plugin_v2() } else { plugin_v5() }; 389+ let name = if i % 2 == 0 { "v2" } else { "v5" }; 390+ harness.hot_reload(name, code).expect(&format!("reload {}", i)); 391+ harness.simulate_turn(&format!("msg-{}", i)); 394+ assert_eq!(harness.session.turns_completed, initial_turns + 10); 395+ eprintln!("[OK] 10 reloads completed, turns: {} → {}", 396+ initial_turns, harness.session.turns_completed); 399+ assert_eq!(harness.current_version(), "v5"); 400+ let r5 = harness.call_tool_hook("bash", "final").expect("v5 hook"); 401+ assert!(r5.starts_with("[v5]"), "Should be v5, got: {}", r5); 402+ eprintln!("[OK] Final version: {} ({})", harness.current_version(), r5); 405+ let trace_after = harness.trace.len(); 406+ assert!(trace_after > trace_before, "Trace should grow with reloads"); 407+ eprintln!("[OK] Trace grew: {} → {} events", trace_before, trace_after); 410+ eprintln!("=== ALL P15 TESTS PASSED ==="); 411+ eprintln!(" Hot reload: v1→v2→rollback(v3)→rollback(v4)→10 cycles"); 412+ eprintln!(" Session preserved across all reloads"); 413+ eprintln!(" Trace: {} events recorded", harness.trace.len());