repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

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)

+2119 / −0 text lines

Diff layout

prototypes/p14-replay-engine/Cargo.lock

Added
new file mode 100644

+443 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "block-buffer"
7version = "0.10.4"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
10dependencies = [
11 "generic-array",
12]
14[[package]]
15name = "cc"
16version = "1.2.62"
17source = "registry+https://github.com/rust-lang/crates.io-index"
18checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"
19dependencies = [
20 "find-msvc-tools",
21 "jobserver",
22 "libc",
23 "shlex",
24]
26[[package]]
27name = "cfg-if"
28version = "1.0.4"
29source = "registry+https://github.com/rust-lang/crates.io-index"
30checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
32[[package]]
33name = "ciborium"
34version = "0.2.2"
35source = "registry+https://github.com/rust-lang/crates.io-index"
36checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
37dependencies = [
38 "ciborium-io",
39 "ciborium-ll",
40 "serde",
41]
43[[package]]
44name = "ciborium-io"
45version = "0.2.2"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
49[[package]]
50name = "ciborium-ll"
51version = "0.2.2"
52source = "registry+https://github.com/rust-lang/crates.io-index"
53checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
54dependencies = [
55 "ciborium-io",
56 "half",
57]
59[[package]]
60name = "cpufeatures"
61version = "0.2.17"
62source = "registry+https://github.com/rust-lang/crates.io-index"
63checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
64dependencies = [
65 "libc",
66]
68[[package]]
69name = "crunchy"
70version = "0.2.4"
71source = "registry+https://github.com/rust-lang/crates.io-index"
72checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
74[[package]]
75name = "crypto-common"
76version = "0.1.7"
77source = "registry+https://github.com/rust-lang/crates.io-index"
78checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
79dependencies = [
80 "generic-array",
81 "typenum",
82]
84[[package]]
85name = "digest"
86version = "0.10.7"
87source = "registry+https://github.com/rust-lang/crates.io-index"
88checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
89dependencies = [
90 "block-buffer",
91 "crypto-common",
92]
94[[package]]
95name = "find-msvc-tools"
96version = "0.1.9"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
100[[package]]
101name = "generic-array"
102version = "0.14.7"
103source = "registry+https://github.com/rust-lang/crates.io-index"
104checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
105dependencies = [
106 "typenum",
107 "version_check",
108]
110[[package]]
111name = "getrandom"
112version = "0.2.17"
113source = "registry+https://github.com/rust-lang/crates.io-index"
114checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
115dependencies = [
116 "cfg-if",
117 "libc",
118 "wasi",
119]
121[[package]]
122name = "getrandom"
123version = "0.3.4"
124source = "registry+https://github.com/rust-lang/crates.io-index"
125checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
126dependencies = [
127 "cfg-if",
128 "libc",
129 "r-efi",
130 "wasip2",
131]
133[[package]]
134name = "half"
135version = "2.7.1"
136source = "registry+https://github.com/rust-lang/crates.io-index"
137checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
138dependencies = [
139 "cfg-if",
140 "crunchy",
141 "zerocopy",
142]
144[[package]]
145name = "itoa"
146version = "1.0.18"
147source = "registry+https://github.com/rust-lang/crates.io-index"
148checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
150[[package]]
151name = "jobserver"
152version = "0.1.34"
153source = "registry+https://github.com/rust-lang/crates.io-index"
154checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
155dependencies = [
156 "getrandom 0.3.4",
157 "libc",
158]
160[[package]]
161name = "libc"
162version = "0.2.186"
163source = "registry+https://github.com/rust-lang/crates.io-index"
164checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
166[[package]]
167name = "memchr"
168version = "2.8.0"
169source = "registry+https://github.com/rust-lang/crates.io-index"
170checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
172[[package]]
173name = "p14-replay-engine"
174version = "0.1.0"
175dependencies = [
176 "ciborium",
177 "rand",
178 "serde",
179 "serde_json",
180 "sha2",
181 "tokio",
182 "zstd",
183]
185[[package]]
186name = "pin-project-lite"
187version = "0.2.17"
188source = "registry+https://github.com/rust-lang/crates.io-index"
189checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
191[[package]]
192name = "pkg-config"
193version = "0.3.33"
194source = "registry+https://github.com/rust-lang/crates.io-index"
195checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
197[[package]]
198name = "ppv-lite86"
199version = "0.2.21"
200source = "registry+https://github.com/rust-lang/crates.io-index"
201checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
202dependencies = [
203 "zerocopy",
204]
206[[package]]
207name = "proc-macro2"
208version = "1.0.106"
209source = "registry+https://github.com/rust-lang/crates.io-index"
210checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
211dependencies = [
212 "unicode-ident",
213]
215[[package]]
216name = "quote"
217version = "1.0.45"
218source = "registry+https://github.com/rust-lang/crates.io-index"
219checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
220dependencies = [
221 "proc-macro2",
222]
224[[package]]
225name = "r-efi"
226version = "5.3.0"
227source = "registry+https://github.com/rust-lang/crates.io-index"
228checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
230[[package]]
231name = "rand"
232version = "0.8.6"
233source = "registry+https://github.com/rust-lang/crates.io-index"
234checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
235dependencies = [
236 "libc",
237 "rand_chacha",
238 "rand_core",
239]
241[[package]]
242name = "rand_chacha"
243version = "0.3.1"
244source = "registry+https://github.com/rust-lang/crates.io-index"
245checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
246dependencies = [
247 "ppv-lite86",
248 "rand_core",
249]
251[[package]]
252name = "rand_core"
253version = "0.6.4"
254source = "registry+https://github.com/rust-lang/crates.io-index"
255checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
256dependencies = [
257 "getrandom 0.2.17",
258]
260[[package]]
261name = "serde"
262version = "1.0.228"
263source = "registry+https://github.com/rust-lang/crates.io-index"
264checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
265dependencies = [
266 "serde_core",
267 "serde_derive",
268]
270[[package]]
271name = "serde_core"
272version = "1.0.228"
273source = "registry+https://github.com/rust-lang/crates.io-index"
274checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
275dependencies = [
276 "serde_derive",
277]
279[[package]]
280name = "serde_derive"
281version = "1.0.228"
282source = "registry+https://github.com/rust-lang/crates.io-index"
283checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
284dependencies = [
285 "proc-macro2",
286 "quote",
287 "syn",
288]
290[[package]]
291name = "serde_json"
292version = "1.0.150"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
295dependencies = [
296 "itoa",
297 "memchr",
298 "serde",
299 "serde_core",
300 "zmij",
301]
303[[package]]
304name = "sha2"
305version = "0.10.9"
306source = "registry+https://github.com/rust-lang/crates.io-index"
307checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
308dependencies = [
309 "cfg-if",
310 "cpufeatures",
311 "digest",
312]
314[[package]]
315name = "shlex"
316version = "1.3.0"
317source = "registry+https://github.com/rust-lang/crates.io-index"
318checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
320[[package]]
321name = "syn"
322version = "2.0.117"
323source = "registry+https://github.com/rust-lang/crates.io-index"
324checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
325dependencies = [
326 "proc-macro2",
327 "quote",
328 "unicode-ident",
329]
331[[package]]
332name = "tokio"
333version = "1.52.3"
334source = "registry+https://github.com/rust-lang/crates.io-index"
335checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
336dependencies = [
337 "pin-project-lite",
338 "tokio-macros",
339]
341[[package]]
342name = "tokio-macros"
343version = "2.7.0"
344source = "registry+https://github.com/rust-lang/crates.io-index"
345checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
346dependencies = [
347 "proc-macro2",
348 "quote",
349 "syn",
350]
352[[package]]
353name = "typenum"
354version = "1.20.0"
355source = "registry+https://github.com/rust-lang/crates.io-index"
356checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
358[[package]]
359name = "unicode-ident"
360version = "1.0.24"
361source = "registry+https://github.com/rust-lang/crates.io-index"
362checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
364[[package]]
365name = "version_check"
366version = "0.9.5"
367source = "registry+https://github.com/rust-lang/crates.io-index"
368checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
370[[package]]
371name = "wasi"
372version = "0.11.1+wasi-snapshot-preview1"
373source = "registry+https://github.com/rust-lang/crates.io-index"
374checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
376[[package]]
377name = "wasip2"
378version = "1.0.3+wasi-0.2.9"
379source = "registry+https://github.com/rust-lang/crates.io-index"
380checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
381dependencies = [
382 "wit-bindgen",
383]
385[[package]]
386name = "wit-bindgen"
387version = "0.57.1"
388source = "registry+https://github.com/rust-lang/crates.io-index"
389checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
391[[package]]
392name = "zerocopy"
393version = "0.8.48"
394source = "registry+https://github.com/rust-lang/crates.io-index"
395checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
396dependencies = [
397 "zerocopy-derive",
398]
400[[package]]
401name = "zerocopy-derive"
402version = "0.8.48"
403source = "registry+https://github.com/rust-lang/crates.io-index"
404checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
405dependencies = [
406 "proc-macro2",
407 "quote",
408 "syn",
409]
411[[package]]
412name = "zmij"
413version = "1.0.21"
414source = "registry+https://github.com/rust-lang/crates.io-index"
415checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
417[[package]]
418name = "zstd"
419version = "0.13.3"
420source = "registry+https://github.com/rust-lang/crates.io-index"
421checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
422dependencies = [
423 "zstd-safe",
424]
426[[package]]
427name = "zstd-safe"
428version = "7.2.4"
429source = "registry+https://github.com/rust-lang/crates.io-index"
430checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
431dependencies = [
432 "zstd-sys",
433]
435[[package]]
436name = "zstd-sys"
437version = "2.0.16+zstd.1.5.7"
438source = "registry+https://github.com/rust-lang/crates.io-index"
439checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
440dependencies = [
441 "cc",
442 "pkg-config",
443]

prototypes/p14-replay-engine/Cargo.toml

Added
new file mode 100644

+13 / −0 text lines

1[package]
2name = "p14-replay-engine"
3version = "0.1.0"
4edition = "2024"
5
6[dependencies]
7ciborium = "0.2"
8serde = { version = "1", features = ["derive"] }
9serde_json = "1"
10sha2 = "0.10"
11rand = "0.8"
12zstd = "0.13"
13tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

prototypes/p14-replay-engine/src/main.rs

Added
new file mode 100644

+741 / −0 text lines

1//! Prototype P14: Replay Engine per SM-006 §13.7.
2//!
3//! Tests:
4//! 1. Generate synthetic trace with 50+ entries (all TraceEntry variants)
5//! 2. TraceCodec: header + length-prefixed compressed CBOR-seq (reuses P11 patterns)
6//! 3. ReplaySpeed: Max / RealTime / Factor(f64) with actual tokio::time::sleep
7//! 4. ReplayMode::Normal — iterate entries, count stats
8//! 5. ReplayMode::Compare — re-execute tool calls, hash diff, record ReplayDiff
9//! 6. seek_to_turn(n) — skip to Nth turn using snapshot indices
10//! 7. extract_session() — smart filter TraceEntry → SessionEntry
11//! 8. extract_provider_trace() — request/response pairing
12//! 9. ReplaySummary stats (total_entries, duration_ms, agent_events, tool_execs, diffs)
14#![allow(missing_docs, unused_variables, unused_assignments)]
16use serde::{Deserialize, Serialize};
17use std::collections::HashMap;
18use std::io::{Cursor, Read, Write};
20// === Shared types (from P11) ===
22#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
23pub struct EntryId(pub String);
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26pub enum Role { System, User, Assistant, Tool }
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub enum StopReason { EndTurn, ToolUse, OverMaxTokens, Aborted, StopSequence, Error }
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32pub enum ContentBlock {
33 Text(String),
34 ToolCall { id: String, name: String, arguments: String },
35 ToolResult { id: String, result: String, is_error: bool },
36 Thinking { content: String },
37}
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40pub 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>,
46}
48// === SessionEntry (from P11, all variants) ===
50#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
51pub 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 },
58}
60// === Extended TraceEntry (SM-006 all replay-relevant variants) ===
62#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
63pub enum TraceEntry {
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 },
77}
79// === TraceFileHeader (from P11) ===
81#[derive(Clone, Debug)]
82pub struct TraceFileHeader {
83 pub magic: [u8; 4],
84 pub version: u16,
85 pub flags: u16,
86 pub session_id: [u8; 16],
87 pub start_timestamp_ns: u64,
88 pub reserved: [u8; 32],
89}
91impl 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] }
99 }
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)?;
108 Ok(())
109 }
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 })
121 }
122}
124// === CBOR codec (P11 patterns) ===
126fn encode_lp(entries: &[TraceEntry]) -> Vec<u8> {
127 let mut buf = Vec::new();
128 for e in entries {
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);
134 }
135 buf
136}
138fn 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..];
147 }
148 out
149}
151// === Replay types (SM-006 §13.7) ===
153#[derive(Clone, Debug)]
154pub enum ReplaySpeed {
155 Max,
156 RealTime,
157 Factor(f64),
158}
160#[derive(Clone, Debug)]
161pub enum ReplayMode {
162 Normal,
163 Compare { sandbox_dir: String, continue_on_diff: bool },
164}
166#[derive(Clone, Debug, serde::Serialize)]
167pub 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,
173}
175#[derive(Clone, Debug)]
176pub struct ReplayStep {
177 pub entry: TraceEntry,
178 pub timestamp_ns: u64,
179 pub index: usize,
180 pub diff: Option<ReplayDiff>,
181}
183#[derive(Clone, Debug, Default, serde::Serialize)]
184pub struct ReplaySummary {
185 pub total_entries: usize,
186 pub duration_ms: u64,
187 pub agent_events: usize,
188 pub tool_executions: usize,
189 pub turns: usize,
190 pub provider_requests: usize,
191 pub plugins: usize,
192 pub snapshots: usize,
193 pub diffs: Vec<ReplayDiff>,
194}
196// === ReplayEngine ===
198pub struct ReplayEngine {
199 entries: Vec<TraceEntry>,
200 start_ts: u64,
201 turn_indices: Vec<usize>, // index into entries where TurnStart occurs
202}
204impl ReplayEngine {
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 { .. }))
208 .map(|(i, _)| i)
209 .collect();
210 Self { entries, start_ts, turn_indices }
211 }
213 /// Load from raw bytes (header already stripped).
214 pub fn from_bytes(data: &[u8], start_ts: u64) -> Self {
215 let entries = decode_lp(data);
216 Self::from_entries(entries, start_ts)
217 }
219 /// Total entry count.
220 pub fn len(&self) -> usize { self.entries.len() }
222 /// Seek to Nth turn (0-indexed). Returns slice of entries starting from that turn.
223 pub fn seek_to_turn(&self, turn: usize) -> &[TraceEntry] {
224 if turn >= self.turn_indices.len() {
225 return &self.entries[self.entries.len()..]; // empty
226 }
227 &self.entries[self.turn_indices[turn]..]
228 }
230 /// Number of turns.
231 pub fn turn_count(&self) -> usize { self.turn_indices.len() }
233 /// Run replay synchronously. Returns summary.
234 /// on_step callback receives each ReplayStep. Returns false to abort.
235 pub fn run<F>(&self, speed: &ReplaySpeed, mode: &ReplayMode, mut on_step: F) -> ReplaySummary
236 where F: FnMut(&ReplayStep) -> bool
237 {
238 let mut summary = ReplaySummary::default();
239 let start = std::time::Instant::now();
240 let mut prev_ts = self.start_ts;
242 // For Compare mode: track ToolStart → ToolEnd pairs
243 let mut pending_tools: HashMap<String, (String, String)> = HashMap::new(); // call_id → (name, args)
245 for (idx, entry) in self.entries.iter().enumerate() {
246 let ts = get_ts(entry);
247 let mut diff = None;
249 // Speed delay (not for Max)
250 match speed {
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));
255 },
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));
260 },
261 }
262 prev_ts = ts;
264 // Compare mode: re-execute tools
265 if let ReplayMode::Compare { sandbox_dir, .. } = mode {
266 match entry {
267 TraceEntry::ToolStart { tool_call_id, tool_name, args_json, .. } => {
268 pending_tools.insert(tool_call_id.clone(), (tool_name.clone(), args_json.clone()));
269 },
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(),
276 tool_name: name,
277 original_hash: result_hash.clone(),
278 new_hash: new_hash.clone(),
279 text_diff: format!("original={} new={}", result_hash, &new_hash),
280 };
281 diff = Some(d.clone());
282 summary.diffs.push(d);
283 }
284 }
285 },
286 _ => {},
287 }
288 }
290 summary.total_entries += 1;
291 // Classify
292 match entry {
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 { .. } => {},
302 }
304 let step = ReplayStep { entry: entry.clone(), timestamp_ns: ts, index: idx, diff };
305 if !on_step(&step) { break; }
306 }
308 summary.duration_ms = start.elapsed().as_millis() as u64;
309 summary
310 }
312 /// Smart filter: TraceEntry → SessionEntry (SM-006 §13.6).
313 pub fn extract_session(&self) -> Vec<SessionEntry> {
314 let mut out = Vec::new();
315 let mut eid = 0u64;
316 let mut msg_count = 0u32;
318 for entry in &self.entries {
319 eid += 1;
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; // ns → ms
324 match entry {
325 TraceEntry::AgentEvent { event, .. } if event == "SessionStart" => {
326 out.push(SessionEntry::Session { version: 1, created: ts });
327 },
328 TraceEntry::TurnStart { turn_number, .. } if *turn_number == 0 => {
329 // First turn start → user message placeholder
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]"))],
333 timestamp: ts,
334 });
335 },
336 TraceEntry::ProviderResponse { request_id, completion_tokens, finish_reason, .. } => {
337 msg_count += 1;
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),
344 },
345 provider: "minimax".into(), model: "MiniMax-M2.7".into(),
346 stop_reason: if finish_reason == "stop" { StopReason::EndTurn } else { StopReason::OverMaxTokens },
347 timestamp: ts,
348 });
349 },
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,
356 }],
357 is_error: *is_error, timestamp: ts,
358 });
359 },
360 TraceEntry::Snapshot { message_count, .. } => {
361 // Compaction-like: if messages > threshold
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()],
368 timestamp: ts,
369 });
370 }
371 },
372 _ => {
373 // Unmapped entries → Unknown
374 let data = format!("{:?}", entry);
375 out.push(SessionEntry::Unknown {
376 id, data: data.into_bytes(), timestamp: ts,
377 });
378 },
379 }
380 }
381 out
382 }
384 /// Extract provider request/response pairs.
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 {
390 match entry {
391 TraceEntry::ProviderRequest { request_id, .. } => {
392 reqs.insert(request_id.clone(), entry.clone());
393 },
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() }
397 });
398 out.push((req, Some(entry.clone())));
399 },
400 _ => {},
401 }
402 }
403 // Unmatched requests
404 for (_, req) in reqs.drain() {
405 out.push((req, None));
406 }
407 out
408 }
409}
411// === Helpers ===
413fn get_ts(e: &TraceEntry) -> u64 {
414 match e {
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,
428 }
429}
431/// Simulate tool re-execution for compare mode. Deterministic hash from args.
432fn 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());
438 // Add a "re-execution" salt so some tools differ from original
439 hasher.update(b"re-exec-v2");
440 let hash = hasher.finalize();
441 format!("sha256:{:x}", hash)[..16].to_string()
442}
444/// Generate deterministic hash for original tool result.
445fn 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()
452}
454// === Synthetic trace generator ===
456fn 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;
461 // Session start
462 entries.push(TraceEntry::AgentEvent { timestamp_ns: ts, event: "SessionStart".into() }); ts += 1_000_000;
464 // Env snapshot
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())],
468 }); ts += 500_000;
470 // Plugin load
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;
474 // 5 turns, each with tools and provider calls
475 let tools = vec![
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"}"#),
483 ];
485 for turn in 0..5 {
486 // Turn start
487 entries.push(TraceEntry::TurnStart {
488 timestamp_ns: ts, turn_number: turn, model: "MiniMax-M2.7".into(), provider: "minimax".into(),
489 }); ts += 500_000;
491 // Provider request/response
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;
501 // Agent event
502 entries.push(TraceEntry::AgentEvent { timestamp_ns: ts, event: "Thinking".into() }); ts += 1_000_000;
504 // 1-2 tool calls per turn
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;
517 }
519 // File hash snapshot every other turn
520 if turn % 2 == 0 {
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)),
525 ],
526 }); ts += 500_000;
527 }
529 // Agent state snapshot
530 entries.push(TraceEntry::Snapshot {
531 timestamp_ns: ts, message_count: (turn + 1) * 3, model: "MiniMax-M2.7".into(), pending_tools: 0,
532 }); ts += 500_000;
534 // Turn end
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;
540 // Plugin event every other turn
541 if turn % 2 == 1 {
542 entries.push(TraceEntry::PluginEvent {
543 timestamp_ns: ts, plugin: "formatter".into(), event: "formatted".into(),
544 }); ts += 1_000_000;
545 }
546 }
548 // Extra plugin error
549 entries.push(TraceEntry::PluginError { timestamp_ns: ts, plugin: "linter".into(), error: "parse error".into() }); ts += 1_000_000;
551 // Final env snapshot
552 entries.push(TraceEntry::EnvSnapshot {
553 timestamp_ns: ts, cwd: "/home/user/smith".into(),
554 env_vars: vec![("HOME".into(), "/home/user".into())],
555 });
557 entries
558}
560// === Tests ===
562#[tokio::main]
563async fn main() {
564 eprintln!("=== P14: Replay Engine ===");
565 eprintln!();
567 // --- Test 1: Generate synthetic trace with 50+ entries ---
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());
573 // Count variants
574 let mut variant_counts: HashMap<&str, usize> = HashMap::new();
575 for e in &entries {
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",
590 };
591 *variant_counts.entry(name).or_insert(0) += 1;
592 }
593 eprintln!(" Variants: {:?}", variant_counts);
594 assert!(variant_counts.len() >= 10, "Should cover 10+ variants, got {}", variant_counts.len());
596 // --- Test 2: TraceCodec roundtrip ---
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());
614 // --- Test 3: ReplaySpeed::Max (instant) ---
615 eprintln!();
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); // SessionStart + 5 Thinking
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);
630 // --- Test 4: ReplaySpeed::Factor(1000) (1ms per 1s trace time) ---
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();
635 // Trace spans ~100ms of simulated time. Factor(1000) → ~0.1ms actual.
636 // Should complete in < 500ms.
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());
641 // --- Test 5: ReplayMode::Compare ---
642 eprintln!("--- Test 5: Compare mode ---");
643 let compare_summary = engine.run(
644 &ReplaySpeed::Max,
645 &ReplayMode::Compare { sandbox_dir: "/tmp/sandbox".into(), continue_on_diff: true },
646 |_step| true,
647 );
648 eprintln!("[OK] Compare: {} entries, {} diffs detected",
649 compare_summary.total_entries, compare_summary.diffs.len());
650 // All tool re-executions should produce different hashes (salted)
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);
655 }
656 assert_eq!(compare_summary.tool_executions, 7); // 5 turns, 1-2 tools each: 1+2+1+2+1=7
658 // --- Test 6: seek_to_turn ---
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); // out of bounds
670 assert!(slice5.is_empty(), "seek_to_turn(5) should be empty (only 5 turns)");
671 eprintln!("[OK] seek_to_turn(5): empty (OOB)");
673 // Seeked engine should also replay correctly
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");
679 // --- Test 7: extract_session (smart filter) ---
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);
685 // Should have Session header
686 let has_session = session.iter().any(|s| matches!(s, SessionEntry::Session { .. }));
687 assert!(has_session, "Should have Session header");
689 // Should have Assistant entries (from ProviderResponse)
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)");
693 // Should have ToolResult entries
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(),
703 );
705 // --- Test 8: extract_provider_trace ---
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()));
714 }
716 // --- Test 9: on_step abort ---
717 eprintln!("--- Test 9: on_step abort ---");
718 let abort_summary = engine.run(&ReplaySpeed::Max, &ReplayMode::Normal, |step| {
719 step.index < 10 // abort after 10 entries
720 });
721 eprintln!("[OK] Aborted after {} entries (requested <10)", abort_summary.total_entries);
722 assert!(abort_summary.total_entries <= 11);
724 // --- Test 10: ReplaySummary completeness ---
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); // 5 req + 5 resp
732 assert!(full.plugins >= 3); // 1 loaded + 1 event + 1 error
733 assert!(full.snapshots >= 4); // 1 env + 2 filehash + 1 agent + 1 final env
735 eprintln!();
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());
741}

prototypes/p15-hot-reload/Cargo.lock

Added
new file mode 100644

+497 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "autocfg"
7version = "1.5.1"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
11[[package]]
12name = "bitflags"
13version = "2.11.1"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
17[[package]]
18name = "bstr"
19version = "1.12.1"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab"
22dependencies = [
23 "memchr",
24 "serde",
25]
27[[package]]
28name = "cc"
29version = "1.2.62"
30source = "registry+https://github.com/rust-lang/crates.io-index"
31checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"
32dependencies = [
33 "find-msvc-tools",
34 "shlex",
35]
37[[package]]
38name = "cfg-if"
39version = "1.0.4"
40source = "registry+https://github.com/rust-lang/crates.io-index"
41checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
43[[package]]
44name = "ciborium"
45version = "0.2.2"
46source = "registry+https://github.com/rust-lang/crates.io-index"
47checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
48dependencies = [
49 "ciborium-io",
50 "ciborium-ll",
51 "serde",
52]
54[[package]]
55name = "ciborium-io"
56version = "0.2.2"
57source = "registry+https://github.com/rust-lang/crates.io-index"
58checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
60[[package]]
61name = "ciborium-ll"
62version = "0.2.2"
63source = "registry+https://github.com/rust-lang/crates.io-index"
64checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
65dependencies = [
66 "ciborium-io",
67 "half",
68]
70[[package]]
71name = "crunchy"
72version = "0.2.4"
73source = "registry+https://github.com/rust-lang/crates.io-index"
74checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
76[[package]]
77name = "either"
78version = "1.16.0"
79source = "registry+https://github.com/rust-lang/crates.io-index"
80checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
82[[package]]
83name = "env_home"
84version = "0.1.0"
85source = "registry+https://github.com/rust-lang/crates.io-index"
86checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
88[[package]]
89name = "erased-serde"
90version = "0.4.10"
91source = "registry+https://github.com/rust-lang/crates.io-index"
92checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
93dependencies = [
94 "serde",
95 "serde_core",
96 "typeid",
97]
99[[package]]
100name = "errno"
101version = "0.3.14"
102source = "registry+https://github.com/rust-lang/crates.io-index"
103checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
104dependencies = [
105 "libc",
106 "windows-sys",
107]
109[[package]]
110name = "find-msvc-tools"
111version = "0.1.9"
112source = "registry+https://github.com/rust-lang/crates.io-index"
113checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
115[[package]]
116name = "half"
117version = "2.7.1"
118source = "registry+https://github.com/rust-lang/crates.io-index"
119checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
120dependencies = [
121 "cfg-if",
122 "crunchy",
123 "zerocopy",
124]
126[[package]]
127name = "itoa"
128version = "1.0.18"
129source = "registry+https://github.com/rust-lang/crates.io-index"
130checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
132[[package]]
133name = "libc"
134version = "0.2.186"
135source = "registry+https://github.com/rust-lang/crates.io-index"
136checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
138[[package]]
139name = "linux-raw-sys"
140version = "0.12.1"
141source = "registry+https://github.com/rust-lang/crates.io-index"
142checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
144[[package]]
145name = "lock_api"
146version = "0.4.14"
147source = "registry+https://github.com/rust-lang/crates.io-index"
148checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
149dependencies = [
150 "scopeguard",
151]
153[[package]]
154name = "lua-src"
155version = "547.0.0"
156source = "registry+https://github.com/rust-lang/crates.io-index"
157checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
158dependencies = [
159 "cc",
160]
162[[package]]
163name = "luajit-src"
164version = "210.5.12+a4f56a4"
165source = "registry+https://github.com/rust-lang/crates.io-index"
166checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
167dependencies = [
168 "cc",
169 "which",
170]
172[[package]]
173name = "memchr"
174version = "2.8.0"
175source = "registry+https://github.com/rust-lang/crates.io-index"
176checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
178[[package]]
179name = "mlua"
180version = "0.10.5"
181source = "registry+https://github.com/rust-lang/crates.io-index"
182checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
183dependencies = [
184 "bstr",
185 "either",
186 "erased-serde",
187 "mlua-sys",
188 "num-traits",
189 "parking_lot",
190 "rustc-hash",
191 "rustversion",
192 "serde",
193 "serde-value",
194]
196[[package]]
197name = "mlua-sys"
198version = "0.6.8"
199source = "registry+https://github.com/rust-lang/crates.io-index"
200checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
201dependencies = [
202 "cc",
203 "cfg-if",
204 "lua-src",
205 "luajit-src",
206 "pkg-config",
207]
209[[package]]
210name = "num-traits"
211version = "0.2.19"
212source = "registry+https://github.com/rust-lang/crates.io-index"
213checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
214dependencies = [
215 "autocfg",
216]
218[[package]]
219name = "ordered-float"
220version = "2.10.1"
221source = "registry+https://github.com/rust-lang/crates.io-index"
222checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
223dependencies = [
224 "num-traits",
225]
227[[package]]
228name = "p15-hot-reload"
229version = "0.1.0"
230dependencies = [
231 "ciborium",
232 "mlua",
233 "serde",
234 "serde_json",
235 "tokio",
236]
238[[package]]
239name = "parking_lot"
240version = "0.12.5"
241source = "registry+https://github.com/rust-lang/crates.io-index"
242checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
243dependencies = [
244 "lock_api",
245 "parking_lot_core",
246]
248[[package]]
249name = "parking_lot_core"
250version = "0.9.12"
251source = "registry+https://github.com/rust-lang/crates.io-index"
252checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
253dependencies = [
254 "cfg-if",
255 "libc",
256 "redox_syscall",
257 "smallvec",
258 "windows-link",
259]
261[[package]]
262name = "pin-project-lite"
263version = "0.2.17"
264source = "registry+https://github.com/rust-lang/crates.io-index"
265checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
267[[package]]
268name = "pkg-config"
269version = "0.3.33"
270source = "registry+https://github.com/rust-lang/crates.io-index"
271checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
273[[package]]
274name = "proc-macro2"
275version = "1.0.106"
276source = "registry+https://github.com/rust-lang/crates.io-index"
277checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
278dependencies = [
279 "unicode-ident",
280]
282[[package]]
283name = "quote"
284version = "1.0.45"
285source = "registry+https://github.com/rust-lang/crates.io-index"
286checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
287dependencies = [
288 "proc-macro2",
289]
291[[package]]
292name = "redox_syscall"
293version = "0.5.18"
294source = "registry+https://github.com/rust-lang/crates.io-index"
295checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
296dependencies = [
297 "bitflags",
298]
300[[package]]
301name = "rustc-hash"
302version = "2.1.2"
303source = "registry+https://github.com/rust-lang/crates.io-index"
304checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
306[[package]]
307name = "rustix"
308version = "1.1.4"
309source = "registry+https://github.com/rust-lang/crates.io-index"
310checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
311dependencies = [
312 "bitflags",
313 "errno",
314 "libc",
315 "linux-raw-sys",
316 "windows-sys",
317]
319[[package]]
320name = "rustversion"
321version = "1.0.22"
322source = "registry+https://github.com/rust-lang/crates.io-index"
323checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
325[[package]]
326name = "scopeguard"
327version = "1.2.0"
328source = "registry+https://github.com/rust-lang/crates.io-index"
329checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
331[[package]]
332name = "serde"
333version = "1.0.228"
334source = "registry+https://github.com/rust-lang/crates.io-index"
335checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
336dependencies = [
337 "serde_core",
338 "serde_derive",
339]
341[[package]]
342name = "serde-value"
343version = "0.7.0"
344source = "registry+https://github.com/rust-lang/crates.io-index"
345checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
346dependencies = [
347 "ordered-float",
348 "serde",
349]
351[[package]]
352name = "serde_core"
353version = "1.0.228"
354source = "registry+https://github.com/rust-lang/crates.io-index"
355checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
356dependencies = [
357 "serde_derive",
358]
360[[package]]
361name = "serde_derive"
362version = "1.0.228"
363source = "registry+https://github.com/rust-lang/crates.io-index"
364checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
365dependencies = [
366 "proc-macro2",
367 "quote",
368 "syn",
369]
371[[package]]
372name = "serde_json"
373version = "1.0.150"
374source = "registry+https://github.com/rust-lang/crates.io-index"
375checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
376dependencies = [
377 "itoa",
378 "memchr",
379 "serde",
380 "serde_core",
381 "zmij",
382]
384[[package]]
385name = "shlex"
386version = "1.3.0"
387source = "registry+https://github.com/rust-lang/crates.io-index"
388checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
390[[package]]
391name = "smallvec"
392version = "1.15.1"
393source = "registry+https://github.com/rust-lang/crates.io-index"
394checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
396[[package]]
397name = "syn"
398version = "2.0.117"
399source = "registry+https://github.com/rust-lang/crates.io-index"
400checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
401dependencies = [
402 "proc-macro2",
403 "quote",
404 "unicode-ident",
405]
407[[package]]
408name = "tokio"
409version = "1.52.3"
410source = "registry+https://github.com/rust-lang/crates.io-index"
411checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
412dependencies = [
413 "pin-project-lite",
414 "tokio-macros",
415]
417[[package]]
418name = "tokio-macros"
419version = "2.7.0"
420source = "registry+https://github.com/rust-lang/crates.io-index"
421checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
422dependencies = [
423 "proc-macro2",
424 "quote",
425 "syn",
426]
428[[package]]
429name = "typeid"
430version = "1.0.3"
431source = "registry+https://github.com/rust-lang/crates.io-index"
432checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
434[[package]]
435name = "unicode-ident"
436version = "1.0.24"
437source = "registry+https://github.com/rust-lang/crates.io-index"
438checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
440[[package]]
441name = "which"
442version = "7.0.3"
443source = "registry+https://github.com/rust-lang/crates.io-index"
444checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
445dependencies = [
446 "either",
447 "env_home",
448 "rustix",
449 "winsafe",
450]
452[[package]]
453name = "windows-link"
454version = "0.2.1"
455source = "registry+https://github.com/rust-lang/crates.io-index"
456checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
458[[package]]
459name = "windows-sys"
460version = "0.61.2"
461source = "registry+https://github.com/rust-lang/crates.io-index"
462checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
463dependencies = [
464 "windows-link",
465]
467[[package]]
468name = "winsafe"
469version = "0.0.19"
470source = "registry+https://github.com/rust-lang/crates.io-index"
471checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
473[[package]]
474name = "zerocopy"
475version = "0.8.48"
476source = "registry+https://github.com/rust-lang/crates.io-index"
477checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
478dependencies = [
479 "zerocopy-derive",
480]
482[[package]]
483name = "zerocopy-derive"
484version = "0.8.48"
485source = "registry+https://github.com/rust-lang/crates.io-index"
486checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
487dependencies = [
488 "proc-macro2",
489 "quote",
490 "syn",
491]
493[[package]]
494name = "zmij"
495version = "1.0.21"
496source = "registry+https://github.com/rust-lang/crates.io-index"
497checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"

prototypes/p15-hot-reload/Cargo.toml

Added
new file mode 100644

+11 / −0 text lines

1[package]
2name = "p15-hot-reload"
3version = "0.1.0"
4edition = "2024"
5
6[dependencies]
7mlua = { version = "0.10", features = ["vendored", "serialize", "lua54"] }
8ciborium = "0.2"
9serde = { version = "1", features = ["derive"] }
10serde_json = "1"
11tokio = { version = "1", features = ["rt", "macros"] }

prototypes/p15-hot-reload/src/main.rs

Added
new file mode 100644

+414 / −0 text lines

1//! Prototype P15: Hot Reload per SM-009 Plugin System.
2//!
3//! Tests:
4//! 1. Load Lua plugin v1 — registers tool_call_transform hook → "[v1] result"
5//! 2. Simulated agent loop calls hooks, gets correct v1 behavior
6//! 3. Hot reload: load v2 Lua plugin — registers new hook → "[v2] result"
7//! 4. Validate v2: check hook signature correctness
8//! 5. Atomic hook swap: old hooks replaced, session preserved
9//! 6. Agent loop continues with v2 behavior
10//! 7. Rollback: load v3 (bad Lua syntax) → validation fails → old hooks restored
11//! 8. Rollback: load v4 (missing hook) → validation fails → old hooks restored
12//! 9. Trace recording: PluginLoaded, PluginEvent, PluginError events captured
13//! 10. Multiple reloads: 10 consecutive hot-swaps, session state preserved
15#![allow(missing_docs, unused_variables, dead_code)]
17use std::collections::HashMap;
18use mlua::Lua;
19use serde::{Deserialize, Serialize};
21// === Types ===
23#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct PluginTraceEvent {
25 pub timestamp_ns: u64,
26 pub kind: String, // "PluginLoaded", "PluginEvent", "PluginError"
27 pub plugin: String,
28 pub detail: String,
29 pub success: bool,
30}
32/// Represents a plugin's registered hook (stored as Lua closure reference).
33struct HookEntry {
34 name: String,
35 lua_fn_name: String,
36 version: String,
37}
39/// Plugin state — holds Lua instance + registered hooks.
40struct PluginInstance {
41 lua: Lua,
42 hooks: HashMap<String, HookEntry>,
43 version: String,
44}
46/// Session state that persists across reloads.
47#[derive(Clone, Debug)]
48struct SessionState {
49 message_count: u32,
50 turns_completed: u32,
51 last_model: String,
52 workspace: String,
53}
55/// The harness — manages plugin lifecycle + session.
56struct PluginHarness {
57 current: Option<PluginInstance>,
58 session: SessionState,
59 trace: Vec<PluginTraceEvent>,
60 ts_counter: u64,
61}
63impl PluginHarness {
64 fn new(workspace: &str) -> Self {
65 Self {
66 current: None,
67 session: SessionState {
68 message_count: 0,
69 turns_completed: 0,
70 last_model: "MiniMax-M2.7".into(),
71 workspace: workspace.into(),
72 },
73 trace: Vec::new(),
74 ts_counter: 1000,
75 }
76 }
78 fn now_ns(&mut self) -> u64 {
79 self.ts_counter += 1;
80 self.ts_counter
81 }
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,
86 kind: kind.into(),
87 plugin: plugin.into(),
88 detail: detail.into(),
89 success,
90 });
91 }
93 /// Load a Lua plugin. Returns Ok(()) on success, Err on failure.
94 fn load_plugin(&mut self, name: &str, lua_code: &str) -> Result<(), String> {
95 let lua = Lua::new();
97 // Phase 1: Load — execute Lua code
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));
102 }
104 // Phase 2: Validate — check that expected hooks exist
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
110 )).eval();
111 match check {
112 Ok(true) => {
113 hooks.insert(hook.to_string(), HookEntry {
114 name: hook.to_string(),
115 lua_fn_name: hook.to_string(),
116 version: name.to_string(),
117 });
118 },
119 Ok(false) => {
120 let ts = self.now_ns();
121 self.trace_event("PluginError", name, &format!("missing hook: {}", hook), false);
122 return Err(format!("Missing hook: {}", hook));
123 },
124 Err(e) => {
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));
128 },
129 }
130 }
132 // Phase 3: Register — store hooks (atomically replace old)
133 let ts = self.now_ns();
134 self.trace_event("PluginLoaded", name, &format!("hooks={}", hooks.len()), true);
136 let instance = PluginInstance {
137 lua,
138 hooks,
139 version: name.to_string(),
140 };
141 self.current = Some(instance);
143 // Phase 4: Activate — fire event
144 let ts = self.now_ns();
145 self.trace_event("PluginEvent", name, "activated", true);
147 Ok(())
148 }
150 /// Hot reload: load new plugin, validate, swap atomically. On failure, keep old.
151 fn hot_reload(&mut self, name: &str, lua_code: &str) -> Result<(), String> {
152 // Save old plugin for rollback
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) {
157 Ok(()) => {
158 let ts = self.now_ns();
159 self.trace_event("PluginEvent", name, &format!("replaced {}", old_version), true);
160 Ok(())
161 },
162 Err(e) => {
163 // Rollback: restore old plugin
164 self.current = old;
165 let ts = self.now_ns();
166 self.trace_event("PluginEvent", name, &format!("rollback to {}", old_version), false);
167 Err(e)
168 },
169 }
170 }
172 /// Call tool_call_transform hook. Returns the transformed result.
173 fn call_tool_hook(&mut self, tool_name: &str, args: &str) -> Result<String, String> {
174 match &self.current {
175 Some(inst) => {
176 let lua = &inst.lua;
177 let result: String = lua.load(&format!(
178 "return tool_call_transform('{}', '{}')",
179 tool_name, args
180 )).eval().map_err(|e| format!("hook error: {}", e))?;
181 Ok(result)
182 },
183 None => Err("no plugin loaded".into()),
184 }
185 }
187 /// Call context_transform hook.
188 fn call_context_hook(&mut self, context: &str) -> Result<String, String> {
189 match &self.current {
190 Some(inst) => {
191 let result: String = inst.lua.load(&format!(
192 "return context_transform('{}')", context
193 )).eval().map_err(|e| format!("hook error: {}", e))?;
194 Ok(result)
195 },
196 None => Err("no plugin loaded".into()),
197 }
198 }
200 /// Simulate an agent turn.
201 fn simulate_turn(&mut self, user_msg: &str) {
202 self.session.message_count += 1;
203 self.session.last_model = "MiniMax-M2.7".into();
205 // Call hooks
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;
210 }
212 /// Get current plugin version.
213 fn current_version(&self) -> &str {
214 self.current.as_ref().map(|c| c.version.as_str()).unwrap_or("none")
215 }
216}
218// === Lua plugin code generators ===
220fn plugin_v1() -> &'static str {
221 r#"
222 function tool_call_transform(tool_name, args)
223 return "[v1] " .. args
224 end
226 function context_transform(ctx)
227 return "[v1] ctx=" .. ctx
228 end
229 "#
230}
232fn plugin_v2() -> &'static str {
233 r#"
234 function tool_call_transform(tool_name, args)
235 return "[v2] " .. args .. " (enhanced)"
236 end
238 function context_transform(ctx)
239 return "[v2] ctx=" .. ctx .. " (enhanced)"
240 end
241 "#
242}
244fn plugin_v3_bad_syntax() -> &'static str {
245 r#"
246 function tool_call_transform(tool_name, args)
247 return "[v3] " .. args
248 -- MISSING CLOSING: syntax error
249 "#
250}
252fn plugin_v4_missing_hook() -> &'static str {
253 r#"
254 function tool_call_transform(tool_name, args)
255 return "[v4] " .. args
256 end
257 -- context_transform is MISSING
258 "#
259}
261fn plugin_v5() -> &'static str {
262 r#"
263 function tool_call_transform(tool_name, args)
264 return "[v5] processed: " .. args
265 end
267 function context_transform(ctx)
268 return "[v5] context: " .. ctx
269 end
270 "#
271}
273// === Tests ===
275fn main() {
276 eprintln!("=== P15: Hot Reload ===");
277 eprintln!();
279 // --- Test 1: Load v1 plugin ---
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());
286 // --- Test 2: Agent loop with v1 ---
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);
300 // --- Test 3: Hot reload to v2 ---
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());
306 // --- Test 4: Validate v2 hook signatures ---
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);
317 // --- Test 5: Session preserved across reload ---
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);
326 // --- Test 6: Agent loop continues with v2 ---
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);
332 // --- Test 7: Rollback on bad syntax (v3) ---
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());
339 // Verify v2 hooks still work after rollback
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);
344 // --- Test 8: Rollback on missing hook (v4) ---
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());
351 // --- Test 9: Trace events recorded ---
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);
364 // v1 + v2 loaded = 2 PluginLoaded
365 assert!(loaded_count >= 2, "Should have >=2 PluginLoaded events, got {}", loaded_count);
366 // v3 syntax error + v4 missing hook = 2 PluginError
367 assert!(error_count >= 2, "Should have >=2 PluginError events, got {}", error_count);
369 // Check error details
370 for e in trace.iter().filter(|e| e.kind == "PluginError") {
371 eprintln!(" error: plugin={} detail={}", e.plugin, e.detail);
372 assert!(!e.success);
373 }
375 // Check rollback events
376 let rollback_events: Vec<_> = trace.iter()
377 .filter(|e| e.kind == "PluginEvent" && e.detail.contains("rollback"))
378 .collect();
379 assert_eq!(rollback_events.len(), 2, "Should have 2 rollback events (v3 + v4)");
380 eprintln!("[OK] 2 rollback events confirmed");
382 // --- Test 10: Multiple consecutive reloads ---
383 eprintln!("--- Test 10: 10 consecutive reloads ---");
384 let initial_turns = harness.session.turns_completed;
385 let trace_before = trace.len();
387 for i in 0..10 {
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));
392 }
394 assert_eq!(harness.session.turns_completed, initial_turns + 10);
395 eprintln!("[OK] 10 reloads completed, turns: {} → {}",
396 initial_turns, harness.session.turns_completed);
398 // Last loaded should be v5 (odd index 9)
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);
404 // Trace should have grown
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);
409 eprintln!();
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());
414}