README Source History Refs Reviews Compare Notes Search Review guide core(SMH-PLAN-CORE0002): make session recovery and replay trustworthy 8597565336e1e43bd71994051d519b51ecc8c31e
Oliver Jan Krylow <oliver@bugabinga.net > · 10 Sep 2026
unsigned
Browse files Compare with HEAD
Frames carry kind, version, and a CRC32, so corruption, schema damage,
and frames from a future build are distinguishable: loading now returns
recovered frames plus explicit damage instead of silently presenting
corrupt payloads as future ones.
A session header frame persists session and branch identity, so reload
reproduces the same state and replay output is byte-stable. Parent links
rebuild branches, fork publishes a new session atomically, and repair
waits on a sidecar session lock instead of replacing the file under a
live writer.
Tool invocation records the call before running the effect, refuses
cancelled sessions, reports RecordFailed with mutation state, wires bash
and its cancellation through the registry, rejects stale edit input, and
makes listing and searching ignore-aware.
Config moves to smith with field-path errors, and both crates drop their
blanket lint suppressions.
Changed files (19) Diff layout Auto Unified Split
.system/plans/SMH-PLAN-CORE0002-frame-recovery-and-core-gates/index.md Added new file mode 100644+107 / −0 text lines
4 + title: "Frame Recovery, Session Identity, and Core Gates"5 + spec: SMH-SPEC-SPEC00017 + depends_on: [SMH-PLAN-CORE0001]10 + # Frame Recovery, Session Identity, and Core Gates 12 + Remediation plan for the gaps found auditing `SMH-PLAN-CORE0001` against the code.13 + `SMH-PLAN-CORE0001` stays approved and unchanged; this plan carries its unmet work to exit.17 + - `smith` and `smith-core` implement types, framing, store, tools, and bash.18 + - The frame-recovery stop condition of `SMH-PLAN-CORE0001` is resolved by the decision below.24 + Wire layout, little endian:27 + [len u32][kind u16][version u16][crc32 u32][CBOR payload]30 + `len` counts every byte after itself, so skip-by-declared-length recovery is unchanged.31 + `kind` discriminates the payload; `SessionHeader` and `Entry` exist now, further kinds are reserved.32 + `crc32` covers kind, version, and payload.34 + Recovery decision table:36 + | crc32 | kind | outcome |38 + | valid | known | decode; a decode failure is schema damage and is reported |39 + | valid | unknown | future frame, preserved verbatim on round trip |40 + | invalid | any | corruption, reported as damage, skipped by declared length |42 + Damage is reported, not fatal.43 + Loading returns recovered frames plus a recovery report, because complete frames must survive alongside explicit damage reporting.44 + No v1 migration exists because nothing is released; v1 files are rejected by version.48 + One variant per layer, typed per-layer codes, no stringly codes.52 + | framing | fault kind and byte offset |53 + | storage | operation and path |54 + | session | branch, entry, and leaf faults |55 + | tools | tool name and `RecordFailed { mutation_applied }` |56 + | config | dotted field path |57 + | control | cancellation as its own variant |59 + `SmithError` stays serializable, so operating-system causes flatten into messages.61 + ### Scope confirmations 63 + - Ignore behavior for list, find, and grep belongs to this plan.64 + - Cancellation and timeout plumbing through tool invocation belongs to this plan.68 + 1. Introduce the layered error taxonomy and frame format v2 with checksum, kind, version, and recovery reports.69 + 2. Add the session header frame so session and branch identity survive reload.70 + 3. Restore branch structure from parent links, add fork, and write real compaction boundary entries.71 + 4. Serialize repair with the writer lock and keep publication atomic for created, forked, and repaired sessions.72 + 5. Fix the tool invocation contract: record call, run effect, record result, and report `RecordFailed` with mutation state.73 + 6. Plumb cancellation and configured timeout into every tool effect and wire the `bash` arm to `bash::execute`.74 + 7. Add edit stale detection, ignore-aware recursive list, find, and grep, and canonical encoding at the entry boundary.75 + 8. Emit tool, result, and compaction trace kinds, and make trace output byte-stable across loads.76 + 9. Restore build gates: remove blanket crate allows and `doc(hidden)`, move `Config` into `smith`, delete duplicated cancellation and dead code.80 + - `smith::error`: layered faults with codes, offsets, paths, and field paths.81 + - `smith::config`: validated configuration owned by the shared crate.82 + - `smith-core::frame`: v2 layout, checksum verification, and damage classification.83 + - `smith-core::store`: locked append, load with recovery report, fork, and locked repair.84 + - `smith-core::tools`: cancellable, timeout-bounded, durably recorded invocation.88 + - Corrupt frames are distinguishable from future frames and reported explicitly.89 + - Future frames still round-trip byte for byte.90 + - Session and branch identity survive reload, so replay output is byte-stable across loads.91 + - Repair cannot lose entries from a live writer.92 + - Fork and restoration preserve IDs, order, leaf, and compaction boundary.93 + - A successful mutation whose recording fails reports `mutation_applied`.94 + - Cancelling or timing out any tool leaves no partial durable claim of success.95 + - Ignore rules change list, find, and grep results deterministically.96 + - `cargo x check` passes with no crate-level lint suppression.100 + Provider-free tool activity can be persisted, recovered, and reconstructed deterministically,101 + and the workspace passes its gates without suppression.105 + - Checksum coverage cannot separate corruption from schema evolution in practice.106 + - Locked repair cannot stay atomic on a supported platform.107 + - Ignore semantics require configuration that the spec does not define.+128 / −25 text lines
8 + source = "registry+https://github.com/rust-lang/crates.io-index" 9 + checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" 5 14 [[package ]][[package ]]6 15 name = "bitflags" name = "bitflags" 7 16 version = "2.13.2" version = "2.13.2" 8 17 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 9 18 checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
23 + source = "registry+https://github.com/rust-lang/crates.io-index" 24 + checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" 11 30 [[package ]][[package ]]12 31 name = "bumpalo" name = "bumpalo" 13 32 version = "3.20.3" version = "3.20.3"
76 + name = "crossbeam-deque" 78 + source = "registry+https://github.com/rust-lang/crates.io-index" 79 + checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" 86 + name = "crossbeam-epoch" 88 + source = "registry+https://github.com/rust-lang/crates.io-index" 89 + checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" 95 + name = "crossbeam-utils" 97 + source = "registry+https://github.com/rust-lang/crates.io-index" 98 + checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" 56 100 [[package ]][[package ]]57 101 name = "crunchy" name = "crunchy" 58 102 version = "0.2.4" version = "0.2.4"
192 + source = "registry+https://github.com/rust-lang/crates.io-index" 193 + checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" 145 202 [[package ]][[package ]]146 203 name = "half" name = "half" 147 204 version = "2.7.1" version = "2.7.1" 159 216 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 160 217 checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
222 + source = "registry+https://github.com/rust-lang/crates.io-index" 223 + checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f" 162 235 [[package ]][[package ]]163 236 name = "indexmap" name = "indexmap" 164 237 version = "2.14.2" version = "2.14.2"
280 + source = "registry+https://github.com/rust-lang/crates.io-index" 281 + checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" 204 283 [[package ]][[package ]]205 284 name = "memchr" name = "memchr" 206 285 version = "2.8.3" version = "2.8.3" 269 348 dependencies = [dependencies = [270 349 "getrandom 0.2.17" , "getrandom 0.2.17" ,271 350 "libredox" , "libredox" ,
355 + name = "regex-automata" 357 + source = "registry+https://github.com/rust-lang/crates.io-index" 358 + checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" 366 + name = "regex-syntax" 368 + source = "registry+https://github.com/rust-lang/crates.io-index" 369 + checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" 275 371 [[package ]][[package ]]276 372 name = "rustversion" name = "rustversion" 277 373 version = "1.0.23" version = "1.0.23" 278 374 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 279 375 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
380 + source = "registry+https://github.com/rust-lang/crates.io-index" 381 + checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" 281 386 [[package ]][[package ]]282 387 name = "serde" name = "serde" 283 388 version = "1.0.229" version = "1.0.229" 333 438 version = "0.1.0" version = "0.1.0" 334 439 dependencies = [dependencies = [335 440 "ciborium" , "ciborium" ,337 443 "serde_json" , "serde_json" ,359 464 version = "0.1.0" version = "0.1.0" 360 465 dependencies = [dependencies = [361 466 "ciborium" , "ciborium" ,366 471 "serde_json" , "serde_json" ,414 518 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 415 519 checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" 416 520 dependencies = [dependencies = [417 - "thiserror-impl 1.0.69" ,423 - source = "registry+https://github.com/rust-lang/crates.io-index" 424 - checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" 426 - "thiserror-impl 2.0.20" ,429 524 [[package ]][[package ]]437 532 "syn 2.0.119" , "syn 2.0.119" ,441 - name = "thiserror-impl" 443 - source = "registry+https://github.com/rust-lang/crates.io-index" 444 - checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
451 535 [[package ]][[package ]]452 536 name = "unicode-ident" name = "unicode-ident" 453 537 version = "1.0.24" version = "1.0.24" 466 550 "wasm-bindgen" , "wasm-bindgen" ,
556 + source = "registry+https://github.com/rust-lang/crates.io-index" 557 + checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" 469 563 [[package ]][[package ]]470 564 name = "wasi" name = "wasi" 471 565 version = "0.11.1+wasi-snapshot-preview1" version = "0.11.1+wasi-snapshot-preview1" 533 627 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 534 628 checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
633 + source = "registry+https://github.com/rust-lang/crates.io-index" 634 + checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" 536 639 [[package ]][[package ]]537 640 name = "winapi-x86_64-pc-windows-gnu" name = "winapi-x86_64-pc-windows-gnu" 538 641 version = "0.4.0" version = "0.4.0" smith-core/Cargo.toml Modified +1 / −2 text lines
12 12 serde = { workspace = true }serde = { workspace = true }13 13 serde_json = { workspace = true }serde_json = { workspace = true }14 14 ciborium = { workspace = true }ciborium = { workspace = true }15 - thiserror = { workspace = true }
16 15 uuid = { workspace = true }uuid = { workspace = true }17 - dirs = { workspace = true }
18 16 fs2 = { workspace = true }fs2 = { workspace = true }
17 + ignore = { workspace = true }20 19 [target .'cfg(unix)' .dependencies ][target .'cfg(unix)' .dependencies ]21 20 nix = { version = "0.29" , features = ["signal" ] }No final newline nix = { version = "0.29" , features = ["signal" ] }No final newline smith-core/src/bash.rs Modified +27 / −19 text lines
39 43 pub fn execute (pub fn execute (40 44 cmd: &str , cmd: &str ,41 45 workdir: Option <&str >, workdir: Option <&str >,51 55 let stderr_remaining = Arc::new(AtomicUsize::new(max_output_bytes)); let stderr_remaining = Arc::new(AtomicUsize::new(max_output_bytes));52 56 let handles = drain_pipes ( let handles = drain_pipes (53 57 &mut child, &mut child,55 - stdout_remaining.clone (),56 - stderr_remaining.clone (),59 + Arc::clone(& stdout_remaining),60 + Arc::clone(& stderr_remaining),91 95 status = Some (st); status = Some (st);94 - if status.is_none () { 95 - if let Ok (Some (st)) = child.try_wait () { 99 + && let Ok (Some (st)) = child.try_wait ()101 - if status.is_none () { 102 - if let Ok (Some (st)) = child.try_wait () { 106 + && let Ok (Some (st)) = child.try_wait ()115 119 Stream::Stdout => stdout.extend_from_slice (& chunk), Stream::Stdout => stdout.extend_from_slice (& chunk),116 120 Stream::Stderr => stderr.extend_from_slice (& chunk), Stream::Stderr => stderr.extend_from_slice (& chunk),118 - Err (RecvTimeoutError::Timeout) => continue , 122 + Err (RecvTimeoutError::Timeout) => { } 119 123 Err (RecvTimeoutError::Disconnected) => break , Err (RecvTimeoutError::Disconnected) => break ,129 133 stderr: String ::from_utf8_lossy(& stderr).into_owned (), stderr: String ::from_utf8_lossy(& stderr).into_owned (),130 134 cancelled, cancelled,131 135 timed_out, timed_out,132 - duration_ms: started.elapsed ().as_millis () as u64 ,136 + duration_ms: u64 :: try_from ( started.elapsed ().as_millis ()) . unwrap_or ( u64 :: MAX ) ,170 174 use nix::sys::signal::{Signal, killpg}; use nix::sys::signal::{Signal, killpg};171 175 use nix::unistd::Pid; use nix::unistd::Pid;172 - let pgid = Pid::from_raw(child.id () as i32 );176 + let pgid = Pid::from_raw(i32 :: try_from ( child.id ()) . unwrap_or ( i32 :: MAX )) ;173 177 let _ = killpg (pgid, Signal::SIGKILL ); let _ = killpg (pgid, Signal::SIGKILL );175 179 let _ = child.kill (); let _ = child.kill ();181 185 fn drain_pipes (fn drain_pipes (182 186 child: &mut Child, child: &mut Child,183 - tx: mpsc::Sender<(Stream, Vec <u8 >)>,187 + tx: & mpsc::Sender<(Stream, Vec <u8 >)>,184 188 stdout_remaining: Arc<AtomicUsize>, stdout_remaining: Arc<AtomicUsize>,185 189 stderr_remaining: Arc<AtomicUsize>, stderr_remaining: Arc<AtomicUsize>,186 190 ) -> Vec <std::thread::JoinHandle<()>> {) -> Vec <std::thread::JoinHandle<()>> {207 212 fn spawn_reader <R: Read + Send + 'static >(fn spawn_reader <R: Read + Send + 'static >(208 213 mut pipe: R, mut pipe: R,209 214 tx: mpsc::Sender<(Stream, Vec <u8 >)>, tx: mpsc::Sender<(Stream, Vec <u8 >)>,214 219 let mut buf = vec! [0 u8 ; READ_CHUNK ]; let mut buf = vec! [0 u8 ; READ_CHUNK ];216 221 match pipe.read (&mut buf) { match pipe.read (&mut buf) {223 + Ok (0 ) | Err ( _ ) => break ,218 224 Ok (n) => { Ok (n) => {219 225 let keep = n.min (remaining.load (Ordering::Relaxed)); let keep = n.min (remaining.load (Ordering::Relaxed));220 226 if keep > 0 { if keep > 0 {235 240 #[cfg(test)]#[cfg(test)]236 241 #[cfg(unix)]#[cfg(unix)]237 - #[allow(clippy::unwrap_used, clippy::expect_used)]243 + clippy::unwrap_used,244 + reason = "tests may panic on invariant violations" 238 246 mod tests {mod tests {239 247 use super ::* ; use super ::* ;240 248 use std::thread; use std::thread;smith-core/src/config.rs Deleted deleted file mode 100644+0 / −54 text lines
1 - use serde::{Deserialize, Serialize};4 - #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]7 - pub session_dir: String,9 - pub max_frame_bytes: usize ,11 - pub tool_timeout_ms: u64 ,13 - pub preserve_unknown_frames: bool ,19 - pub fn default_valid () -> Self {20 - let session_dir = match dirs::data_dir() {21 - Some (base) => base.join ("smith" ).join ("sessions" ),22 - None => std::path::PathBuf::from(".smith" ).join ("sessions" ),25 - session_dir: session_dir.to_string_lossy ().into_owned (),26 - max_frame_bytes: 1024 * 1024 ,27 - tool_timeout_ms: 30_000 ,28 - preserve_unknown_frames: true ,33 - pub fn validate (& self) -> Result <(), String > {34 - if self.session_dir.trim ().is_empty () {35 - return Err ("session_dir must not be empty" .to_string ());37 - if self.max_frame_bytes < 1024 {38 - return Err ("max_frame_bytes must be at least 1024" .to_string ());40 - if self.max_frame_bytes > 1024 * 1024 * 100 {41 - return Err ("max_frame_bytes exceeds safe limit of 100MB" .to_string ());43 - if self.tool_timeout_ms < 100 {44 - return Err ("tool_timeout_ms must be at least 100ms" .to_string ());50 - impl Default for Config {51 - fn default () -> Self {52 - Self ::default_valid()
smith-core/src/frame.rs Modified +502 / −172 text lines
8 - use crate ::session::Entry;9 - use smith::error::{Result , SmithError};15 + use crate ::session::{ Entry, SessionHeader } ;16 + use smith::error::{FrameFault , Result , SmithError};17 + use std::io::{ Read , Write} ;13 20 pub const DEFAULT_MAX_FRAME_BYTES : usize = 1024 * 1024 ;pub const DEFAULT_MAX_FRAME_BYTES : usize = 1024 * 1024 ;16 - pub const MAX_DECLARED_LENGTH : usize = u32 ::MAX as usize ;23 + pub const HEADER_LEN : usize = 4 ;18 - pub (crate ) const HEADER_LEN : usize = 4 ;26 + pub const BODY_PREFIX_LEN : usize = 8 ;29 + pub const KIND_ENTRY : u16 = 1 ;32 + pub const VERSION_ENTRY : u16 = 1 ;35 + pub const KIND_SESSION_HEADER : u16 = 2 ;38 + pub const VERSION_SESSION_HEADER : u16 = 1 ;41 + const SKIP_CHUNK : usize = 64 * 1024 ;21 - #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize , serde::Deserialize )]44 + #[derive(Clone, PartialEq, Eq, Debug)]22 45 pub enum Frame {pub enum Frame {
49 + header: SessionHeader,26 54 entry: Entry, entry: Entry,33 - declared_length: usize ,37 68 impl Frame {impl Frame {40 - pub fn encode_entry (entry: & Entry, max_frame_bytes: usize ) -> Result <Vec <u8 >> {75 + pub fn encode_payload <T: serde::Serialize>(77 + max_frame_bytes: usize ,78 + ) -> Result <Vec <u8 >> {41 79 let mut limited = LimitedWriter::new(max_frame_bytes); let mut limited = LimitedWriter::new(max_frame_bytes);42 - match ciborium::ser::into_writer(entry, &mut limited) {45 - if limited.overflowed () {46 - return Err (SmithError::FrameTooLarge {47 - max_bytes: max_frame_bytes,48 - actual: max_frame_bytes + 1 ,51 - return Err (SmithError::FrameEncode {52 - message: e.to_string (),80 + let result = ciborium::ser::into_writer(value, &mut limited);56 81 if limited.overflowed () { if limited.overflowed () {57 - return Err (SmithError::FrameTooLarge {58 - max_bytes: max_frame_bytes,59 - actual: max_frame_bytes + 1 ,82 + return Err (too_large (max_frame_bytes, max_frame_bytes + 1 ));85 + Ok (()) => Ok (limited.into_inner ()),86 + Err (e) => Err (fault (FrameFault::Encode {87 + message: e.to_string (),62 - Ok (limited.into_inner ())
66 98 pub fn encode (& self, max_frame_bytes: usize ) -> Result <Vec <u8 >> { pub fn encode (& self, max_frame_bytes: usize ) -> Result <Vec <u8 >> {67 - let payload = match self {68 - Self ::Known { entry } => Self ::encode_entry(entry, max_frame_bytes)? ,99 + let (kind, version, payload) = match self {100 + Self ::Header { header } => (101 + KIND_SESSION_HEADER ,102 + VERSION_SESSION_HEADER ,103 + Self ::encode_payload(header, max_frame_bytes)? ,105 + Self ::Known { entry } => (108 + Self ::encode_payload(entry, max_frame_bytes)? ,69 110 Self ::Unknown { Self ::Unknown {73 - if raw_bytes.len () != * declared_length || * declared_length > max_frame_bytes {74 - return Err (SmithError::FrameEncode {76 - "unknown frame length {} inconsistent or above limit {}" ,77 - declared_length, max_frame_bytes115 + if payload.len () > max_frame_bytes {116 + return Err (too_large (max_frame_bytes, payload.len ()));118 + (* kind, * version, payload.clone ())84 - let mut out = Vec ::with_capacity(HEADER_LEN + payload.len ());85 - out.extend_from_slice (& (payload.len () as u32 ).to_le_bytes ());86 - out.extend_from_slice (& payload);121 + let declared = BODY_PREFIX_LEN + payload.len ();122 + let mut body = Vec ::with_capacity(declared);123 + body.extend_from_slice (& kind.to_le_bytes ());124 + body.extend_from_slice (& version.to_le_bytes ());125 + body.extend_from_slice (& crc32 (kind, version, & payload).to_le_bytes ());126 + body.extend_from_slice (& payload);127 + let Ok (prefix) = u32 ::try_from(declared) else {128 + return Err (too_large (max_frame_bytes, payload.len ()));130 + let mut out = Vec ::with_capacity(HEADER_LEN + declared);131 + out.extend_from_slice (& prefix.to_le_bytes ());132 + out.extend_from_slice (& body);92 - pub fn decode_payload (payload: Vec <u8 >) -> Self {93 - match ciborium::de::from_reader::<Entry, _ >(payload.as_slice ()) {94 - Ok (entry) => Self ::Known { entry },95 - Err (_ ) => Self ::Unknown {96 - declared_length: payload.len (),139 + fn decode_body (body: & [u8 ]) -> std::result::Result <Frame, FrameFault> {140 + if body.len () < BODY_PREFIX_LEN {141 + return Err (FrameFault::Malformed {142 + declared_length: body.len (),145 + let kind = u16 ::from_le_bytes([body[0 ], body[1 ]]);146 + let version = u16 ::from_le_bytes([body[2 ], body[3 ]]);147 + let checksum = u32 ::from_le_bytes([body[4 ], body[5 ], body[6 ], body[7 ]]);148 + let payload = & body[BODY_PREFIX_LEN .. ];149 + if checksum != crc32 (kind, version, payload) {150 + return Err (FrameFault::Checksum {151 + declared_length: body.len (),154 + match (kind, version) {155 + (KIND_ENTRY , VERSION_ENTRY ) => decode_payload (payload).map (|entry| Frame::Known { entry }),156 + (KIND_SESSION_HEADER , VERSION_SESSION_HEADER ) => {157 + decode_payload (payload).map (|header| Frame::Header { header })
159 + (KIND_ENTRY | KIND_SESSION_HEADER , _ ) => {160 + Err (FrameFault::UnsupportedVersion { kind, version })162 + _ => Ok (Frame::Unknown {165 + payload: payload.to_vec (),104 - #[derive(Clone, PartialEq, Eq, Debug)]105 - pub enum DecodeOutcome {107 - Frame(Frame, usize ),170 + fn decode_payload <T: serde::de::DeserializeOwned>(172 + ) -> std::result::Result <T, FrameFault> {173 + ciborium::de::from_reader::<T, _ >(payload).map_err (|e| FrameFault::SchemaDecode {174 + message: e.to_string (),120 - pub fn decode_frame (buf: & [u8 ], max_frame_bytes: usize ) -> DecodeOutcome {121 - if buf.len () < HEADER_LEN {122 - return DecodeOutcome::Incomplete;124 - let declared = u32 ::from_le_bytes([buf[0 ], buf[1 ], buf[2 ], buf[3 ]]) as usize ;125 - let total = HEADER_LEN .saturating_add (declared);126 - if total > buf.len () {127 - return DecodeOutcome::Incomplete;129 - if declared > max_frame_bytes {130 - return DecodeOutcome::Skipped(total);132 - let frame = Frame::decode_payload(buf[HEADER_LEN .. total].to_vec ());133 - DecodeOutcome::Frame(frame, total)182 + #[derive(Clone, PartialEq, Eq, Debug, Default)]183 + pub struct Recovery {185 + pub frames: Vec <Frame>,187 + pub damage: Vec <SmithError>,191 + pub torn_tail_at: Option <u64 >,198 + pub fn read_frames <R: Read>(reader: &mut R, max_frame_bytes: usize ) -> Recovery {199 + let mut recovery = Recovery::default();200 + let declared_limit = max_frame_bytes.saturating_add (BODY_PREFIX_LEN );202 + let offset = recovery.good_end;203 + let mut header = [0 u8 ; HEADER_LEN ];204 + match read_exact_or_eof (reader, &mut header) {208 + recovery.torn_tail_at = Some (offset);212 + let declared = u32 ::from_le_bytes(header) as usize ;213 + let total = HEADER_LEN as u64 + declared as u64 ;214 + if declared > declared_limit {215 + if ! skip_exact (reader, declared) {216 + recovery.torn_tail_at = Some (offset);219 + recovery.damage.push (located (220 + FrameFault::TooLarge {221 + max_bytes: max_frame_bytes,222 + actual: declared.saturating_sub (BODY_PREFIX_LEN ),226 + recovery.good_end = offset + total;229 + let mut body = vec! [0 u8 ; declared];230 + if reader.read_exact (&mut body).is_err () {231 + recovery.torn_tail_at = Some (offset);234 + match decode_body (& body) {235 + Ok (frame) => recovery.frames.push (frame),236 + Err (f) => recovery.damage.push (located (f, offset)),238 + recovery.good_end = offset + total;137 248 pub fn write_frame (writer: &mut impl Write, frame: & Frame, max_frame_bytes: usize ) -> Result <()> {pub fn write_frame (writer: &mut impl Write, frame: & Frame, max_frame_bytes: usize ) -> Result <()> {138 249 let bytes = frame.encode (max_frame_bytes)? ; let bytes = frame.encode (max_frame_bytes)? ;141 - .map_err (|e| SmithError::FrameEncode {250 + writer.write_all (& bytes).map_err (|e| {251 + fault (FrameFault::Encode {142 252 message: e.to_string (), message: e.to_string (),
258 + const fn fault (f: FrameFault) -> SmithError {265 + const fn located (f: FrameFault, offset: u64 ) -> SmithError {268 + offset: Some (offset),272 + const fn too_large (max_bytes: usize , actual: usize ) -> SmithError {273 + fault (FrameFault::TooLarge { max_bytes, actual })278 + fn read_exact_or_eof <R: Read>(reader: &mut R, buf: &mut [u8 ]) -> std::io::Result <bool > {280 + while filled < buf.len () {281 + match reader.read (&mut buf[filled.. ]) {286 + return Err (std::io::Error::new(287 + std::io::ErrorKind::UnexpectedEof,291 + Ok (n) => filled += n,292 + Err (e) if e.kind () == std::io::ErrorKind::Interrupted => {}293 + Err (e) => return Err (e),300 + fn skip_exact <R: Read>(reader: &mut R, len: usize ) -> bool {301 + let mut remaining = len;302 + let mut sink = vec! [0 u8 ; remaining.min (SKIP_CHUNK )];303 + while remaining > 0 {304 + let chunk = remaining.min (SKIP_CHUNK );305 + if reader.read_exact (&mut sink[.. chunk]).is_err () {314 + fn crc32 (kind: u16 , version: u16 , payload: & [u8 ]) -> u32 {315 + let mut crc = 0xFFFF_FFFF_ u32 ;316 + let mut step = |byte: u8 | {317 + let index = ((crc ^ u32 ::from(byte)) & 0xFF ) as usize ;318 + crc = (crc >> 8 ) ^ CRC32_TABLE [index];320 + for byte in kind.to_le_bytes () {323 + for byte in version.to_le_bytes () {326 + for byte in payload {332 + const CRC32_TABLE : [u32 ; 256 ] = {333 + let mut table = [0 u32 ; 256 ];339 + value = if value & 1 == 1 {340 + 0xEDB8_8320 ^ (value >> 1 )346 + table[i as usize ] = value;149 354 struct LimitedWriter {struct LimitedWriter {155 360 impl LimitedWriter {impl LimitedWriter {156 - fn new (limit: usize ) -> Self {361 + const fn new (limit: usize ) -> Self {158 363 buf: Vec ::new(), buf: Vec ::new(),159 364 remaining: limit, remaining: limit,164 - fn overflowed (& self) -> bool {369 + const fn overflowed (& self) -> bool {165 370 self.overflow self.overflow201 406 pub use crate ::session::canonical_json;pub use crate ::session::canonical_json;202 408 #[cfg(test)]#[cfg(test)]203 - #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]410 + clippy::unwrap_used,412 + reason = "tests may panic on invariant violations" 204 414 mod tests {mod tests {205 415 use super ::* ; use super ::* ;206 416 use crate ::session::{Entry, EntryContent}; use crate ::session::{Entry, EntryContent};215 425 Entry::message(msg, None ) Entry::message(msg, None )
428 + fn known_bytes (text: &str ) -> Vec <u8 > {430 + entry: Entry::message(Message::with_text(Role::User, text), None ),432 + .encode (DEFAULT_MAX_FRAME_BYTES )436 + fn text_of (frame: & Frame) -> String {438 + Frame::Known { entry } => match & entry.content {439 + EntryContent::Message(m) => match & m.blocks[0 ] {440 + ContentBlock::Text(t) => t.clone (),441 + other => panic! ("unexpected block {other:?}" ),443 + other => panic! ("unexpected content {other:?}" ),445 + other => panic! ("unexpected frame {other:?}" ),449 + fn read_all (bytes: & [u8 ], max_frame_bytes: usize ) -> Recovery {450 + read_frames (&mut & bytes[.. ], max_frame_bytes)454 + fn corrupt_frame_is_reported_and_neighbours_survive () {455 + let mut bytes = known_bytes ("before" );456 + let corrupt_at = bytes.len () as u64 ;457 + let mut corrupt = known_bytes ("corrupt" );459 + let last = corrupt.len () - 1 ;460 + corrupt[last] ^= 0xFF ;461 + bytes.extend_from_slice (& corrupt);462 + bytes.extend_from_slice (& known_bytes ("after" ));464 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );465 + let texts: Vec <String > = recovery.frames.iter ().map (text_of).collect ();466 + assert_eq! (texts, vec! ["before" .to_string (), "after" .to_string ()]);467 + assert_eq! (recovery.damage.len (), 1 );468 + assert_eq! (recovery.damage[0 ].code (), "FRAME_CHECKSUM" );472 + fault: FrameFault::Checksum {473 + declared_length: corrupt.len () - HEADER_LEN 475 + offset: Some (corrupt_at),478 + assert_eq! (recovery.good_end, bytes.len () as u64 );479 + assert_eq! (recovery.torn_tail_at, None );483 + fn future_frame_round_trips_byte_for_byte () {484 + let future = Frame::Unknown {487 + payload: vec! [0xDE , 0xAD , 0x01 , 0x02 ],489 + let bytes = future.encode (DEFAULT_MAX_FRAME_BYTES ).unwrap ();490 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );491 + assert! (recovery.damage.is_empty ());492 + assert_eq! (recovery.frames, vec! [future]);494 + recovery.frames[0 ].encode (DEFAULT_MAX_FRAME_BYTES ).unwrap (),219 500 fn known_frame_round_trips_through_cbor () { fn known_frame_round_trips_through_cbor () {220 501 let entry = sample_entry (true ); let entry = sample_entry (true );224 505 .encode (DEFAULT_MAX_FRAME_BYTES ) .encode (DEFAULT_MAX_FRAME_BYTES )225 506 .unwrap (); .unwrap ();226 - match decode_frame (& bytes, DEFAULT_MAX_FRAME_BYTES ) {227 - DecodeOutcome::Frame(Frame::Known { entry: back }, consumed) => {228 - assert_eq! (consumed, bytes.len ());229 - let msg = match back.content {230 - EntryContent::Message(m) => m,231 - other => panic! ("unexpected content {other:?}" ),233 - assert_eq! (msg.blocks[0 ], ContentBlock::Text("hello" .into ()));234 - assert_eq! (msg.blocks[1 ], ContentBlock::Thinking("internal" .into ()));236 - other => panic! ("unexpected outcome {other:?}" ),507 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );508 + assert_eq! (recovery.frames, vec! [Frame::Known { entry }]);509 + assert_eq! (recovery.good_end, bytes.len () as u64 );241 - fn torn_tail_reports_incomplete () {242 - let bytes = Frame::Known {243 - entry: sample_entry (false ),245 - .encode (DEFAULT_MAX_FRAME_BYTES )513 + fn torn_tail_is_located_and_earlier_frames_kept () {514 + let mut bytes = known_bytes ("kept" );515 + let tail_at = bytes.len () as u64 ;516 + bytes.extend_from_slice (& known_bytes ("lost" )[.. 6 ]);517 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );247 518 assert_eq! ( assert_eq! (248 - decode_frame (& bytes[.. 3 ], 1 << 20 ),249 - DecodeOutcome::Incomplete252 - decode_frame (& bytes[.. bytes.len () - 1 ], 1 << 20 ),253 - DecodeOutcome::Incomplete519 + recovery.frames.iter ().map (text_of).collect::<Vec <_ >>(),520 + vec! ["kept" .to_string ()]
522 + assert_eq! (recovery.torn_tail_at, Some (tail_at));523 + assert_eq! (recovery.good_end, tail_at);526 + let mut short = known_bytes ("kept" );527 + let short_tail = short.len () as u64 ;528 + short.extend_from_slice (& [0xFF , 0xFF ]);529 + let recovery = read_all (& short, DEFAULT_MAX_FRAME_BYTES );530 + assert_eq! (recovery.frames.len (), 1 );531 + assert_eq! (recovery.torn_tail_at, Some (short_tail));258 535 fn oversized_complete_frame_is_skipped_by_length () { fn oversized_complete_frame_is_skipped_by_length () {259 - let payload = vec! [0xAB_ u8 ; 100 ];260 - let mut bytes = (payload.len () as u32 ).to_le_bytes ().to_vec ();261 - bytes.extend_from_slice (& payload);263 - match decode_frame (& bytes, 50 ) {264 - DecodeOutcome::Skipped(consumed) => assert_eq! (consumed, bytes.len ()),265 - other => panic! ("unexpected outcome {other:?}" ),536 + let mut bytes = (5000_ u32 ).to_le_bytes ().to_vec ();537 + bytes.extend_from_slice (& vec! [0xAB_ u8 ; 5000 ]);538 + let skipped = bytes.len () as u64 ;539 + bytes.extend_from_slice (& known_bytes ("tail" ));540 + let recovery = read_all (& bytes, 1024 );542 + recovery.frames.iter ().map (text_of).collect::<Vec <_ >>(),543 + vec! ["tail" .to_string ()]545 + assert_eq! (recovery.damage.len (), 1 );546 + assert_eq! (recovery.damage[0 ].code (), "FRAME_TOO_LARGE" );550 + fault: FrameFault::TooLarge {552 + actual: 5000 - BODY_PREFIX_LEN 557 + assert_eq! (recovery.good_end, bytes.len () as u64 );558 + assert_eq! (skipped, 5004 );270 - fn oversized_truncated_frame_is_incomplete_not_scanned () {562 + fn oversized_truncated_frame_is_torn_not_scanned () {271 563 let mut bytes = 200_ u32 .to_le_bytes ().to_vec (); let mut bytes = 200_ u32 .to_le_bytes ().to_vec ();272 564 bytes.extend_from_slice (& [0 u8 ; 10 ]); bytes.extend_from_slice (& [0 u8 ; 10 ]);273 - assert_eq! (decode_frame (& bytes, 50 ), DecodeOutcome::Incomplete);565 + let recovery = read_all (& bytes, 50 );566 + assert! (recovery.frames.is_empty ());567 + assert! (recovery.damage.is_empty ());568 + assert_eq! (recovery.torn_tail_at, Some (0 ));277 - fn sequential_decode_consumes_each_frame () {278 - let f1 = Frame::Known {279 - entry: sample_entry (false ),572 + fn declared_length_below_body_prefix_is_malformed () {573 + let mut bytes = 3_ u32 .to_le_bytes ().to_vec ();574 + bytes.extend_from_slice (& [1 , 2 , 3 ]);575 + bytes.extend_from_slice (& known_bytes ("after" ));576 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );577 + assert_eq! (recovery.damage.len (), 1 );578 + assert_eq! (recovery.damage[0 ].code (), "FRAME_MALFORMED" );579 + assert_eq! (recovery.frames.len (), 1 );583 + fn unsupported_entry_version_is_reported_not_preserved () {584 + let payload = vec! [0xA0 ]; 585 + let frame = Frame::Unknown {587 + version: VERSION_ENTRY + 1 ,281 - let f2 = Frame::Known {282 - entry: sample_entry (false ),590 + let bytes = frame.encode (DEFAULT_MAX_FRAME_BYTES ).unwrap ();591 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );592 + assert! (recovery.frames.is_empty ());593 + assert_eq! (recovery.damage[0 ].code (), "FRAME_VERSION" );597 + fn checksum_valid_entry_with_bad_schema_is_schema_damage () {598 + let frame = Frame::Unknown {600 + version: VERSION_ENTRY ,601 + payload: vec! [0xA0 ], 284 - let mut bytes = f1.encode (1 << 20 ).unwrap ();285 - bytes.extend_from_slice (& f2.encode (1 << 20 ).unwrap ());286 - let (first, used1) = match decode_frame (& bytes, 1 << 20 ) {287 - DecodeOutcome::Frame(f, n) => (f, n),288 - other => panic! ("unexpected {other:?}" ),290 - assert_eq! (first, f1);291 - let (second, used2) = match decode_frame (& bytes[used1.. ], 1 << 20 ) {292 - DecodeOutcome::Frame(f, n) => (f, n),293 - other => panic! ("unexpected {other:?}" ),295 - assert_eq! (second, f2);296 - assert_eq! (used1 + used2, bytes.len ());603 + let bytes = frame.encode (DEFAULT_MAX_FRAME_BYTES ).unwrap ();604 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );605 + assert! (recovery.frames.is_empty ());606 + assert_eq! (recovery.damage[0 ].code (), "FRAME_SCHEMA" );610 + fn version_one_frames_without_body_prefix_are_rejected () {612 + let entry = sample_entry (false );613 + let payload = Frame::encode_payload(& entry, DEFAULT_MAX_FRAME_BYTES ).unwrap ();614 + let mut bytes = u32 ::try_from(payload.len ()).unwrap ().to_le_bytes ().to_vec ();615 + bytes.extend_from_slice (& payload);616 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );617 + assert! (recovery.frames.is_empty ());618 + assert_eq! (recovery.damage.len (), 1 );622 + fn sequential_frames_consume_the_whole_stream () {623 + let mut bytes = known_bytes ("one" );624 + bytes.extend_from_slice (& known_bytes ("two" ));625 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );627 + recovery.frames.iter ().map (text_of).collect::<Vec <_ >>(),628 + vec! ["one" .to_string (), "two" .to_string ()]630 + assert_eq! (recovery.good_end, bytes.len () as u64 );335 669 e2.id = e1.id; e2.id = e1.id;336 670 e2.timestamp_ms = e1.timestamp_ms; e2.timestamp_ms = e1.timestamp_ms;337 - let b1 = Frame::Known { entry: e1. clone ( ) }.encode (1 << 20 ).unwrap ();338 - let b2 = Frame::Known { entry: e2. clone ( ) }.encode (1 << 20 ).unwrap ();671 + let b1 = Frame::Known { entry: e1 }.encode (1 << 20 ).unwrap ();672 + let b2 = Frame::Known { entry: e2 }.encode (1 << 20 ).unwrap ();339 673 assert_eq! (b1, b2); assert_eq! (b1, b2);343 - fn unknown_payload_is_preserved_verbatim () {344 - let raw = vec! [0xDE , 0xAD , 0xBE , 0xEF , 0x01 , 0x02 ];345 - let frame = Frame::Unknown {346 - declared_length: raw.len (),347 - raw_bytes: raw.clone (),677 + fn header_frame_round_trips () {678 + let header = SessionHeader {679 + session_id: smith::id::SessionId::new(),680 + branch_id: smith::id::BranchId::new(),349 - let bytes = frame.encode (1 << 20 ).unwrap ();350 - match decode_frame (& bytes, 1 << 20 ) {351 - DecodeOutcome::Frame(358 - assert_eq! (raw_bytes, raw);359 - assert_eq! (declared_length, raw.len ());360 - assert_eq! (used, bytes.len ());362 - other => panic! ("unexpected {other:?}" ),682 + let bytes = Frame::Header { header }683 + .encode (DEFAULT_MAX_FRAME_BYTES )685 + let recovery = read_all (& bytes, DEFAULT_MAX_FRAME_BYTES );686 + assert_eq! (recovery.frames, vec! [Frame::Header { header }]);687 + assert! (recovery.damage.is_empty ());691 + fn checksum_matches_known_reference_value () {693 + assert_eq! (crc32 (0x3231 , 0x3433 , b "56789" ), 0xCBF4_3926 );smith-core/src/lib.rs Modified +12 / −32 text lines
6 6 #![forbid(unsafe_code)]#![forbid(unsafe_code)]7 - #![warn(missing_docs, unused_mut)]15 - clippy::redundant_clone,17 - clippy::option_if_let_else,18 - clippy::missing_const_for_fn,19 - clippy::needless_pass_by_ref_mut,20 - clippy::too_long_first_doc_paragraph,
25 9 pub mod bash ;pub mod bash ;27 11 pub mod frame ;pub mod frame ;28 13 pub mod session ;pub mod session ;29 15 pub mod store ;pub mod store ;30 17 pub mod tools ;pub mod tools ;31 19 pub mod trace ;pub mod trace ;33 21 pub use bash::{BashResult, execute};pub use bash::{BashResult, execute};34 - pub use config::Config;35 - pub use frame::{DecodeOutcome, Frame, decode_frame, write_frame};36 - pub use session::{Branch, Entry, EntryContent, Session};37 - pub use store::{SessionWriter, load_session, repair_session};22 + pub use frame::{Frame, Recovery, read_frames, write_frame};23 + pub use session::{Branch, COMPACTION_KIND , Entry, EntryContent, Session, SessionHeader };25 + OpenSession, SessionWriter, create_session, fork_session, load_session, open_session,38 28 pub use tools::{ToolOutcome, ToolRegistry, ToolSession};pub use tools::{ToolOutcome, ToolRegistry, ToolSession};39 29 pub use trace::{TraceKind, TraceRecord, replay};pub use trace::{TraceKind, TraceRecord, replay};41 31 #[cfg(test)]#[cfg(test)]42 - #[allow(clippy::unwrap_used, clippy::expect_used)]
43 32 mod tests {mod tests {44 33 use super ::* ; use super ::* ;45 34 use smith::message::{Message, Role}; use smith::message::{Message, Role};52 41 session.append_to_active (entry); session.append_to_active (entry);53 42 assert_eq! (session.active_branch ().entries.len (), 1 ); assert_eq! (session.active_branch ().entries.len (), 1 );57 - fn config_validates_bounds () {58 - let mut cfg = Config::default_valid();59 - cfg.max_frame_bytes = 100 ;60 - assert! (cfg.validate ().is_err ());61 - cfg.max_frame_bytes = 1024 ;62 - assert! (cfg.validate ().is_ok ());
smith-core/src/session.rs Modified +442 / −21 text lines
1 3 use serde::{Deserialize, Serialize};use serde::{Deserialize, Serialize};2 - use smith::{ id :: * , message::Message};4 + use smith::error::{Result , SmithError};5 + use smith::id::{BranchId, EntryId, SessionId, ToolCallId};6 + use smith::message::{ ContentBlock , Message};7 + use std::collections::{HashMap, HashSet};10 + pub const COMPACTION_KIND : &str = "compaction" ;6 15 pub fn canonical_json (value: & serde_json::Value) -> serde_json::Value {pub fn canonical_json (value: & serde_json::Value) -> serde_json::Value {7 16 match value { match value {8 17 serde_json::Value::Object(map) => { serde_json::Value::Object(map) => {
35 + #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]36 + pub struct SessionHeader {38 + pub session_id: SessionId,40 + pub branch_id: BranchId,25 44 #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]26 45 pub struct Entry {pub struct Entry {34 53 pub content: EntryContent, pub content: EntryContent,37 57 #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]38 58 #[serde(tag = "kind" , content = "data" )]#[serde(tag = "kind" , content = "data" )]39 59 pub enum EntryContent {pub enum EntryContent {41 61 Message(Message), Message(Message),43 63 ToolCall { ToolCall {44 65 name: String , name: String ,45 67 input: serde_json::Value, input: serde_json::Value,46 - call_id: smith :: id :: ToolCallId,49 72 ToolResult { ToolResult {51 76 output: String , output: String ,52 - call_id: smith :: id :: ToolCallId,56 83 kind: String , kind: String ,57 85 detail: serde_json::Value, detail: serde_json::Value,
91 + fn canonicalize (content: EntryContent) -> EntryContent {93 + EntryContent::ToolCall {97 + } => EntryContent::ToolCall {99 + input: canonical_json (& input),102 + EntryContent::Meta { kind, detail } => EntryContent::Meta {104 + detail: canonical_json (& detail),106 + EntryContent::Message(mut message) => {107 + for block in &mut message.blocks {108 + if let ContentBlock::ToolUse { input, .. } = block {109 + * input = canonical_json (input);112 + EntryContent::Message(message)114 + other @ EntryContent::ToolResult { .. } => other,120 + std::time::SystemTime::now()121 + .duration_since (std::time::UNIX_EPOCH )122 + .map_or (0 , |elapsed| {123 + i64 ::try_from(elapsed.as_millis ()).unwrap_or (i64 ::MAX )61 127 impl Entry {impl Entry {62 130 pub fn new (parent: Option <EntryId>, content: EntryContent) -> Self { pub fn new (parent: Option <EntryId>, content: EntryContent) -> Self {64 132 id: EntryId::new(), id: EntryId::new(),66 - timestamp_ms: std::time::SystemTime::now()67 - .duration_since (std::time::UNIX_EPOCH )68 - .map (|d| d.as_millis () as i64 )134 + timestamp_ms: now_ms (),135 + content: canonicalize (content),74 141 pub fn message (msg: Message, parent: Option <EntryId>) -> Self { pub fn message (msg: Message, parent: Option <EntryId>) -> Self {75 142 Self ::new(parent, EntryContent::Message(msg)) Self ::new(parent, EntryContent::Message(msg))
147 + pub fn compaction (parent: Option <EntryId>, detail: serde_json::Value) -> Self {150 + EntryContent::Meta {151 + kind: COMPACTION_KIND .to_string (),159 + pub fn is_compaction (& self) -> bool {160 + matches! (& self.content, EntryContent::Meta { kind, .. } if kind == COMPACTION_KIND )87 172 pub selected_idx: usize , pub selected_idx: usize ,
175 + impl Default for Branch {176 + fn default () -> Self {90 181 impl Branch {impl Branch {91 184 pub fn new () -> Self { pub fn new () -> Self {93 186 branch_id: BranchId::new(), branch_id: BranchId::new(),99 193 pub fn append (&mut self, entry: Entry) -> usize { pub fn append (&mut self, entry: Entry) -> usize {100 194 self.entries.push (entry); self.entries.push (entry);101 195 self.selected_idx = self.entries.len ().saturating_sub (1 ); self.selected_idx = self.entries.len ().saturating_sub (1 );102 196 self.selected_idx self.selected_idx105 201 pub fn selected_entry (& self) -> Option <& Entry> { pub fn selected_entry (& self) -> Option <& Entry> {106 202 self.entries.get (self.selected_idx) self.entries.get (self.selected_idx)120 216 pub compaction_boundary: Option <EntryId>, pub compaction_boundary: Option <EntryId>,
219 + impl Default for Session {220 + fn default () -> Self {123 225 impl Session {impl Session {124 228 pub fn new () -> Self { pub fn new () -> Self {126 230 id: SessionId::new(), id: SessionId::new(),133 239 pub fn active_branch (& self) -> & Branch { pub fn active_branch (& self) -> & Branch {134 240 & self.branches[self.active_branch_idx] & self.branches[self.active_branch_idx]137 244 pub fn active_branch_mut (&mut self) -> &mut Branch { pub fn active_branch_mut (&mut self) -> &mut Branch {138 245 &mut self.branches[self.active_branch_idx] &mut self.branches[self.active_branch_idx]141 249 pub fn append_to_active (&mut self, entry: Entry) { pub fn append_to_active (&mut self, entry: Entry) {142 250 let branch = self.active_branch_mut (); let branch = self.active_branch_mut ();143 251 branch.append (entry); branch.append (entry);146 256 pub fn selected_id (& self) -> Option <EntryId> { pub fn selected_id (& self) -> Option <EntryId> {147 257 self.active_branch ().selected_entry ().map (|e| e.id) self.active_branch ().selected_entry ().map (|e| e.id)
262 + pub fn append_compaction (&mut self, detail: serde_json::Value) -> Entry {263 + let entry = Entry::compaction(self.selected_id (), detail);264 + self.compaction_boundary = Some (entry.id);265 + self.append_to_active (entry.clone ());270 + fn entries_by_id (& self) -> HashMap<EntryId, & Entry> {273 + .flat_map (|branch| branch.entries.iter ())274 + .map (|entry| (entry.id, entry))280 + fn ancestry (& self, at: EntryId) -> Option <Vec <Entry>> {281 + let known = self.entries_by_id ();282 + let mut chain = Vec ::new();283 + let mut cursor = Some (at);284 + while let Some (id) = cursor {285 + let entry = known.get (& id)? ;286 + chain.push ((* entry).clone ());287 + cursor = entry.parent;303 + pub fn fork_at (& self, at: EntryId) -> Result <Self > {304 + let entries = self.ancestry (at).ok_or_else (|| SmithError::Session {305 + code: "ENTRY_NOT_FOUND" .to_string (),306 + message: format! ("entry {at} is not part of session {}" , self.id),309 + .compaction_boundary310 + .filter (|id| entries.iter ().any (|entry| entry.id == * id));311 + let selected_idx = entries.len ().saturating_sub (1 );313 + id: SessionId::new(),314 + branches: vec! [Branch {315 + branch_id: BranchId::new(),319 + active_branch_idx: 0 ,320 + compaction_boundary: boundary,326 + pub fn header (& self) -> SessionHeader {328 + session_id: self.id,329 + branch_id: self.active_branch ().branch_id,154 342 pub fn from_frames (frames: & [crate::frame::Frame]) -> Self { pub fn from_frames (frames: & [crate::frame::Frame]) -> Self {155 - let mut session = Self ::new();156 - let mut restored : Vec <Entry> = Vec ::new();343 + let mut header = None ;344 + let mut stored : Vec <Entry> = Vec ::new();345 + let mut boundary = None ;157 346 for frame in frames { for frame in frames {158 - if let crate ::frame::Frame::Known { entry } = frame {159 - if let EntryContent::Meta { kind, .. } = & entry.content {160 - if kind == "compaction" {161 - session.compaction_boundary = Some (entry.id);348 + crate ::frame::Frame::Header { header: found } => header = Some (* found),349 + crate ::frame::Frame::Known { entry } => {350 + if entry.is_compaction () {351 + boundary = Some (entry.id);
353 + stored.push (entry.clone ());164 - restored.push (entry.clone ());355 + crate ::frame::Frame::Unknown { .. } => {}167 - let branch = session.active_branch_mut ();168 - branch.entries = restored;169 - branch.selected_idx = branch.entries.len ().saturating_sub (1 );358 + Self ::from_entries(header, & stored, boundary)363 + header: Option <SessionHeader>,365 + boundary: Option <EntryId>,367 + let mut session = Self ::new();368 + if let Some (header) = header {369 + session.id = header.session_id;370 + session.active_branch_mut ().branch_id = header.branch_id;372 + session.compaction_boundary = boundary;373 + if stored.is_empty () {376 + let parents: HashSet<EntryId> = stored.iter ().filter_map (|entry| entry.parent).collect ();377 + let known: HashMap<EntryId, & Entry> = 378 + stored.iter ().map (|entry| (entry.id, entry)).collect ();379 + let last_id = stored[stored.len () - 1 ].id;380 + let mut branches = Vec ::new();381 + let mut active_branch_idx = 0 ;382 + for leaf in stored.iter ().filter (|entry| ! parents.contains (& entry.id)) {383 + let mut entries = Vec ::new();384 + let mut cursor = Some (leaf.id);386 + while let Some (id) = cursor {387 + match known.get (& id) {389 + entries.push ((* entry).clone ());390 + cursor = entry.parent;396 + let selected_idx = entries.len ().saturating_sub (1 );397 + let is_active = leaf.id == last_id;399 + active_branch_idx = branches.len ();401 + branches.push (Branch {405 + branch_id: if is_active {406 + session.active_branch ().branch_id408 + BranchId::from(leaf.id.as_uuid ())414 + session.branches = branches;415 + session.active_branch_idx = active_branch_idx;
422 + clippy::unwrap_used,424 + reason = "tests may panic on invariant violations" 428 + use crate ::frame::Frame;429 + use smith::message::Role;431 + fn message (text: &str , parent: Option <EntryId>) -> Entry {432 + Entry::message(Message::with_text(Role::User, text), parent)435 + fn text_of (entry: & Entry) -> String {436 + match & entry.content {437 + EntryContent::Message(m) => format! ("{}" , m.blocks.len ()),438 + EntryContent::Meta { kind, .. } => kind.clone (),439 + other => panic! ("unexpected content {other:?}" ),443 + fn frames (session: & Session) -> Vec <Frame> {444 + let mut frames = vec! [Frame::Header {445 + header: session.header (),452 + .map (|entry| Frame::Known {453 + entry: entry.clone (),460 + fn sibling_entries_restore_as_separate_branches () {461 + let root = message ("root" , None );462 + let first = message ("first" , Some (root.id));463 + let second = message ("second" , Some (root.id));464 + let stored = vec! [root.clone (), first.clone (), second.clone ()];465 + let header = SessionHeader {466 + session_id: SessionId::new(),467 + branch_id: BranchId::new(),469 + let session = Session::from_entries(Some (header), & stored, None );470 + assert_eq! (session.branches.len (), 2 );473 + assert_eq! (session.selected_id (), Some (second.id));474 + assert_eq! (session.active_branch ().branch_id, header.branch_id);475 + let ids: Vec <EntryId> = session479 + .map (|entry| entry.id)481 + assert_eq! (ids, vec! [root.id, second.id]);482 + let sibling = & session.branches[1 - session.active_branch_idx];484 + sibling.entries.iter ().map (|e| e.id).collect::<Vec <_ >>(),485 + vec! [root.id, first.id]488 + let again = Session::from_entries(Some (header), & stored, None );489 + assert_eq! (again, session);493 + fn fork_preserves_ids_order_leaf_and_compaction_boundary () {494 + let mut session = Session::new();495 + let root = message ("root" , None );496 + session.append_to_active (root.clone ());497 + let boundary = session.append_compaction (serde_json::json! ({"summarized" : 1 }));498 + let after = message ("after" , Some (boundary.id));499 + session.append_to_active (after.clone ());501 + let forked = session.fork_at (boundary.id).unwrap ();502 + assert_ne! (forked.id, session.id);508 + .map (|entry| entry.id)509 + .collect::<Vec <_ >>(),510 + vec! [root.id, boundary.id]512 + assert_eq! (forked.selected_id (), Some (boundary.id));513 + assert_eq! (forked.compaction_boundary, Some (boundary.id));520 + .collect::<Vec <_ >>(),521 + vec! ["1" .to_string (), COMPACTION_KIND .to_string ()]525 + let earlier = session.fork_at (root.id).unwrap ();526 + assert_eq! (earlier.compaction_boundary, None );527 + assert_eq! (earlier.active_branch ().entries.len (), 1 );530 + assert_eq! (session.active_branch ().entries.len (), 3 );531 + assert_eq! (session.selected_id (), Some (after.id));535 + fn tool_use_json_inside_messages_encodes_identically () {536 + let call_id = smith::id::ToolCallId::new();537 + let block = |input: serde_json::Value| {538 + let mut message = Message::with_text(Role::Assistant, "call" );539 + message.add_block (smith::message::ContentBlock::ToolUse {540 + name: "write" .to_string (),546 + let mut first = Entry::message(547 + block (serde_json::json! ({"path" : "p" , "content" : "c" })),550 + let mut second = Entry::message(551 + block (serde_json::json! ({"content" : "c" , "path" : "p" })),555 + second.id = first.id;556 + second.timestamp_ms = first.timestamp_ms;557 + if let (EntryContent::Message(a), EntryContent::Message(b)) = 558 + (&mut first.content, &mut second.content)561 + b.timestamp_ms = a.timestamp_ms;563 + let encode = |entry: & Entry| {565 + entry: entry.clone (),570 + assert_eq! (encode (& first), encode (& second));574 + fn fork_rejects_unknown_entries () {575 + let session = Session::new();576 + let err = session.fork_at (EntryId::new()).unwrap_err ();577 + assert_eq! (err.code (), "ENTRY_NOT_FOUND" );581 + fn compaction_boundary_survives_a_frame_round_trip () {582 + let mut session = Session::new();583 + session.append_to_active (message ("root" , None ));584 + let boundary = session.append_compaction (serde_json::json! ({}));585 + let restored = Session::from_frames(& frames (& session));586 + assert_eq! (restored.compaction_boundary, Some (boundary.id));587 + assert_eq! (restored.id, session.id);589 + restored.active_branch ().branch_id,590 + session.header ().branch_idsmith-core/src/store.rs Modified +512 / −172 text lines
4 - use crate ::config::Config;5 - use crate ::frame::{Frame, HEADER_LEN , write_frame};4 + use crate ::frame::{Frame, Recovery, read_frames, write_frame};5 + use crate ::session::Session;6 + use smith::config::Config;6 7 use smith::error::{Result , SmithError};use smith::error::{Result , SmithError};
8 + use smith::id::EntryId;7 9 use std::fs::{File, OpenOptions};use std::fs::{File, OpenOptions};8 - use std::io::{BufReader, Read , Seek, SeekFrom, Write};10 + use std::io::{BufReader, Seek, SeekFrom, Write};9 11 use std::path::{Path, PathBuf};use std::path::{Path, PathBuf};28 + fn acquire (path: & Path) -> Result <Self > {29 + if let Some (parent) = path.parent ()30 + && ! parent.as_os_str ().is_empty ()32 + std::fs::create_dir_all(parent).map_err (io_err ("STORE_MKDIR" ))? ;34 + let file = OpenOptions::new()39 + .open (lock_path (path))40 + .map_err (io_err ("STORE_LOCK_OPEN" ))? ;41 + fs2::FileExt::lock_exclusive(& file).map_err (io_err ("STORE_LOCK" ))? ;46 + impl Drop for SessionLock {49 + let _ = fs2::FileExt::unlock(& self.file);54 + fn lock_path (path: & Path) -> PathBuf {55 + let mut name = path.as_os_str ().to_os_string ();16 67 pub struct SessionWriter {pub struct SessionWriter {17 68 file: File, file: File,18 69 config: Config, config: Config,19 70 path: PathBuf, path: PathBuf,22 75 impl SessionWriter {impl SessionWriter {24 81 pub fn open <P: AsRef <Path>>(path: P, config: Config) -> Result <Self > { pub fn open <P: AsRef <Path>>(path: P, config: Config) -> Result <Self > {25 - config.validate ().map_err (|e| SmithError::Config {26 - field: "store" .to_string (),82 + Self ::open_with_recovery(path, config).map (|(writer, _)| writer)87 + fn open_with_recovery <P: AsRef <Path>>(path: P, config: Config) -> Result <(Self , Recovery)> {29 88 let path = path.as_ref ().to_path_buf (); let path = path.as_ref ().to_path_buf ();30 - if let Some (parent) = path.parent () {31 - if ! parent.as_os_str ().is_empty () {32 - std::fs::create_dir_all(parent).map_err (io_err ("STORE_MKDIR" ))? ;91 + let lock = SessionLock::acquire(& path)? ;92 + Self ::attach(path, config, lock)96 + fn attach (path: PathBuf, config: Config, lock: SessionLock) -> Result <(Self , Recovery)> {35 99 let mut file = OpenOptions::new() let mut file = OpenOptions::new()36 100 .read (true ) .read (true )37 101 .write (true ) .write (true )39 103 .truncate (false ) .truncate (false )40 104 .open (& path) .open (& path)41 105 .map_err (io_err ("STORE_OPEN" ))? ; .map_err (io_err ("STORE_OPEN" ))? ;43 - file.lock_exclusive ().map_err (io_err ("STORE_LOCK" ))? ;45 - let good_end = scan_and_fix_tail (&mut file, config.max_frame_bytes)? ;46 - file.seek (SeekFrom::Start(good_end))108 + let recovery = walk_file (& file, config.max_frame_bytes)? ;109 + let len = file.metadata ().map_err (io_err ("STORE_STAT" ))? .len ();110 + if recovery.good_end < len {111 + file.set_len (recovery.good_end)112 + .map_err (io_err ("STORE_TRUNCATE" ))? ;114 + file.seek (SeekFrom::Start(recovery.good_end))47 115 .map_err (io_err ("STORE_SEEK" ))? ; .map_err (io_err ("STORE_SEEK" ))? ;48 - Ok (Self { file, config, path })54 134 pub fn append_frame (&mut self, frame: & Frame) -> Result <()> { pub fn append_frame (&mut self, frame: & Frame) -> Result <()> {55 135 let bytes = frame.encode (self.config.max_frame_bytes)? ; let bytes = frame.encode (self.config.max_frame_bytes)? ;56 136 self.file.write_all (& bytes).map_err (io_err ("STORE_WRITE" ))? ; self.file.write_all (& bytes).map_err (io_err ("STORE_WRITE" ))? ;62 143 pub fn path (& self) -> & Path { pub fn path (& self) -> & Path {63 144 & self.path & self.path67 - impl Drop for SessionWriter {70 - let _ = fs2::FileExt::unlock(& self.file);150 + pub struct OpenSession {152 + pub session: Session,154 + pub writer: SessionWriter,156 + pub recovery: Recovery,79 - pub fn load_session (path: & Path, max_frame_bytes: usize ) -> Result <Vec <Frame>> {170 + pub fn open_session (path: & Path, config: Config) -> Result <OpenSession> {171 + let (mut writer, recovery) = SessionWriter::open_with_recovery(path, config)? ;172 + let has_header = recovery175 + .any (|frame| matches! (frame, Frame::Header { .. }));176 + let session = if has_header {177 + Session::from_frames(& recovery.frames)178 + } else if recovery.frames.is_empty () && recovery.damage.is_empty () {179 + let session = Session::new();180 + writer.append_frame (& Frame::Header {181 + header: session.header (),185 + return Err (SmithError::Session {186 + code: "SESSION_HEADER_MISSING" .to_string (),187 + message: format! ("{} holds frames but no session header" , path.display ()),207 + pub fn create_session (path: & Path, session: & Session, config: Config) -> Result <OpenSession> {208 + let lock = SessionLock::acquire(path)? ;209 + if std::fs::metadata(path).is_ok_and (|meta| meta.len () > 0 ) {210 + return Err (SmithError::Session {211 + code: "SESSION_EXISTS" .to_string (),212 + message: format! ("{} already holds a session" , path.display ()),215 + let tmp = path.with_extension ("smith-create.tmp" );217 + let mut out = File::create(& tmp).map_err (io_err ("CREATE_TMP" ))? ;221 + header: session.header (),223 + config.max_frame_bytes,225 + for entry in & session.active_branch ().entries {229 + entry: entry.clone (),231 + config.max_frame_bytes,234 + out.sync_all ().map_err (io_err ("CREATE_SYNC" ))? ;236 + std::fs::rename(& tmp, path).map_err (io_err ("CREATE_PUBLISH" ))? ;237 + let (writer, recovery) = SessionWriter::attach(path.to_path_buf (), config, lock)? ;239 + session: Session::from_frames(& recovery.frames),256 + ) -> Result <OpenSession> {257 + let forked = source.fork_at (at)? ;258 + create_session (path, & forked, config)271 + pub fn load_session (path: & Path, max_frame_bytes: usize ) -> Result <Recovery> {80 272 let file = File::open(path).map_err (io_err ("STORE_OPEN" ))? ; let file = File::open(path).map_err (io_err ("STORE_OPEN" ))? ;81 273 let mut reader = BufReader::with_capacity(64 * 1024 , file); let mut reader = BufReader::with_capacity(64 * 1024 , file);82 - let mut frames = Vec ::new();84 - let mut header = [0 u8 ; HEADER_LEN ];85 - match read_exact_or_eof (&mut reader, &mut header) {90 - let declared = u32 ::from_le_bytes(header) as usize ;91 - if declared > max_frame_bytes {93 - let mut remaining = declared as u64 ;98 - let chunk = remaining.min (64 * 1024 ) as usize ;99 - let mut sink = vec! [0 u8 ; chunk];100 - match reader.read_exact (&mut sink) {101 - Ok (()) => remaining -= chunk as u64 ,102 - Err (_ ) => return Ok (frames), 107 - let mut chunk = vec! [0 u8 ; declared];108 - match reader.read_exact (&mut chunk) {109 - Ok (()) => frames.push (Frame::decode_payload(chunk)),110 - Err (_ ) => return Ok (frames), 274 + Ok (read_frames (&mut reader, max_frame_bytes))119 - pub fn repair_session (path: & Path, max_frame_bytes: usize ) -> Result <Vec <Frame>> {120 - let frames = load_session (path, max_frame_bytes)? ;287 + pub fn repair_session (path: & Path, max_frame_bytes: usize ) -> Result <Recovery> {288 + let _lock = SessionLock::acquire(path)? ;289 + let recovery = load_session (path, max_frame_bytes)? ;121 290 let tmp = path.with_extension ("smith-repair.tmp" ); let tmp = path.with_extension ("smith-repair.tmp" );123 292 let mut out = File::create(& tmp).map_err (io_err ("REPAIR_CREATE" ))? ; let mut out = File::create(& tmp).map_err (io_err ("REPAIR_CREATE" ))? ;124 - for frame in & frames {293 + for frame in & recovery . frames {125 294 write_frame (&mut out, frame, max_frame_bytes)? ; write_frame (&mut out, frame, max_frame_bytes)? ;127 296 out.sync_all ().map_err (io_err ("REPAIR_SYNC" ))? ; out.sync_all ().map_err (io_err ("REPAIR_SYNC" ))? ;129 298 std::fs::rename(& tmp, path).map_err (io_err ("REPAIR_PUBLISH" ))? ; std::fs::rename(& tmp, path).map_err (io_err ("REPAIR_PUBLISH" ))? ;135 - fn scan_and_fix_tail (file: & File, max_frame_bytes: usize ) -> Result <u64 > {136 - let len = file.metadata ().map_err (io_err ("STORE_STAT" ))? .len ();138 - BufReader::with_capacity(64 * 1024 , file.try_clone ().map_err (io_err ("STORE_OPEN" ))? );139 - let mut good_end: u64 = 0 ;141 - let header_start = reader.stream_position ().map_err (io_err ("STORE_READ" ))? ;142 - let mut header = [0 u8 ; HEADER_LEN ];144 - if ! read_exact_or_eof (&mut reader, &mut header).unwrap_or (false ) {147 - let declared = u32 ::from_le_bytes(header) as usize ;148 - let total = declared as u64 + HEADER_LEN as u64 ;149 - let mut remaining = total;150 - let mut complete = true ;151 - while remaining > 0 {152 - let chunk = remaining.min (64 * 1024 ) as usize ;153 - let mut sink = vec! [0 u8 ; chunk];154 - match reader.read_exact (&mut sink) {155 - Ok (()) => remaining -= chunk as u64 ,166 - let _ = max_frame_bytes; 167 - good_end = header_start + total;170 - file.set_len (good_end).map_err (io_err ("STORE_TRUNCATE" ))? ;177 - fn read_exact_or_eof <R: Read>(reader: &mut R, buf: &mut [u8 ]) -> std::io::Result <bool > {179 - while filled < buf.len () {180 - match reader.read (&mut buf[filled.. ]) {185 - return Err (std::io::Error::new(186 - std::io::ErrorKind::UnexpectedEof,190 - Ok (n) => filled += n,191 - Err (e) if e.kind () == std::io::ErrorKind::Interrupted => continue ,192 - Err (e) => return Err (e),307 + fn walk_file (file: & File, max_frame_bytes: usize ) -> Result <Recovery> {308 + let mut handle = file.try_clone ().map_err (io_err ("STORE_OPEN" ))? ;310 + .seek (SeekFrom::Start(0 ))311 + .map_err (io_err ("STORE_SEEK" ))? ;312 + let mut reader = BufReader::with_capacity(64 * 1024 , handle);313 + Ok (read_frames (&mut reader, max_frame_bytes))198 316 fn io_err (code: &'static str ) -> impl Fn(std::io::Error) -> SmithError {fn io_err (code: &'static str ) -> impl Fn(std::io::Error) -> SmithError {205 323 #[cfg(test)]#[cfg(test)]206 - #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]325 + clippy::unwrap_used,327 + reason = "tests may panic on invariant violations" 207 329 mod tests {mod tests {208 330 use super ::* ; use super ::* ;209 331 use crate ::session::{Entry, EntryContent, Session}; use crate ::session::{Entry, EntryContent, Session};223 345 Frame::Known { entry: entry (text) } Frame::Known { entry: entry (text) }
348 + fn text_of (frame: & Frame) -> String {350 + Frame::Known { entry } => match & entry.content {351 + EntryContent::Message(m) => match & m.blocks[0 ] {352 + ContentBlock::Text(t) => t.clone (),353 + other => panic! ("unexpected block {other:?}" ),355 + other => panic! ("unexpected content {other:?}" ),357 + other => panic! ("unexpected frame {other:?}" ),227 362 fn append_load_round_trip_preserves_entries () { fn append_load_round_trip_preserves_entries () {228 363 let path = tmp_path ("round_trip.smh" ); let path = tmp_path ("round_trip.smh" );229 364 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);230 365 let cfg = Config::default_valid(); let cfg = Config::default_valid();
366 + let first = entry ("one" );367 + let second = Entry::message(Message::with_text(Role::User, "two" ), Some (first.id));232 369 let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap (); let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();233 - w.append_frame (& frame ("one" )).unwrap ();234 - w.append_frame (& frame ("two" )).unwrap ();370 + w.append_frame (& Frame::Known {371 + entry: first.clone (),374 + w.append_frame (& Frame::Known {375 + entry: second.clone (),236 - let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();379 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap (). frames ;237 380 assert_eq! (frames.len (), 2 ); assert_eq! (frames.len (), 2 );238 381 let session = Session::from_frames(& frames); let session = Session::from_frames(& frames);239 - assert_eq! (session.active_branch ().entries.len (), 2 );
240 382 assert_eq! ( assert_eq! (241 - session.active_branch ().entries[1 ].id,242 - session.selected_id ().unwrap ()388 + .collect::<Vec <_ >>(),389 + vec! [first.id, second.id]
391 + assert_eq! (session.selected_id (), Some (second.id));244 392 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);260 408 .encode (cfg.max_frame_bytes) .encode (cfg.max_frame_bytes)261 409 .unwrap (); .unwrap ();262 - let mut torn = good. clone ( ) ;410 + let mut torn = good;263 411 torn.extend_from_slice (& [0x10 , 0x00 , 0x00 , 0x00 , 0xAA , 0xBB ]); torn.extend_from_slice (& [0x10 , 0x00 , 0x00 , 0x00 , 0xAA , 0xBB ]);264 412 std::fs::write(& path, & torn).unwrap (); std::fs::write(& path, & torn).unwrap ();267 415 let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap (); let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();268 416 w.append_frame (& frame ("after" )).unwrap (); w.append_frame (& frame ("after" )).unwrap ();270 - let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();418 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap (). frames ;271 419 let texts: Vec <String > = frames let texts: Vec <String > = frames273 421 .filter_map (|f| match f { .filter_map (|f| match f {290 438 let path = tmp_path ("loader_torn.smh" ); let path = tmp_path ("loader_torn.smh" );291 439 let cfg = Config::default_valid(); let cfg = Config::default_valid();292 440 let good = frame ("a" ).encode (cfg.max_frame_bytes).unwrap (); let good = frame ("a" ).encode (cfg.max_frame_bytes).unwrap ();293 - let mut bytes = good. clone ( ) ;441 + let mut bytes = good;294 442 bytes.extend_from_slice (& [0xFF , 0xFF ]); bytes.extend_from_slice (& [0xFF , 0xFF ]); 295 443 std::fs::write(& path, & bytes).unwrap (); std::fs::write(& path, & bytes).unwrap ();296 - let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();444 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap (). frames ;297 445 assert_eq! (frames.len (), 1 ); assert_eq! (frames.len (), 1 );298 446 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);
450 + fn reopening_a_multi_frame_session_keeps_every_frame () {451 + let path = tmp_path ("reopen_multi.smh" );452 + let _ = std::fs::remove_file(& path);453 + let cfg = Config::default_valid();455 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();456 + w.append_frame (& frame ("one" )).unwrap ();457 + w.append_frame (& frame ("two" )).unwrap ();461 + let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();462 + w.append_frame (& frame ("three" )).unwrap ();464 + let recovery = load_session (& path, cfg.max_frame_bytes).unwrap ();465 + assert_eq! (recovery.frames.len (), 3 );466 + assert! (recovery.damage.is_empty ());467 + assert_eq! (recovery.torn_tail_at, None );468 + let _ = std::fs::remove_file(& path);302 472 fn oversized_complete_frame_is_skipped_and_following_frames_reachable () { fn oversized_complete_frame_is_skipped_and_following_frames_reachable () {303 473 let path = tmp_path ("oversized_skip.smh" ); let path = tmp_path ("oversized_skip.smh" );306 476 bytes.extend_from_slice (& vec! [0xAB_ u8 ; 5000 ]); bytes.extend_from_slice (& vec! [0xAB_ u8 ; 5000 ]);307 477 bytes.extend_from_slice (& frame ("tail" ).encode (1 << 20 ).unwrap ()); bytes.extend_from_slice (& frame ("tail" ).encode (1 << 20 ).unwrap ());308 478 std::fs::write(& path, & bytes).unwrap (); std::fs::write(& path, & bytes).unwrap ();309 - let frames = load_session (& path, 1024 ).unwrap ();310 - assert_eq! (frames.len (), 1 );311 - assert! (matches! (frames[0 ], Frame::Known { .. }));479 + let recovery = load_session (& path, 1024 ).unwrap ();480 + assert_eq! (recovery . frames.len (), 1 );481 + assert! (matches! (recovery . frames[0 ], Frame::Known { .. }));482 + assert_eq! (recovery.damage[0 ].code (), "FRAME_TOO_LARGE" );312 483 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);317 488 let path = tmp_path ("repair.smh" ); let path = tmp_path ("repair.smh" );318 489 let cfg = Config::default_valid(); let cfg = Config::default_valid();319 490 let good = frame ("a" ).encode (cfg.max_frame_bytes).unwrap (); let good = frame ("a" ).encode (cfg.max_frame_bytes).unwrap ();320 - let mut bytes = good. clone ( ) ;491 + let mut bytes = good;321 492 bytes.extend_from_slice (& frame ("b" ).encode (cfg.max_frame_bytes).unwrap ()[.. 6 ]); bytes.extend_from_slice (& frame ("b" ).encode (cfg.max_frame_bytes).unwrap ()[.. 6 ]);322 493 std::fs::write(& path, & bytes).unwrap (); std::fs::write(& path, & bytes).unwrap ();323 494 let before = std::fs::metadata(& path).unwrap ().len (); let before = std::fs::metadata(& path).unwrap ().len ();324 - let frames = repair_session (& path, cfg.max_frame_bytes).unwrap ();325 - assert_eq! (frames.len (), 1 );495 + let recovery = repair_session (& path, cfg.max_frame_bytes).unwrap ();496 + assert_eq! (recovery . frames.len (), 1 );497 + assert_eq! (recovery.torn_tail_at, Some (before - 6 ));326 498 let after = std::fs::metadata(& path).unwrap ().len (); let after = std::fs::metadata(& path).unwrap ().len ();327 499 assert! (after < before); assert! (after < before);328 - assert_eq! ( load_session (& path, cfg.max_frame_bytes). unwrap ( ) . len ( ) , 1 ) ; 501 + load_session (& path, cfg.max_frame_bytes)329 507 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);349 527 let err = w.append_frame (& Frame::Known { entry: big }).unwrap_err (); let err = w.append_frame (& Frame::Known { entry: big }).unwrap_err ();350 528 assert_eq! (err.code (), "FRAME_TOO_LARGE" ); assert_eq! (err.code (), "FRAME_TOO_LARGE" );352 - assert_eq! ( load_session (& path, cfg.max_frame_bytes). unwrap ( ) . len ( ) , 1 ) ; 531 + load_session (& path, cfg.max_frame_bytes)353 537 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);358 542 let path = tmp_path ("locked.smh" ); let path = tmp_path ("locked.smh" );359 543 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);360 544 let cfg = Config::default_valid(); let cfg = Config::default_valid();361 - let _w1 = SessionWriter::open(& path, cfg. clone ( )) .unwrap ();545 + let writer = SessionWriter::open(& path, cfg).unwrap ();364 548 let probe = OpenOptions::new() let probe = OpenOptions::new()365 549 .read (true ) .read (true )366 550 .write (true ) .write (true )551 + .open (lock_path ( & path)) 368 552 .unwrap (); .unwrap ();370 - assert! (probe . try_lock_exclusive ().is_err ());553 + assert! (fs2 :: FileExt :: try_lock_exclusive(& probe ).is_err ());555 + assert! (fs2::FileExt::try_lock_exclusive(& probe).is_ok ());372 556 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);
560 + fn repair_waits_for_a_live_writer_and_keeps_its_entries () {561 + let path = tmp_path ("repair_race.smh" );562 + let _ = std::fs::remove_file(& path);563 + let _ = std::fs::remove_file(lock_path (& path));564 + let cfg = Config::default_valid();565 + let mut writer = SessionWriter::open(& path, cfg.clone ()).unwrap ();566 + writer.append_frame (& frame ("one" )).unwrap ();568 + let repair_path = path.clone ();569 + let limit = cfg.max_frame_bytes;570 + let repair = std::thread::spawn(move || repair_session (& repair_path, limit).unwrap ());574 + std::thread::sleep(std::time::Duration::from_millis(150 ));575 + writer.append_frame (& frame ("two" )).unwrap ();578 + let recovery = repair.join ().unwrap ();579 + assert_eq! (recovery.frames.len (), 2 );580 + let loaded = load_session (& path, cfg.max_frame_bytes).unwrap ();581 + let texts: Vec <String > = loaded.frames.iter ().map (text_of).collect ();582 + assert_eq! (texts, vec! ["one" .to_string (), "two" .to_string ()]);583 + let _ = std::fs::remove_file(& path);584 + let _ = std::fs::remove_file(lock_path (& path));376 588 fn unknown_frames_survive_write_and_load () { fn unknown_frames_survive_write_and_load () {377 589 let path = tmp_path ("unknown_frames.smh" ); let path = tmp_path ("unknown_frames.smh" );378 590 let _ = std::fs::remove_file(& path); let _ = std::fs::remove_file(& path);379 591 let cfg = Config::default_valid(); let cfg = Config::default_valid();380 592 let unknown = Frame::Unknown { let unknown = Frame::Unknown {382 - raw_bytes: vec! [1 , 2 , 3 , 4 , 5 , 6 ],595 + payload: vec! [1 , 2 , 3 , 4 , 5 , 6 ],385 598 let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap (); let mut w = SessionWriter::open(& path, cfg.clone ()).unwrap ();386 599 w.append_frame (& unknown).unwrap (); w.append_frame (& unknown).unwrap ();387 600 w.append_frame (& frame ("known" )).unwrap (); w.append_frame (& frame ("known" )).unwrap ();389 - let frames = load_session (& path, cfg.max_frame_bytes).unwrap ();602 + let frames = load_session (& path, cfg.max_frame_bytes).unwrap (). frames ;390 603 assert_eq! (frames.len (), 2 ); assert_eq! (frames.len (), 2 );391 604 match & frames[0 ] { match & frames[0 ] {392 605 Frame::Unknown { Frame::Unknown {396 - assert_eq! (raw_bytes , & vec! [1 , 2 , 3 , 4 , 5 , 6 ]);397 - assert_eq! (* declared_length, 6 );610 + assert_eq! (payload , & vec! [1 , 2 , 3 , 4 , 5 , 6 ]);611 + assert_eq! ((* kind, * version), (0x4242 , 3 ));399 613 other => panic! ("expected unknown frame, got {other:?}" ), other => panic! ("expected unknown frame, got {other:?}" ),420 634 let session_path = dir.join ("e2e.smh" ); let session_path = dir.join ("e2e.smh" );421 635 let _ = std::fs::remove_file(& session_path); let _ = std::fs::remove_file(& session_path);422 636 let cfg = Config::default_valid(); let cfg = Config::default_valid();424 - let writer = SessionWriter::open(& session_path, cfg.clone ()).unwrap ();425 - let mut ts = crate ::tools::ToolSession::with_writer(workdir.clone (), writer);639 + let opened = open_session (& session_path, cfg.clone ()).unwrap ();640 + opened_id = opened.session.id;641 + let mut ts = crate ::tools::ToolSession::with_session(426 646 ts.invoke ( ts.invoke (428 - serde_json::json! ({"path" : "out/hello.txt" , "content" : "hi" }),648 + & serde_json::json! ({"path" : "out/hello.txt" , "content" : "hi" }),430 650 .unwrap (); .unwrap ();431 - ts.invoke ("read" , serde_json::json! ({"path" : "out/hello.txt" }))651 + ts.invoke ("read" , & serde_json::json! ({"path" : "out/hello.txt" }))432 652 .unwrap (); .unwrap ();434 - let frames = load_session (& session_path, cfg.max_frame_bytes). unwrap ( ) ; 435 - assert_eq! (frames.len (), 4 ); 654 + let frames = load_session (& session_path, cfg.max_frame_bytes)657 + assert_eq! (frames.len (), 5 ); 436 658 let restored = Session::from_frames(& frames); let restored = Session::from_frames(& frames);
659 + assert_eq! (restored.id, opened_id);437 660 assert_eq! (restored.active_branch ().entries.len (), 4 ); assert_eq! (restored.active_branch ().entries.len (), 4 );439 662 let kinds: Vec <&str > = restored let kinds: Vec <&str > = restored456 679 let _ = std::fs::remove_dir_all(& dir); let _ = std::fs::remove_dir_all(& dir);
683 + fn reopened_session_keeps_its_identity_and_replays_identically () {684 + let path = tmp_path ("identity.smh" );685 + let _ = std::fs::remove_file(& path);686 + let cfg = Config::default_valid();688 + let mut opened = open_session (& path, cfg.clone ()).unwrap ();689 + opened.writer.append_frame (& frame ("one" )).unwrap ();694 + let opened = open_session (& path, cfg.clone ()).unwrap ();698 + let opened = open_session (& path, cfg).unwrap ();701 + assert_eq! (first.id, created.id);703 + first.active_branch ().branch_id,704 + created.active_branch ().branch_id706 + assert_eq! (second.id, first.id);709 + let encode = |session: & Session| {710 + let mut bytes = Vec ::new();711 + ciborium::ser::into_writer(&crate ::trace::replay(session), &mut bytes).unwrap ();714 + assert_eq! (encode (& first), encode (& second));715 + let _ = std::fs::remove_file(& path);719 + fn forking_publishes_a_new_session_file_and_leaves_the_source_intact () {720 + let dir = tmp_path ("fork_dir" );721 + std::fs::create_dir_all(& dir).unwrap ();722 + let source_path = dir.join ("source.smh" );723 + let fork_path = dir.join ("fork.smh" );724 + let cfg = Config::default_valid();726 + let (source_session, boundary_id, leaf_id) = {727 + let mut opened = open_session (& source_path, cfg.clone ()).unwrap ();728 + let root = entry ("root" );729 + let root_id = root.id;730 + opened.session.append_to_active (root.clone ());733 + .append_frame (& Frame::Known { entry: root })735 + let boundary = opened737 + .append_compaction (serde_json::json! ({"kept" : 1 }));740 + .append_frame (& Frame::Known {741 + entry: boundary.clone (),744 + let tip = Entry::message(Message::with_text(Role::User, "after" ), Some (boundary.id));745 + let tip_id = tip.id;746 + opened.session.append_to_active (tip.clone ());749 + .append_frame (& Frame::Known { entry: tip })751 + assert_ne! (root_id, tip_id);752 + (opened.session, boundary.id, tip_id)757 + fork_session (& source_session, boundary_id, & fork_path, cfg.clone ()).unwrap ();758 + assert_ne! (forked.session.id, source_session.id);759 + assert_eq! (forked.session.selected_id (), Some (boundary_id));760 + assert_eq! (forked.session.compaction_boundary, Some (boundary_id));761 + assert! (forked.recovery.damage.is_empty ());767 + let reopened = open_session (& fork_path, cfg.clone ()).unwrap ();768 + assert_eq! (reopened.session.id, fork_id);769 + assert_eq! (reopened.session.selected_id (), Some (boundary_id));770 + assert_eq! (reopened.session.active_branch ().entries.len (), 2 );771 + assert_eq! (reopened.session.compaction_boundary, Some (boundary_id));776 + let source_again = open_session (& source_path, cfg.clone ()).unwrap ();777 + assert_eq! (source_again.session.id, source_session.id);778 + assert_eq! (source_again.session.selected_id (), Some (leaf_id));779 + assert_eq! (source_again.session.active_branch ().entries.len (), 3 );783 + let err = fork_session (& source_session, boundary_id, & fork_path, cfg).unwrap_err ();784 + assert_eq! (err.code (), "SESSION_EXISTS" );785 + let _ = std::fs::remove_dir_all(& dir);789 + fn session_file_without_header_is_rejected () {790 + let path = tmp_path ("headerless.smh" );791 + let cfg = Config::default_valid();792 + std::fs::write(& path, frame ("orphan" ).encode (cfg.max_frame_bytes).unwrap ()).unwrap ();793 + let err = open_session (& path, cfg).unwrap_err ();794 + assert_eq! (err.code (), "SESSION_HEADER_MISSING" );795 + let _ = std::fs::remove_file(& path);460 799 fn header_len_matches_protocol () { fn header_len_matches_protocol () {461 - assert_eq! (HEADER_LEN , 4 );800 + assert_eq! (crate :: frame :: HEADER_LEN , 4 );801 + assert_eq! (crate ::frame::BODY_PREFIX_LEN , 8 );smith-core/src/tools.rs Modified +631 / −118 text lines
4 4 use crate ::frame::{Frame, canonical_json};use crate ::frame::{Frame, canonical_json};5 5 use crate ::session::{Entry, EntryContent, Session};use crate ::session::{Entry, EntryContent, Session};6 6 use crate ::store::SessionWriter;use crate ::store::SessionWriter;
7 + use smith::config::Config;7 8 use smith::error::{Result , SmithError};use smith::error::{Result , SmithError};8 9 use smith::id::ToolCallId;use smith::id::ToolCallId;9 - use smith::tool::ToolMetadata;10 + use smith::tool::{ CancelHandle , ToolMetadata} ;10 11 use std::collections::HashMap;use std::collections::HashMap;11 12 use std::fs;use std::fs;12 13 use std::io::{BufRead, BufReader, Write};use std::io::{BufRead, BufReader, Write};17 18 const DEFAULT_OUTPUT_CAP : usize = 64 * 1024 ;const DEFAULT_OUTPUT_CAP : usize = 64 * 1024 ;18 19 const MAX_LIST_ENTRIES : usize = 1000 ;const MAX_LIST_ENTRIES : usize = 1000 ;19 20 const MAX_GREP_MATCHES : usize = 200 ;const MAX_GREP_MATCHES : usize = 200 ;20 - const MAX_EDIT_FILE_BYTES : usize = 8 * 1024 * 1024 ;21 + const MAX_EDIT_FILE_BYTES : u64 = 8 * 1024 * 1024 ;23 24 #[derive(Clone, Debug, Default)]#[derive(Clone, Debug, Default)]29 30 impl ToolRegistry {impl ToolRegistry {31 33 pub fn new () -> Self { pub fn new () -> Self {32 34 Self ::default() Self ::default()41 44 pub fn with_builtins () -> Self { pub fn with_builtins () -> Self {42 45 let mut reg = Self ::new(); let mut reg = Self ::new();43 46 for meta in builtin_tools () { for meta in builtin_tools () {51 55 pub fn builtin_tools () -> Vec <ToolMetadata> {pub fn builtin_tools () -> Vec <ToolMetadata> {52 56 let object = |required: & [&str ], props: serde_json::Value| { let object = |required: & [&str ], props: serde_json::Value| {53 57 serde_json::json! ({ serde_json::json! ({122 126 writer: Option <SessionWriter>, writer: Option <SessionWriter>,124 128 pub working_dir: PathBuf, pub working_dir: PathBuf,
130 + cancel: CancelHandle,133 + observed: HashMap<PathBuf, FileVersion>,137 + #[derive(Clone, Copy, PartialEq, Eq, Debug)]144 + fn of (path: & Path) -> Option <Self > {145 + let meta = fs::metadata(path).ok ()? ;146 + let modified_ms = meta149 + .duration_since (std::time::UNIX_EPOCH )154 + modified_ms: i64 ::try_from(modified_ms).unwrap_or (i64 ::MAX ),127 159 impl ToolSession {impl ToolSession {132 164 session: Session::new(), session: Session::new(),133 165 writer: None , writer: None ,134 166 working_dir: working_dir.into (), working_dir: working_dir.into (),
167 + config: Config::default_valid(),168 + cancel: CancelHandle::new(),169 + observed: HashMap::new(),139 - pub fn with_writer (working_dir: impl Into <PathBuf>, writer: SessionWriter) -> Self {175 + pub fn with_config (mut self, config: Config) -> Self {176 + self.config = config;182 + pub fn cancel_handle (& self) -> CancelHandle {188 + pub fn with_session (189 + working_dir: impl Into <PathBuf>,191 + writer: SessionWriter,141 195 writer: Some (writer), writer: Some (writer),142 196 ..Self ::new(working_dir) ..Self ::new(working_dir)153 212 pub fn validate (& self, name: &str , input: & serde_json::Value) -> Result <()> { pub fn validate (& self, name: &str , input: & serde_json::Value) -> Result <()> {154 213 let meta = self.registry.tools.get (name).ok_or_else (|| { let meta = self.registry.tools.get (name).ok_or_else (|| {155 214 tool_err ( tool_err (181 240 .get (key) .get (key)182 241 .and_then (|p| p.get ("type" )) .and_then (|p| p.get ("type" ))183 242 .and_then (|t| t.as_str ()) .and_then (|t| t.as_str ())
243 + && ! json_type_matches (expected, value)185 - if ! json_type_matches (expected, value) {186 246 return Err (tool_err ( return Err (tool_err (187 247 "VALIDATION" , "VALIDATION" ,188 248 format! ("field '{key}' for tool '{name}' must be of type {expected}" ), format! ("field '{key}' for tool '{name}' must be of type {expected}" ),202 - pub fn invoke (&mut self, name: &str , input: serde_json::Value) -> Result <ToolOutcome> {203 - self.validate (name, & input)? ;270 + pub fn invoke (&mut self, name: &str , input: & serde_json::Value) -> Result <ToolOutcome> {271 + self.validate (name, input)? ;272 + if self.cancel.is_cancelled () {273 + return Err (SmithError::Cancelled);204 275 let call_id = ToolCallId::new(); let call_id = ToolCallId::new();205 - let canonical_input = canonical_json (& input);276 + let canonical_input = canonical_json (input);206 277 let parent = self.session.selected_id (); let parent = self.session.selected_id ();208 - let effect = execute_file_effect (name, & canonical_input, & self.working_dir);278 + self.record_entry (Entry::new(280 + EntryContent::ToolCall {281 + name: name.to_string (),282 + input: canonical_input.clone (),286 + let effect = execute_effect (209 294 let ok = effect.is_ok (); let ok = effect.is_ok ();210 295 let output = match & effect { let output = match & effect {211 296 Ok (text) => text.clone (), Ok (text) => text.clone (),218 303 output: output.clone (), output: output.clone (),219 304 timestamp_ms: now_ms (), timestamp_ms: now_ms (),222 - self.record_entry (Entry::new(224 - EntryContent::ToolCall {225 - name: name.to_string (),226 - input: canonical_input,
231 306 self.record_entry (Entry::new( self.record_entry (Entry::new(232 307 self.session.selected_id (), self.session.selected_id (),233 308 EntryContent::ToolResult { EntryContent::ToolResult {314 + .map_err (|err| SmithError::RecordFailed {315 + tool: name.to_string (),316 + mutation_applied: ok && mutates_host (name),317 + message: err.to_string (),239 319 effect.map (move |_| outcome) effect.map (move |_| outcome)303 - fn execute_file_effect (384 + fn mutates_host (name: &str ) -> bool {385 + matches! (name, "write" | "edit" | "bash" )304 389 name: &str , name: &str ,305 390 input: & serde_json::Value, input: & serde_json::Value,306 391 working_dir: & Path, working_dir: & Path,
393 + cancel: & CancelHandle,394 + observed: &mut HashMap<PathBuf, FileVersion>,307 395 ) -> std::result::Result <String , SmithError> {) -> std::result::Result <String , SmithError> {308 396 let path_str = input.get ("path" ).and_then (|v| v.as_str ()).unwrap_or ("" ); let path_str = input.get ("path" ).and_then (|v| v.as_str ()).unwrap_or ("" );309 397 match name { match name {311 - let path = resolve_path (path_str, working_dir);312 - let offset = input.get ("offset" ).and_then (|v| v.as_u64 ()).unwrap_or (0 ) as usize ;315 - .and_then (|v| v.as_u64 ())316 - .map (|v| v.min (usize ::MAX as u64 ) as usize )317 - .unwrap_or (usize ::MAX );318 - let max_bytes = input320 - .and_then (|v| v.as_u64 ())321 - .map (|v| (v as usize ).min (HARD_OUTPUT_CAP ))322 - .unwrap_or (DEFAULT_OUTPUT_CAP );323 - read_bounded (& path, offset, limit, max_bytes)328 - .and_then (|v| v.as_str ())329 - .ok_or_else (|| tool_err ("VALIDATION" , "write requires string 'content'" ))? ;330 - let path = resolve_path (path_str, working_dir);331 - write_atomic (& path, content.as_bytes ())? ;332 - Ok (format! ("written {} bytes" , content.len ()))337 - .and_then (|v| v.as_str ())338 - .unwrap_or_default ();341 - .and_then (|v| v.as_str ())342 - .unwrap_or_default ();343 - let path = resolve_path (path_str, working_dir);344 - edit_exact (& path, old, new)398 + "bash" => run_bash (input, working_dir, config.tool_timeout_ms, cancel),399 + "read" => read_effect (input, resolve_path (path_str, working_dir), observed),400 + "write" => write_effect (input, resolve_path (path_str, working_dir), observed),401 + "edit" => edit_effect (input, resolve_path (path_str, working_dir), observed),346 402 "ls" => { "ls" => {347 - let dir = if path_str.is_empty () {348 - working_dir.to_path_buf ()350 - resolve_path (path_str, working_dir)352 - let mut names: Vec <String > = fs::read_dir(& dir)353 - .map_err (io_tool_err ("LS_ERROR" ))? 354 - .collect::<std::io::Result <Vec <_ >>>()355 - .map_err (io_tool_err ("LS_ERROR" ))? 357 - .map (|e| e.file_name ().to_string_lossy ().into_owned ())403 + let dir = directory_or (path_str, working_dir);405 + return Err (tool_err (407 + format! ("{} is not a directory" , dir.display ()),410 + let names = walk_relative (& dir, Some (1 ), config, cancel, "LS_ERROR" )? ;360 411 Ok (bounded_join (names, MAX_LIST_ENTRIES )) Ok (bounded_join (names, MAX_LIST_ENTRIES ))362 413 "find" => { "find" => {364 415 .get ("pattern" ) .get ("pattern" )365 416 .and_then (|v| v.as_str ()) .and_then (|v| v.as_str ())366 417 .unwrap_or_default (); .unwrap_or_default ();367 - let root = if path_str.is_empty () {368 - working_dir.to_path_buf ()370 - resolve_path (path_str, working_dir)372 - let mut names: Vec <String > = fs::read_dir(& root)373 - .map_err (io_tool_err ("FIND_ERROR" ))? 374 - .collect::<std::io::Result <Vec <_ >>>()375 - .map_err (io_tool_err ("FIND_ERROR" ))? 418 + let root = directory_or (path_str, working_dir);420 + return Err (tool_err (422 + format! ("{} is not a directory" , root.display ()),425 + let names = walk_relative (& root, None , config, cancel, "FIND_ERROR" )? 376 426 .into_iter () .into_iter ()377 - .map (|e| e.file_name ().to_string_lossy ().into_owned ())378 - .filter (|n| n.contains (pattern))427 + .filter (|name| pattern.is_empty () || name.contains (pattern))379 428 .collect (); .collect ();381 429 Ok (bounded_join (names, MAX_LIST_ENTRIES )) Ok (bounded_join (names, MAX_LIST_ENTRIES ))383 431 "grep" => { "grep" => {385 433 .get ("query" ) .get ("query" )386 434 .and_then (|v| v.as_str ()) .and_then (|v| v.as_str ())387 435 .unwrap_or_default (); .unwrap_or_default ();388 - let path = resolve_path (path_str, working_dir);389 - grep_bounded (& path , query)436 + let target = directory_or (path_str, working_dir);437 + if target.is_dir () {438 + grep_tree (& target, query, config, cancel)440 + grep_bounded (& target , query)391 443 _ => Err (tool_err ( _ => Err (tool_err (392 444 "TOOL_NOT_IMPLEMENTED" , "TOOL_NOT_IMPLEMENTED" ,
452 + input: & serde_json::Value,454 + observed: &mut HashMap<PathBuf, FileVersion>,455 + ) -> std::result::Result <String , SmithError> {456 + let count = |key: &str | {459 + .and_then (serde_json::Value::as_u64)460 + .map (|value| usize ::try_from(value).unwrap_or (usize ::MAX ))462 + let text = read_bounded (464 + count ("offset" ).unwrap_or (0 ),465 + count ("limit" ).unwrap_or (usize ::MAX ),466 + count ("max_bytes" ).map_or (DEFAULT_OUTPUT_CAP , |bytes| bytes.min (HARD_OUTPUT_CAP )),468 + remember (path, observed);474 + input: & serde_json::Value,476 + observed: &mut HashMap<PathBuf, FileVersion>,477 + ) -> std::result::Result <String , SmithError> {480 + .and_then (|value| value.as_str ())481 + .ok_or_else (|| tool_err ("VALIDATION" , "write requires string 'content'" ))? ;482 + write_atomic (& path, content.as_bytes ())? ;483 + remember (path, observed);484 + Ok (format! ("written {} bytes" , content.len ()))493 + input: & serde_json::Value,495 + observed: &mut HashMap<PathBuf, FileVersion>,496 + ) -> std::result::Result <String , SmithError> {497 + let text = |key: &str | input.get (key).and_then (|v| v.as_str ()).unwrap_or_default ();498 + if let Some (seen) = observed.get (& path)499 + && FileVersion::of(& path) != Some (* seen)501 + return Err (tool_err (504 + "{} changed since it was last read; read it again before editing" ,509 + let result = edit_exact (& path, text ("old_string" ), text ("new_string" ))? ;510 + remember (path, observed);515 + fn remember (path: PathBuf, observed: &mut HashMap<PathBuf, FileVersion>) {516 + if let Some (version) = FileVersion::of(& path) {517 + observed.insert (path, version);522 + fn directory_or (path_str: &str , working_dir: & Path) -> PathBuf {523 + if path_str.is_empty () {524 + working_dir.to_path_buf ()526 + resolve_path (path_str, working_dir)534 + fn walker (root: & Path, max_depth: Option <usize >, config: & Config) -> ignore::Walk {535 + let respect = config.respect_ignore_files;536 + let mut builder = ignore::WalkBuilder::new(root);538 + .max_depth (max_depth)539 + .hidden (! config.include_hidden)541 + .git_ignore (respect)542 + .git_global (respect)543 + .git_exclude (respect)548 + .sort_by_file_path (std::cmp::Ord::cmp);555 + max_depth: Option <usize >,557 + cancel: & CancelHandle,559 + ) -> std::result::Result <Vec <String >, SmithError> {560 + let mut names = Vec ::new();561 + for found in walker (root, max_depth, config) {562 + if cancel.is_cancelled () {563 + return Err (SmithError::Cancelled);565 + let found = found.map_err (|e| tool_err (code, e.to_string ()))? ;566 + if found.depth () == 0 {573 + .unwrap_or_else (|_| found.path ())577 + if names.len () >= MAX_LIST_ENTRIES {593 + cancel: & CancelHandle,594 + ) -> std::result::Result <String , SmithError> {595 + let mut matches: Vec <String > = Vec ::new();596 + let mut total_bytes = 0 usize ;597 + for found in walker (root, None , config) {598 + if cancel.is_cancelled () {599 + return Err (SmithError::Cancelled);601 + let found = found.map_err (|e| tool_err ("GREP_ERROR" , e.to_string ()))? ;602 + if ! found.file_type ().is_some_and (|kind| kind.is_file ()) {605 + let relative = found608 + .unwrap_or_else (|_| found.path ())611 + let Ok (file) = fs::File::open(found.path ()) else {614 + let mut reader = BufReader::with_capacity(64 * 1024 , file);615 + let mut line = Vec ::new();616 + let mut line_no = 0 usize ;619 + match reader.read_until (b '\n' , &mut line) {620 + Ok (0 ) | Err (_ ) => break ,623 + if line.contains (& 0 ) {627 + let text = String ::from_utf8_lossy(& line).trim_end ().to_string ();628 + if ! text.contains (query) {631 + let rendered = format! ("{relative}:{line_no}:{text}" );632 + if matches.len () >= MAX_GREP_MATCHES 633 + || total_bytes + rendered.len () > DEFAULT_OUTPUT_CAP 635 + matches.push ("<truncated>" .to_string ());636 + return Ok (matches.join ("\n" ));638 + total_bytes += rendered.len ();639 + matches.push (rendered);642 + Ok (matches.join ("\n" ))647 + input: & serde_json::Value,650 + cancel: & CancelHandle,651 + ) -> std::result::Result <String , SmithError> {654 + .and_then (|v| v.as_str ())655 + .ok_or_else (|| tool_err ("VALIDATION" , "bash requires string 'command'" ))? ;656 + let requested = input658 + .and_then (serde_json::Value::as_u64)659 + .unwrap_or (timeout_ms);660 + let result = crate ::bash::execute(662 + working_dir.to_str (),663 + requested.min (timeout_ms),667 + if result.cancelled {668 + return Err (SmithError::Cancelled);670 + let mut output = result.stdout;671 + if ! result.stderr.is_empty () {672 + if ! output.is_empty () {675 + output.push_str ("[stderr] " );676 + output.push_str (& result.stderr);678 + if result.timed_out {679 + return Err (tool_err (681 + format! ("timed out after {requested} ms: {output}" ),684 + match result.exit_code {685 + Some (0 ) => Ok (output),686 + Some (code) => Err (tool_err ("BASH_EXIT" , format! ("exit {code}: {output}" ))),687 + None => Err (tool_err (689 + format! ("terminated without exit status: {output}" ),399 695 fn read_bounded (fn read_bounded (400 696 path: & Path, path: & Path,427 723 if line_no <= offset { if line_no <= offset {428 724 continue ; continue ;430 - if out.lines ().count () >= limit.min (usize ::MAX - 1 ) && limit != usize ::MAX {
433 726 let emit = if limit == usize ::MAX { let emit = if limit == usize ::MAX {475 769 fn temp_sibling (path: & Path) -> PathBuf {fn temp_sibling (path: & Path) -> PathBuf {476 770 static COUNTER : AtomicUsize = AtomicUsize::new(0 ); static COUNTER : AtomicUsize = AtomicUsize::new(0 );477 771 let n = COUNTER .fetch_add (1 , Ordering::Relaxed); let n = COUNTER .fetch_add (1 , Ordering::Relaxed);480 - .map (|s| s.to_string_lossy ().into_owned ())481 - . unwrap_or_else ( || "file" .to_string ()) ; 772 + let name = path.file_name ().map_or_else (773 + || "file" .to_string (), 774 + |name| name.to_string_lossy ().into_owned (),482 776 path.with_file_name (format! (".{name}.tmp-{}-{n}" , std::process::id())) path.with_file_name (format! (".{name}.tmp-{}-{n}" , std::process::id()))486 780 fn edit_exact (path: & Path, old: &str , new: &str ) -> std::result::Result <String , SmithError> {fn edit_exact (path: & Path, old: &str , new: &str ) -> std::result::Result <String , SmithError> {487 781 let meta = fs::metadata(path).map_err (io_tool_err ("EDIT_READ_ERROR" ))? ; let meta = fs::metadata(path).map_err (io_tool_err ("EDIT_READ_ERROR" ))? ;488 - if meta.len () as usize > MAX_EDIT_FILE_BYTES {782 + if meta.len () > MAX_EDIT_FILE_BYTES {489 783 return Err (tool_err ( return Err (tool_err (490 784 "FILE_TOO_LARGE" , "FILE_TOO_LARGE" ,491 785 "edit input exceeds the file size limit" , "edit input exceeds the file size limit" ,544 838 Ok (matches.join ("\n" )) Ok (matches.join ("\n" ))547 842 fn now_ms () -> i64 {fn now_ms () -> i64 {548 843 std::time::SystemTime::now() std::time::SystemTime::now()549 844 .duration_since (std::time::UNIX_EPOCH ) .duration_since (std::time::UNIX_EPOCH )550 - .map (|d| d.as_millis () as i64 )845 + .map_or (0 , |elapsed| {846 + i64 ::try_from(elapsed.as_millis ()).unwrap_or (i64 ::MAX )554 850 #[cfg(test)]#[cfg(test)]555 - #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]852 + clippy::unwrap_used,854 + reason = "tests may panic on invariant violations" 556 856 mod tests {mod tests {557 857 use super ::* ; use super ::* ;558 858 use std::path::PathBuf; use std::path::PathBuf;
868 + fn listing_and_searching_respect_ignore_rules_and_hidden_entries () {869 + let dir = workdir ("ignore_rules" );870 + std::fs::write(dir.join (".gitignore" ), "ignored.txt\n" ).unwrap ();871 + std::fs::write(dir.join ("keep.txt" ), "needle here\n" ).unwrap ();872 + std::fs::write(dir.join ("ignored.txt" ), "needle here\n" ).unwrap ();873 + std::fs::write(dir.join (".hidden.txt" ), "needle here\n" ).unwrap ();874 + std::fs::create_dir_all(dir.join ("nested" )).unwrap ();875 + std::fs::write(dir.join ("nested/deep.txt" ), "needle deep\n" ).unwrap ();877 + let mut ts = ToolSession::new(& dir);880 + .invoke ("find" , & serde_json::json! ({"pattern" : "" }))883 + assert_eq! (found, "keep.txt\nnested\nnested/deep.txt" );885 + let listed = ts.invoke ("ls" , & serde_json::json! ({})).unwrap ().output;886 + assert_eq! (listed, "keep.txt\nnested" );889 + .invoke ("grep" , & serde_json::json! ({"path" : "" , "query" : "needle" }))894 + "keep.txt:1:needle here\nnested/deep.txt:1:needle deep" 898 + let mut config = Config::default_valid();899 + config.respect_ignore_files = false ;900 + config.include_hidden = true ;901 + let mut permissive = ToolSession::new(& dir).with_config (config);902 + let found = permissive903 + .invoke ("find" , & serde_json::json! ({"pattern" : ".txt" }))906 + assert_eq! (found, ".hidden.txt\nignored.txt\nkeep.txt\nnested/deep.txt" );907 + let hits = permissive910 + & serde_json::json! ({"path" : "" , "query" : "needle here" }),916 + ".hidden.txt:1:needle here\nignored.txt:1:needle here\nkeep.txt:1:needle here" 921 + fn edit_rejects_input_that_describes_an_older_version_of_the_file () {922 + let dir = workdir ("stale_edit" );923 + let target = dir.join ("doc.txt" );924 + std::fs::write(& target, "alpha\n" ).unwrap ();925 + let mut ts = ToolSession::new(& dir);926 + ts.invoke ("read" , & serde_json::json! ({"path" : "doc.txt" }))930 + std::thread::sleep(std::time::Duration::from_millis(20 ));931 + std::fs::write(& target, "alpha edited elsewhere\n" ).unwrap ();936 + & serde_json::json! ({"path" : "doc.txt" , "old_string" : "alpha" , "new_string" : "beta" }),939 + assert_eq! (err.code (), "STALE_INPUT" );941 + std::fs::read_to_string(& target).unwrap (),942 + "alpha edited elsewhere\n" 946 + ts.invoke ("read" , & serde_json::json! ({"path" : "doc.txt" }))950 + & serde_json::json! ({"path" : "doc.txt" , "old_string" : "alpha" , "new_string" : "beta" }),954 + std::fs::read_to_string(& target).unwrap (),955 + "beta edited elsewhere\n" 960 + fn bash_effect_runs_in_the_workdir_and_is_recorded () {961 + let dir = workdir ("bash_effect" );962 + let mut ts = ToolSession::new(& dir);966 + & serde_json::json! ({"command" : "printf hi > made.txt; printf done" }),969 + assert! (outcome.ok);970 + assert_eq! (outcome.output, "done" );971 + assert_eq! (std::fs::read_to_string(dir.join ("made.txt" )).unwrap (), "hi" );973 + let kinds: Vec <&str > = ts978 + .map (|e| match & e.content {979 + EntryContent::ToolCall { .. } => "call" ,980 + EntryContent::ToolResult { .. } => "result" ,984 + assert_eq! (kinds, vec! ["call" , "result" ]);988 + fn failing_and_timing_out_commands_report_explicitly () {989 + let dir = workdir ("bash_failures" );990 + let mut ts = ToolSession::new(& dir);992 + .invoke ("bash" , & serde_json::json! ({"command" : "exit 3" }))994 + assert_eq! (err.code (), "BASH_EXIT" );998 + & serde_json::json! ({"command" : "sleep 5" , "timeout_ms" : 150 }),1001 + assert_eq! (err.code (), "BASH_TIMEOUT" );1008 + .filter (|e| matches! (& e.content, EntryContent::ToolResult { ok: false , .. }))1010 + assert_eq! (failed, 2 );1014 + fn cancellation_stops_effects_before_they_start () {1015 + let dir = workdir ("cancel_effects" );1016 + let mut ts = ToolSession::new(& dir);1017 + let cancel = ts.cancel_handle ();1022 + & serde_json::json! ({"path" : "never.txt" , "content" : "x" }),1025 + assert_eq! (err.code (), "CANCELLED" );1026 + assert! (! dir.join ("never.txt" ).exists ());1028 + assert! (ts.session.active_branch ().entries.is_empty ());1032 + fn cancelling_a_running_command_aborts_it () {1033 + let dir = workdir ("cancel_running" );1034 + let mut ts = ToolSession::new(& dir);1035 + let cancel = ts.cancel_handle ();1036 + let waker = std::thread::spawn(move || {1037 + std::thread::sleep(std::time::Duration::from_millis(150 ));1040 + let started = std::time::Instant::now();1044 + & serde_json::json! ({"command" : "sleep 10" , "timeout_ms" : 10_000 }),1047 + waker.join ().unwrap ();1048 + assert_eq! (err.code (), "CANCELLED" );1049 + assert! (started.elapsed () < std::time::Duration::from_secs(5 ));1053 + fn unrecordable_result_after_a_mutation_reports_the_mutation () {1054 + let dir = workdir ("record_failed" );1055 + let session_path = dir.join ("session.smh" );1056 + let mut cfg = Config::default_valid();1057 + cfg.max_frame_bytes = 1024 ;1058 + let opened = crate ::store::open_session(& session_path, cfg.clone ()).unwrap ();1060 + ToolSession::with_session(& dir, opened.session, opened.writer).with_config (cfg);1066 + & serde_json::json! ({"command" : "printf 'x%.0s' $(seq 5000)" }),1069 + assert_eq! (err.code (), "RECORD_FAILED" );1072 + SmithError::RecordFailed {1073 + mutation_applied: true ,568 1080 fn write_requires_string_content_and_leaves_existing_file_untouched () { fn write_requires_string_content_and_leaves_existing_file_untouched () {569 1081 let dir = workdir ("write_schema" ); let dir = workdir ("write_schema" );571 1083 std::fs::write(& target, "original" ).unwrap (); std::fs::write(& target, "original" ).unwrap ();572 1084 let mut ts = ToolSession::new(& dir); let mut ts = ToolSession::new(& dir);573 1085 let err = ts let err = ts574 - .invoke ("write" , serde_json::json! ({"path" : "data.txt" }))1086 + .invoke ("write" , & serde_json::json! ({"path" : "data.txt" }))575 1087 .unwrap_err (); .unwrap_err ();576 1088 assert_eq! (err.code (), "VALIDATION" ); assert_eq! (err.code (), "VALIDATION" );577 1089 assert_eq! (std::fs::read_to_string(& target).unwrap (), "original" ); assert_eq! (std::fs::read_to_string(& target).unwrap (), "original" );578 1090 let err = ts let err = ts579 1091 .invoke ( .invoke (580 1092 "write" , "write" ,581 - serde_json::json! ({"path" : "data.txt" , "content" : 42 }),1093 + & serde_json::json! ({"path" : "data.txt" , "content" : 42 }),583 1095 .unwrap_err (); .unwrap_err ();584 1096 assert_eq! (err.code (), "VALIDATION" ); assert_eq! (err.code (), "VALIDATION" );592 1104 let mut ts = ToolSession::new(& dir); let mut ts = ToolSession::new(& dir);593 1105 ts.invoke ( ts.invoke (594 1106 "write" , "write" ,595 - serde_json::json! ({"path" : "a/b/c.txt" , "content" : "deep" }),1107 + & serde_json::json! ({"path" : "a/b/c.txt" , "content" : "deep" }),597 1109 .unwrap (); .unwrap ();598 1110 assert_eq! ( assert_eq! (602 1114 let leftovers: Vec <_ > = std::fs::read_dir(& dir) let leftovers: Vec <_ > = std::fs::read_dir(& dir)603 1115 .unwrap () .unwrap ()604 - .filter_map (|e| e.ok ())1116 + .filter_map (std::result::Result::ok)605 1117 .flat_map (|e| { .flat_map (|e| {606 1118 std::fs::read_dir(e.path ()) std::fs::read_dir(e.path ())607 1119 .unwrap () .unwrap ()608 - .filter_map (|x| x.ok ())1120 + .filter_map (std::result::Result::ok)609 1121 .map (|x| x.file_name ().to_string_lossy ().into_owned ()) .map (|x| x.file_name ().to_string_lossy ().into_owned ())610 1122 .collect::<Vec <_ >>() .collect::<Vec <_ >>()627 1139 let err = ts let err = ts628 1140 .invoke ( .invoke (630 - serde_json::json! ({"path" : "f.txt" , "old_string" : "a" , "new_string" : "b" }),1142 + & serde_json::json! ({"path" : "f.txt" , "old_string" : "a" , "new_string" : "b" }),632 1144 .unwrap_err (); .unwrap_err ();633 1145 assert_eq! (err.code (), "EDIT_AMBIGUOUS" ); assert_eq! (err.code (), "EDIT_AMBIGUOUS" );635 1147 let err = ts let err = ts636 1148 .invoke ( .invoke (638 - serde_json::json! ({"path" : "f.txt" , "old_string" : "NOT_PRESENT" , "new_string" : "b" }),1150 + & serde_json::json! ({"path" : "f.txt" , "old_string" : "NOT_PRESENT" , "new_string" : "b" }),640 1152 .unwrap_err (); .unwrap_err ();641 1153 assert_eq! (err.code (), "EDIT_NOT_FOUND" ); assert_eq! (err.code (), "EDIT_NOT_FOUND" );644 1156 ts.invoke ( ts.invoke (646 - serde_json::json! ({"path" : "f.txt" , "old_string" : "a a" , "new_string" : "b" }),1158 + & serde_json::json! ({"path" : "f.txt" , "old_string" : "a a" , "new_string" : "b" }),648 1160 .unwrap (); .unwrap ();649 1161 assert_eq! (std::fs::read_to_string(& target).unwrap (), "b" ); assert_eq! (std::fs::read_to_string(& target).unwrap (), "b" );655 1167 let dir = workdir ("read_caps" ); let dir = workdir ("read_caps" );656 1168 let mut body = String ::new(); let mut body = String ::new();657 1169 for i in 0 .. 100 { for i in 0 .. 100 {658 - body.push_str (& format! ("line-{i}\n" ));1170 + use std::fmt::Write as _ ;1171 + let _ = writeln! (body, "line-{i}" );660 1173 std::fs::write(dir.join ("lines.txt" ), & body).unwrap (); std::fs::write(dir.join ("lines.txt" ), & body).unwrap ();661 1174 let mut ts = ToolSession::new(& dir); let mut ts = ToolSession::new(& dir);662 1175 let out = ts let out = ts663 1176 .invoke ( .invoke (665 - serde_json::json! ({"path" : "lines.txt" , "offset" : 2 , "limit" : 3 }),1178 + & serde_json::json! ({"path" : "lines.txt" , "offset" : 2 , "limit" : 3 }),667 1180 .unwrap (); .unwrap ();668 1181 assert_eq! (out.output, "line-2\nline-3\nline-4\n" ); assert_eq! (out.output, "line-2\nline-3\nline-4\n" );669 1182 let capped = ts let capped = ts670 1183 .invoke ( .invoke (672 - serde_json::json! ({"path" : "lines.txt" , "max_bytes" : 20 }),1185 + & serde_json::json! ({"path" : "lines.txt" , "max_bytes" : 20 }),674 1187 .unwrap (); .unwrap ();675 1188 assert! (capped.output.len () <= 20 ); assert! (capped.output.len () <= 20 );676 1189 std::fs::write(dir.join ("bin.dat" ), [0x62 , 0x00 , 0x62 ]).unwrap (); std::fs::write(dir.join ("bin.dat" ), [0x62 , 0x00 , 0x62 ]).unwrap ();677 1190 let err = ts let err = ts678 - .invoke ("read" , serde_json::json! ({"path" : "bin.dat" }))1191 + .invoke ("read" , & serde_json::json! ({"path" : "bin.dat" }))679 1192 .unwrap_err (); .unwrap_err ();680 1193 assert_eq! (err.code (), "BINARY_CONTENT" ); assert_eq! (err.code (), "BINARY_CONTENT" );681 1194 let _ = std::fs::remove_dir_all(& dir); let _ = std::fs::remove_dir_all(& dir);688 1201 std::fs::write(dir.join (name), "" ).unwrap (); std::fs::write(dir.join (name), "" ).unwrap ();690 1203 let mut ts = ToolSession::new(& dir); let mut ts = ToolSession::new(& dir);691 - let out = ts.invoke ("ls" , serde_json::json! ({})).unwrap ();1204 + let out = ts.invoke ("ls" , & serde_json::json! ({})).unwrap ();692 1205 assert_eq! (out.output, "alpha\nmid\nzeta" ); assert_eq! (out.output, "alpha\nmid\nzeta" );693 1206 let found = ts let found = ts694 - .invoke ("find" , serde_json::json! ({"pattern" : "a" }))1207 + .invoke ("find" , & serde_json::json! ({"pattern" : "a" }))695 1208 .unwrap (); .unwrap ();696 1209 assert_eq! (found.output, "alpha\nzeta" ); assert_eq! (found.output, "alpha\nzeta" );697 1210 let err = ts let err = ts698 1211 .invoke ( .invoke (700 - serde_json::json! ({"path" : "missing-dir" , "pattern" : "x" }),1213 + & serde_json::json! ({"path" : "missing-dir" , "pattern" : "x" }),702 1215 .unwrap_err (); .unwrap_err ();703 1216 assert_eq! (err.code (), "FIND_ERROR" ); assert_eq! (err.code (), "FIND_ERROR" );716 1229 let out = ts let out = ts717 1230 .invoke ( .invoke (719 - serde_json::json! ({"path" : "log.txt" , "query" : "hit" }),1232 + & serde_json::json! ({"path" : "log.txt" , "query" : "hit" }),721 1234 .unwrap (); .unwrap ();722 1235 assert_eq! (out.output, "hit one\nhit two\nhit three" ); assert_eq! (out.output, "hit one\nhit two\nhit three" );727 1240 fn unregistered_tools_and_non_object_input_are_rejected () { fn unregistered_tools_and_non_object_input_are_rejected () {728 1241 let dir = workdir ("registry" ); let dir = workdir ("registry" );729 1242 let mut ts = ToolSession::new(& dir); let mut ts = ToolSession::new(& dir);730 - let err = ts.invoke ("rm" , serde_json::json! ({})).unwrap_err ();1243 + let err = ts.invoke ("rm" , & serde_json::json! ({})).unwrap_err ();731 1244 assert_eq! (err.code (), "TOOL_NOT_REGISTERED" ); assert_eq! (err.code (), "TOOL_NOT_REGISTERED" );732 1245 let err = ts let err = ts733 - .invoke ("read" , serde_json::json! ("not-an-object" ))1246 + .invoke ("read" , & serde_json::json! ("not-an-object" ))734 1247 .unwrap_err (); .unwrap_err ();735 1248 assert_eq! (err.code (), "INVALID_INPUT" ); assert_eq! (err.code (), "INVALID_INPUT" );736 1249 let _ = std::fs::remove_dir_all(& dir); let _ = std::fs::remove_dir_all(& dir);740 1253 fn failed_effects_are_recorded_as_failures () { fn failed_effects_are_recorded_as_failures () {741 1254 let dir = workdir ("record_fail" ); let dir = workdir ("record_fail" );742 1255 let mut ts = ToolSession::new(& dir); let mut ts = ToolSession::new(& dir);743 - let res = ts.invoke ("read" , serde_json::json! ({"path" : "nope.txt" }));1256 + let res = ts.invoke ("read" , & serde_json::json! ({"path" : "nope.txt" }));744 1257 assert! (res.is_err ()); assert! (res.is_err ());746 1259 assert_eq! (ts.session.active_branch ().entries.len (), 2 ); assert_eq! (ts.session.active_branch ().entries.len (), 2 );smith-core/src/trace.rs Modified +146 / −25 text lines
1 - #![allow(unused_imports, dead_code)]2 - use crate ::session::{Entry , Session};7 + use crate ::session::{EntryContent , Session};8 + use smith::id::SessionId ;6 11 #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]7 12 pub struct TraceRecord {pub struct TraceRecord {9 14 pub timestamp_ms: i64 , pub timestamp_ms: i64 ,11 16 pub session_id: SessionId, pub session_id: SessionId,13 18 pub kind: TraceKind, pub kind: TraceKind,15 20 pub event_ref: String, pub event_ref: String,19 - #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]24 + #[derive(Clone, Copy , PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]20 25 pub enum TraceKind {pub enum TraceKind {22 27 SessionCreated, SessionCreated,36 41 ReplayCompleted, ReplayCompleted,40 50 pub fn build_trace (session: & Session) -> Vec <TraceRecord> {pub fn build_trace (session: & Session) -> Vec <TraceRecord> {41 - let mut trace = Vec ::new();42 - trace.push (TraceRecord {51 + let branch = session.active_branch ();52 + let mut trace = vec! [TraceRecord {43 53 timestamp_ms: 0 , timestamp_ms: 0 ,44 54 session_id: session.id, session_id: session.id,45 55 kind: TraceKind::SessionCreated, kind: TraceKind::SessionCreated,46 - event_ref: format! ("branch:{}" , session.active_branch_idx),48 - for entry in & session.active_branch ().entries {56 + event_ref: format! ("branch:{}" , branch.branch_id),58 + for entry in & branch.entries {59 + let (kind, event_ref) = match & entry.content {60 + EntryContent::Message(message) => (61 + TraceKind::MessageStreamed,62 + format! ("message:{}" , message.id),64 + EntryContent::ToolCall { call_id, name, .. } => {65 + (TraceKind::ToolCallEmitted, format! ("call:{name}:{call_id}" ))67 + EntryContent::ToolResult { call_id, ok, .. } => (68 + TraceKind::ToolResultReceived,69 + format! ("result:{call_id}:{}" , if * ok { "ok" } else { "failed" }),71 + EntryContent::Meta { kind, .. } if entry.is_compaction () => {72 + (TraceKind::Compaction, format! ("meta:{kind}:{}" , entry.id))74 + EntryContent::Meta { kind, .. } => {75 + (TraceKind::EntryAdded, format! ("meta:{kind}:{}" , entry.id))49 78 trace.push (TraceRecord { trace.push (TraceRecord {50 79 timestamp_ms: entry.timestamp_ms, timestamp_ms: entry.timestamp_ms,51 80 session_id: session.id, session_id: session.id,52 - kind: TraceKind::EntryAdded,53 - event_ref: format! ("entry:{}" , entry.id),61 93 pub fn replay (session: & Session) -> Vec <TraceRecord> {pub fn replay (session: & Session) -> Vec <TraceRecord> {94 + let body = build_trace (session);95 + let last_ms = body.last ().map_or (0 , |record| record.timestamp_ms);96 + let mut trace = Vec ::with_capacity(body.len () + 2 );97 + trace.push (TraceRecord {99 + session_id: session.id,100 + kind: TraceKind::ReplayStarted,101 + event_ref: format! ("session:{}" , session.id),104 + trace.push (TraceRecord {105 + timestamp_ms: last_ms,106 + session_id: session.id,107 + kind: TraceKind::ReplayCompleted,108 + event_ref: format! ("entries:{}" , session.active_branch ().entries.len ()),65 113 #[cfg(test)]#[cfg(test)]66 - #[allow(clippy::unwrap_used, clippy::expect_used)]115 + clippy::unwrap_used,116 + reason = "tests may panic on invariant violations" 67 118 mod tests {mod tests {68 119 use super ::* ; use super ::* ;
120 + use crate ::session::Entry;121 + use crate ::store::{load_session, open_session};122 + use crate ::tools::ToolSession;123 + use smith::config::Config;69 124 use smith::message::{Message, Role}; use smith::message::{Message, Role};
126 + fn kinds (trace: & [TraceRecord]) -> Vec <TraceKind> {127 + trace.iter ().map (|record| record.kind).collect ()72 - fn trace_reconstructs_order () {73 - let mut session = crate :: session :: Session::new();74 - session.append_to_active (crate :: session :: Entry::message(131 + fn trace_reports_tool_activity_and_compaction_in_order () {132 + let mut session = Session::new();133 + session.append_to_active (Entry::message(75 134 Message::with_text(Role::User, "hello" ), Message::with_text(Role::User, "hello" ),78 - let trace = replay (& session);79 - assert! (! trace.is_empty ());80 - assert_eq! (trace[0 ].kind, TraceKind::SessionCreated);137 + let mut tools = ToolSession::new(std::env::temp_dir());138 + tools.session = session;140 + .invoke ("ls" , & serde_json::json! ({"path" : "." }))142 + tools.session.append_compaction (serde_json::json! ({}));145 + kinds (& replay (& tools.session)),147 + TraceKind::ReplayStarted,148 + TraceKind::SessionCreated,149 + TraceKind::MessageStreamed,150 + TraceKind::ToolCallEmitted,151 + TraceKind::ToolResultReceived,152 + TraceKind::Compaction,153 + TraceKind::ReplayCompleted,159 + fn replaying_a_persisted_session_is_byte_stable () {160 + let dir = std::env::temp_dir().join (format! ("smith_trace_{}" , std::process::id()));161 + let _ = std::fs::remove_dir_all(& dir);162 + std::fs::create_dir_all(& dir).unwrap ();163 + let path = dir.join ("trace.smh" );164 + let cfg = Config::default_valid();166 + let opened = open_session (& path, cfg.clone ()).unwrap ();167 + let mut tools = ToolSession::with_session(& dir, opened.session, opened.writer)168 + .with_config (cfg.clone ());172 + & serde_json::json! ({"path" : "note.txt" , "content" : "hi" }),176 + .invoke ("read" , & serde_json::json! ({"path" : "note.txt" }))179 + let encode = |session: & Session| {180 + let mut bytes = Vec ::new();181 + ciborium::ser::into_writer(& replay (session), &mut bytes).unwrap ();184 + let first = load_session (& path, cfg.max_frame_bytes).unwrap ().frames;185 + let second = load_session (& path, cfg.max_frame_bytes).unwrap ().frames;186 + let left = encode (& Session::from_frames(& first));187 + let right = encode (& Session::from_frames(& second));188 + assert_eq! (left, right);190 + kinds (& replay (& Session::from_frames(& first))),192 + TraceKind::ReplayStarted,193 + TraceKind::SessionCreated,194 + TraceKind::ToolCallEmitted,195 + TraceKind::ToolResultReceived,196 + TraceKind::ToolCallEmitted,197 + TraceKind::ToolResultReceived,198 + TraceKind::ReplayCompleted,201 + let _ = std::fs::remove_dir_all(& dir);+1 / −1 text lines
12 12 serde = { workspace = true }serde = { workspace = true }13 13 ciborium = { workspace = true }ciborium = { workspace = true }14 14 serde_json = { workspace = true }serde_json = { workspace = true }15 - thiserror = { workspace = true }15 + dirs = { workspace = true }18 18 default = []No final newline default = []No final newline new file mode 100644+96 / −0 text lines
1 + use crate ::error::{Result , SmithError};2 + use serde::{Deserialize, Serialize};8 + #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]11 + pub session_dir: String,13 + pub max_frame_bytes: usize ,15 + pub tool_timeout_ms: u64 ,17 + pub preserve_unknown_frames: bool ,19 + pub respect_ignore_files: bool ,21 + pub include_hidden: bool ,25 + const MIN_FRAME_BYTES : usize = 1024 ;28 + const MAX_FRAME_BYTES : usize = 100 * 1024 * 1024 ;31 + const MIN_TOOL_TIMEOUT_MS : u64 = 100 ;37 + pub fn default_valid () -> Self {38 + let session_dir = dirs::data_dir()40 + || std::path::PathBuf::from(".smith" ),41 + |base| base.join ("smith" ),45 + session_dir: session_dir.to_string_lossy ().into_owned (),46 + max_frame_bytes: MIN_FRAME_BYTES * 1024 ,47 + tool_timeout_ms: 30_000 ,48 + preserve_unknown_frames: true ,49 + respect_ignore_files: true ,50 + include_hidden: false ,59 + pub fn validate (& self) -> Result <()> {60 + if self.session_dir.trim ().is_empty () {61 + return Err (invalid ("session_dir" , "must not be empty" ));63 + if self.max_frame_bytes < MIN_FRAME_BYTES {66 + & format! ("must be at least {MIN_FRAME_BYTES}" ),69 + if self.max_frame_bytes > MAX_FRAME_BYTES {72 + & format! ("must not exceed {MAX_FRAME_BYTES}" ),75 + if self.tool_timeout_ms < MIN_TOOL_TIMEOUT_MS {78 + & format! ("must be at least {MIN_TOOL_TIMEOUT_MS}" ),85 + fn invalid (field: &str , message: &str ) -> SmithError {87 + field: field.to_string (),88 + message: message.to_string (),92 + impl Default for Config {93 + fn default () -> Self {94 + Self ::default_valid()smith/src/error.rs Modified +140 / −21 text lines
1 3 use std::fmt;use std::fmt;
7 + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]24 + declared_length: usize ,29 + declared_length: usize ,48 + pub const fn code (& self) -> &'static str {50 + Self ::TooLarge { .. } => "FRAME_TOO_LARGE" ,51 + Self ::Encode { .. } => "FRAME_ENCODE" ,52 + Self ::Malformed { .. } => "FRAME_MALFORMED" ,53 + Self ::Checksum { .. } => "FRAME_CHECKSUM" ,54 + Self ::UnsupportedVersion { .. } => "FRAME_VERSION" ,55 + Self ::SchemaDecode { .. } => "FRAME_SCHEMA" ,60 + impl fmt::Display for FrameFault {61 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {63 + Self ::TooLarge { max_bytes, actual } => {64 + write! (f, "too large: {actual} > {max_bytes} bytes" )66 + Self ::Encode { message } => write! (f, "encode: {message}" ),67 + Self ::Malformed { declared_length } => {70 + "malformed: declared length {declared_length} is too short" 73 + Self ::Checksum { declared_length } => {74 + write! (f, "checksum mismatch in {declared_length} declared bytes" )76 + Self ::UnsupportedVersion { kind, version } => {77 + write! (f, "unsupported version {version} for kind {kind}" )79 + Self ::SchemaDecode { message } => write! (f, "schema decode: {message}" ),4 85 #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]5 86 pub enum SmithError {pub enum SmithError {7 - Session { code: String , message: String },9 - Provider { code: String , message: String },11 - Tool { code: String , message: String },13 - FrameDecode { message: String },15 - FrameEncode { message: String },17 - FrameTooLarge { max_bytes: usize , actual: usize },114 + mutation_applied: bool ,123 + offset: Option <u64 >,19 126 Cancelled, Cancelled,21 - Config { field: String , message: String },24 136 impl fmt::Display for SmithError {impl fmt::Display for SmithError {27 139 Self ::Session { code, message } => write! (f, "session [{code}]: {message}" ), Self ::Session { code, message } => write! (f, "session [{code}]: {message}" ),28 140 Self ::Provider { code, message } => write! (f, "provider [{code}]: {message}" ), Self ::Provider { code, message } => write! (f, "provider [{code}]: {message}" ),29 141 Self ::Tool { code, message } => write! (f, "tool [{code}]: {message}" ), Self ::Tool { code, message } => write! (f, "tool [{code}]: {message}" ),30 - Self ::FrameDecode { message } => write! (f, "frame decode: {message}" ),31 - Self ::FrameEncode { message } => write! (f, "frame encode: {message}" ),32 - Self ::FrameTooLarge { max_bytes, actual } => {33 - write! (f, "frame too large: {actual} > {max_bytes} bytes" )142 + Self ::RecordFailed {148 + "tool [RECORD_FAILED]: {tool} recording failed (mutation applied: {mutation_applied}): {message}" 150 + Self ::Frame { fault, offset } => match offset {151 + Some (at) => write! (f, "frame at offset {at}: {fault}" ),152 + None => write! (f, "frame: {fault}" ),35 154 Self ::Cancelled => write! (f, "operation cancelled" ), Self ::Cancelled => write! (f, "operation cancelled" ),36 155 Self ::Config { field, message } => { Self ::Config { field, message } => {37 156 write! (f, "config [{field}]: {message}" ) write! (f, "config [{field}]: {message}" )48 167 impl SmithError {impl SmithError {50 170 pub fn code (& self) -> &str { pub fn code (& self) -> &str {51 171 match self { match self {52 - Self ::Session { code, .. } => code,53 - Self ::Provider { code, .. } => code,54 - Self ::Tool { code, .. } => code,55 - Self ::FrameDecode { .. } => "FRAME_DECODE" ,56 - Self ::FrameEncode { .. } => "FRAME_ENCODE" ,57 - Self ::FrameTooLarge { .. } => "FRAME_TOO_LARGE" ,172 + Self ::Session { code, .. } | Self ::Provider { code, .. } | Self ::Tool { code, .. } => {175 + Self ::RecordFailed { .. } => "RECORD_FAILED" ,176 + Self ::Frame { fault, .. } => fault.code (),58 177 Self ::Cancelled => "CANCELLED" , Self ::Cancelled => "CANCELLED" ,59 178 Self ::Config { .. } => "CONFIG" , Self ::Config { .. } => "CONFIG" ,+58 / −235 text lines
1 6 use std::fmt;use std::fmt;
8 + use serde::{Deserialize, Serialize};2 9 use uuid::Uuid;use uuid::Uuid;6 - Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde:: Serialize, serde:: Deserialize,8 - pub struct SessionId (Uuid);12 + macro_rules! smith_id {13 + ($name:ident , $what:literal) => {14 + #[doc = concat!("Identifier of " , $what, "." )]16 + Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize,18 + pub struct $name (Uuid );11 - pub fn new () -> Self {23 + pub fn new () -> Self {15 - pub fn as_uuid (& self) -> Uuid {29 + pub const fn as_uuid (& self) -> Uuid {34 + impl fmt::Display for $name {35 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {36 + write! (f, "{}" , self.0 )40 + impl From <Uuid> for $name {41 + fn from (value: Uuid) -> Self {46 + impl From <$name> for Uuid {47 + fn from (id: $name) -> Self {52 + impl Default for $name {53 + fn default () -> Self {20 - impl fmt::Display for SessionId {21 - fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {26 - impl From <Uuid> for SessionId {27 - fn from (u: Uuid) -> Self {32 - impl From <SessionId> for Uuid {33 - fn from (id: SessionId) -> Uuid {38 - impl Default for SessionId {39 - fn default () -> Self {46 - Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,48 - pub struct BranchId (Uuid);51 - pub fn new () -> Self {55 - pub fn as_uuid (& self) -> Uuid {60 - impl fmt::Display for BranchId {61 - fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {66 - impl From <Uuid> for BranchId {67 - fn from (u: Uuid) -> Self {72 - impl From <BranchId> for Uuid {73 - fn from (id: BranchId) -> Uuid {78 - impl Default for BranchId {79 - fn default () -> Self {86 - Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,88 - pub struct EntryId (Uuid);91 - pub fn new () -> Self {95 - pub fn as_uuid (& self) -> Uuid {100 - impl fmt::Display for EntryId {101 - fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {106 - impl From <Uuid> for EntryId {107 - fn from (u: Uuid) -> Self {112 - impl From <EntryId> for Uuid {113 - fn from (id: EntryId) -> Uuid {118 - impl Default for EntryId {119 - fn default () -> Self {126 - Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,128 - pub struct ToolCallId (Uuid);131 - pub fn new () -> Self {132 - Self (Uuid::now_v7())135 - pub fn as_uuid (& self) -> Uuid {140 - impl fmt::Display for ToolCallId {141 - fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {146 - impl From <Uuid> for ToolCallId {147 - fn from (u: Uuid) -> Self {152 - impl From <ToolCallId> for Uuid {153 - fn from (id: ToolCallId) -> Uuid {158 - impl Default for ToolCallId {159 - fn default () -> Self {166 - Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,168 - pub struct ToolResultId (Uuid);171 - pub fn new () -> Self {172 - Self (Uuid::now_v7())175 - pub fn as_uuid (& self) -> Uuid {180 - impl fmt::Display for ToolResultId {181 - fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {186 - impl From <Uuid> for ToolResultId {187 - fn from (u: Uuid) -> Self {192 - impl From <ToolResultId> for Uuid {193 - fn from (id: ToolResultId) -> Uuid {198 - impl Default for ToolResultId {199 - fn default () -> Self {206 - Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,208 - pub struct MessageId (Uuid);211 - pub fn new () -> Self {212 - Self (Uuid::now_v7())215 - pub fn as_uuid (& self) -> Uuid {220 - impl fmt::Display for MessageId {221 - fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {226 - impl From <Uuid> for MessageId {227 - fn from (u: Uuid) -> Self {232 - impl From <MessageId> for Uuid {233 - fn from (id: MessageId) -> Uuid {238 - impl Default for MessageId {239 - fn default () -> Self {60 + smith_id! (SessionId, "one session" );61 + smith_id! (BranchId, "one branch of a session" );62 + smith_id! (EntryId, "one session entry" );63 + smith_id! (ToolCallId, "one tool call" );64 + smith_id! (ToolResultId, "one tool result" );65 + smith_id! (MessageId, "one message" );+36 / −28 text lines
5 5 #![forbid(unsafe_code)]#![forbid(unsafe_code)]11 - clippy::must_use_candidate,12 - clippy::match_same_arms,13 - clippy::doc_markdown,14 - clippy::missing_const_for_fn,15 - clippy::missing_errors_doc,16 - clippy::module_name_repetitions,17 - clippy::struct_excessive_bools,18 - clippy::too_many_arguments,
23 10 pub mod error ;pub mod error ;25 12 pub mod id ;pub mod id ;27 14 pub mod message ;pub mod message ;29 16 pub mod stream ;pub mod stream ;31 18 pub mod tool ;pub mod tool ;33 - pub use error::{Result , SmithError};20 + pub use config::Config;21 + pub use error::{FrameFault , Result , SmithError};34 22 pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};35 23 pub use message::{ContentBlock, Message, Role};pub use message::{ContentBlock, Message, Role};36 24 pub use stream::{StopReason, StreamEvent, Usage};pub use stream::{StopReason, StreamEvent, Usage};37 - pub use tool::{CancelHandle, CancellationToken , ToolCall, ToolMetadata, ToolResult};25 + pub use tool::{CancelHandle, ToolCall, ToolMetadata, ToolResult};39 27 #[cfg(test)]#[cfg(test)]40 - #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn)]30 + reason = "tests may panic on invariant violations" 41 32 mod tests {mod tests {42 33 use super ::* ; use super ::* ;100 - fn cancellation_is_cooperative () {101 - let mut token = CancellationToken::new();102 - assert! (! token.is_cancelled ());104 - assert! (token.is_cancelled ());91 + fn config_names_the_field_it_rejects () {92 + let mut config = Config::default_valid();93 + config.max_frame_bytes = 100 ;94 + let err = config.validate ().unwrap_err ();95 + assert_eq! (err.code (), "CONFIG" );99 + field: "max_frame_bytes" .to_string (),100 + message: "must be at least 1024" .to_string (),103 + config.max_frame_bytes = 1024 ;104 + assert! (config.validate ().is_ok ());105 + config.session_dir = " " .to_string ();107 + config.validate ().unwrap_err (),108 + SmithError::Config {109 + field: "session_dir" .to_string (),110 + message: "must not be empty" .to_string (),smith/src/message.rs Modified +24 / −9 text lines
3 + use crate ::id::{MessageId, ToolCallId};2 4 use serde::{Deserialize, Serialize};use serde::{Deserialize, Serialize};3 5 use std::fmt;use std::fmt;18 20 impl fmt::Display for Role {impl fmt::Display for Role {19 21 fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result { fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {20 22 match self { match self {21 - Role ::User => write! (f, "user" ),22 - Role ::Assistant => write! (f, "assistant" ),23 - Role ::System => write! (f, "system" ),24 - Role ::Tool => write! (f, "tool" ),23 + Self ::User => write! (f, "user" ),24 + Self ::Assistant => write! (f, "assistant" ),25 + Self ::System => write! (f, "system" ),26 + Self ::Tool => write! (f, "tool" ),59 61 impl ContentBlock {impl ContentBlock {60 64 pub fn text <S: Into <String >>(s: S) -> Self { pub fn text <S: Into <String >>(s: S) -> Self {61 65 Self ::Text(s.into ()) Self ::Text(s.into ())64 70 pub fn thinking <S: Into <String >>(s: S) -> Self { pub fn thinking <S: Into <String >>(s: S) -> Self {65 71 Self ::Thinking(s.into ()) Self ::Thinking(s.into ())68 76 pub fn tool_use <N: Into <String >>( pub fn tool_use <N: Into <String >>(70 78 input: serde_json::Value, input: serde_json::Value,80 90 pub fn tool_result (call_id: ToolCallId, ok: bool , output: impl Into <String >) -> Self { pub fn tool_result (call_id: ToolCallId, ok: bool , output: impl Into <String >) -> Self {81 91 Self ::ToolResult { Self ::ToolResult {102 112 impl Message {impl Message {103 115 pub fn new (role: Role) -> Self { pub fn new (role: Role) -> Self {105 117 id: MessageId::new(), id: MessageId::new(),112 126 pub fn with_text <S: Into <String >>(role: Role, text: S) -> Self { pub fn with_text <S: Into <String >>(role: Role, text: S) -> Self {114 128 id: MessageId::new(), id: MessageId::new(),121 136 pub fn add_block (&mut self, block: ContentBlock) { pub fn add_block (&mut self, block: ContentBlock) {122 137 self.blocks.push (block); self.blocks.push (block);136 151 ContentBlock::Text(t) => write! (f, "text: {t}" )? , ContentBlock::Text(t) => write! (f, "text: {t}" )? ,137 152 ContentBlock::Thinking(t) => write! (f, "thinking: {t}" )? , ContentBlock::Thinking(t) => write! (f, "thinking: {t}" )? ,138 153 ContentBlock::ToolUse { name, call_id, .. } => { ContentBlock::ToolUse { name, call_id, .. } => {139 - write! (f, "tool_use {{ name: {name}, call_id: {call_id} }}" )? 154 + write! (f, "tool_use {{ name: {name}, call_id: {call_id} }}" )? ; 141 156 ContentBlock::ToolResult { call_id, ok, .. } => { ContentBlock::ToolResult { call_id, ok, .. } => {142 - write! (f, "tool_result {{ call_id: {call_id}, ok: {ok} }}" )? 157 + write! (f, "tool_result {{ call_id: {call_id}, ok: {ok} }}" )? ; 151 167 fn now_ms () -> i64 {fn now_ms () -> i64 {152 168 use std::time::{SystemTime, UNIX_EPOCH }; use std::time::{SystemTime, UNIX_EPOCH };153 169 SystemTime::now() SystemTime::now()154 170 .duration_since (UNIX_EPOCH ) .duration_since (UNIX_EPOCH )155 - .map (|d| d.as_millis () as i64 )171 + .map_or (0 , |d| i64 ::try_from(d.as_millis ()).unwrap_or (i64 ::MAX ))smith/src/stream.rs Modified +19 / −3 text lines
3 + use crate ::id::{MessageId, ToolCallId};2 4 use serde::{Deserialize, Serialize};use serde::{Deserialize, Serialize};85 87 impl Usage {impl Usage {86 - pub fn new () -> Self {90 + pub const fn new () -> Self {88 92 input_tokens: 0 , input_tokens: 0 ,89 93 output_tokens: 0 , output_tokens: 0 ,102 106 impl StreamEvent {impl StreamEvent {103 109 pub fn text_delta (message_id: MessageId, delta: impl Into <String >) -> Self { pub fn text_delta (message_id: MessageId, delta: impl Into <String >) -> Self {104 110 Self ::TextDelta { Self ::TextDelta {105 111 message_id, message_id,110 118 pub fn thinking_delta (message_id: MessageId, delta: impl Into <String >) -> Self { pub fn thinking_delta (message_id: MessageId, delta: impl Into <String >) -> Self {111 119 Self ::ThinkingDelta { Self ::ThinkingDelta {112 120 message_id, message_id,117 127 pub fn tool_use ( pub fn tool_use (118 128 message_id: MessageId, message_id: MessageId,119 129 name: impl Into <String >, name: impl Into <String >,131 143 pub fn tool_result ( pub fn tool_result (132 144 message_id: MessageId, message_id: MessageId,133 145 call_id: ToolCallId, call_id: ToolCallId,145 - pub fn stop (reason: StopReason, usage: Option <Usage>) -> Self {159 + pub const fn stop (reason: StopReason, usage: Option <Usage>) -> Self {146 160 Self ::Stop { reason, usage } Self ::Stop { reason, usage }149 165 pub fn error (error: impl Into <String >) -> Self { pub fn error (error: impl Into <String >) -> Self {150 166 Self ::Error { Self ::Error {151 167 error: error.into (), error: error.into (),smith/src/tool.rs Modified +9 / −23 text lines
3 + use crate ::id::ToolCallId ;2 4 use serde::{Deserialize, Serialize};use serde::{Deserialize, Serialize};15 17 impl ToolMetadata {impl ToolMetadata {16 20 pub fn new <N: Into <String >, D: Into <String >>(name: N, description: D) -> Self { pub fn new <N: Into <String >, D: Into <String >>(name: N, description: D) -> Self {18 22 name: name.into (), name: name.into (),28 34 pub fn with_schema (mut self, schema: serde_json::Value) -> Self { pub fn with_schema (mut self, schema: serde_json::Value) -> Self {29 35 self.input_schema = schema; self.input_schema = schema;53 59 pub output: String , pub output: String ,58 - #[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]59 - pub struct CancellationToken {64 - impl CancellationToken {65 - pub fn new () -> Self {66 - Self { cancelled: false }69 - pub fn cancel (&mut self) {70 - self.cancelled = true ;73 - pub fn is_cancelled (& self) -> bool {
80 64 #[derive(Clone, Debug, Default)]#[derive(Clone, Debug, Default)]85 69 impl CancelHandle {impl CancelHandle {87 72 pub fn new () -> Self { pub fn new () -> Self {88 73 Self ::default() Self ::default()97 83 pub fn is_cancelled (& self) -> bool { pub fn is_cancelled (& self) -> bool {98 84 self.flag.load (std::sync::atomic::Ordering::Acquire) self.flag.load (std::sync::atomic::Ordering::Acquire)