repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

core(SMH-PLAN-CORE0002): make session recovery and replay trustworthy

8597565336e1e43bd71994051d519b51ecc8c31e

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

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

+2891 / −960 text lines

Diff layout

.system/plans/SMH-PLAN-CORE0002-frame-recovery-and-core-gates/index.md

Added
new file mode 100644

+107 / −0 text lines

1---
2id: SMH-PLAN-CORE0002
3type: plan
4title: "Frame Recovery, Session Identity, and Core Gates"
5spec: SMH-SPEC-SPEC0001
6status: approved
7depends_on: [SMH-PLAN-CORE0001]
8---
9
10# Frame Recovery, Session Identity, and Core Gates
12Remediation 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.
15## Entry
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.
20## Decisions
22### Frame format v2
24Wire layout, little endian:
26```text
27[len u32][kind u16][version u16][crc32 u32][CBOR payload]
28```
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.
34Recovery decision table:
36| crc32 | kind | outcome |
37| --- | --- | --- |
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 |
42Damage is reported, not fatal.
43Loading returns recovered frames plus a recovery report, because complete frames must survive alongside explicit damage reporting.
44No v1 migration exists because nothing is released; v1 files are rejected by version.
46### Error taxonomy
48One variant per layer, typed per-layer codes, no stringly codes.
50| layer | carries |
51| --- | --- |
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.
66## Order
681. Introduce the layered error taxonomy and frame format v2 with checksum, kind, version, and recovery reports.
692. Add the session header frame so session and branch identity survive reload.
703. Restore branch structure from parent links, add fork, and write real compaction boundary entries.
714. Serialize repair with the writer lock and keep publication atomic for created, forked, and repaired sessions.
725. Fix the tool invocation contract: record call, run effect, record result, and report `RecordFailed` with mutation state.
736. Plumb cancellation and configured timeout into every tool effect and wire the `bash` arm to `bash::execute`.
747. Add edit stale detection, ignore-aware recursive list, find, and grep, and canonical encoding at the entry boundary.
758. Emit tool, result, and compaction trace kinds, and make trace output byte-stable across loads.
769. Restore build gates: remove blanket crate allows and `doc(hidden)`, move `Config` into `smith`, delete duplicated cancellation and dead code.
78## Interfaces
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.
86## Verification
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.
98## Exit
100Provider-free tool activity can be persisted, recovered, and reconstructed deterministically,
101and the workspace passes its gates without suppression.
103## Stop conditions
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.

Cargo.lock

Modified

+128 / −25 text lines

22# It is not intended for manual editing.
33version = 4
5[[package]]
6name = "aho-corasick"
7version = "1.1.5"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
10dependencies = [
11 "memchr",
12]
514[[package]]
615name = "bitflags"
716version = "2.13.2"
817source = "registry+https://github.com/rust-lang/crates.io-index"
918checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
20[[package]]
21name = "bstr"
22version = "1.13.1"
23source = "registry+https://github.com/rust-lang/crates.io-index"
24checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
25dependencies = [
26 "memchr",
27 "serde_core",
28]
1130[[package]]
1231name = "bumpalo"
1332version = "3.20.3"
5372 "half",
75[[package]]
76name = "crossbeam-deque"
77version = "0.8.8"
78source = "registry+https://github.com/rust-lang/crates.io-index"
79checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
80dependencies = [
81 "crossbeam-epoch",
82 "crossbeam-utils",
83]
85[[package]]
86name = "crossbeam-epoch"
87version = "0.9.21"
88source = "registry+https://github.com/rust-lang/crates.io-index"
89checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
90dependencies = [
91 "crossbeam-utils",
92]
94[[package]]
95name = "crossbeam-utils"
96version = "0.8.23"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
56100[[package]]
57101name = "crunchy"
58102version = "0.2.4"
142186 "r-efi",
189[[package]]
190name = "globset"
191version = "0.4.20"
192source = "registry+https://github.com/rust-lang/crates.io-index"
193checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"
194dependencies = [
195 "aho-corasick",
196 "bstr",
197 "log",
198 "regex-automata",
199 "regex-syntax",
200]
145202[[package]]
146203name = "half"
147204version = "2.7.1"
159216source = "registry+https://github.com/rust-lang/crates.io-index"
160217checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
219[[package]]
220name = "ignore"
221version = "0.4.33"
222source = "registry+https://github.com/rust-lang/crates.io-index"
223checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f"
224dependencies = [
225 "crossbeam-deque",
226 "globset",
227 "log",
228 "memchr",
229 "regex-automata",
230 "same-file",
231 "walkdir",
232 "winapi-util",
233]
162235[[package]]
163236name = "indexmap"
164237version = "2.14.2"
201274 "libc",
277[[package]]
278name = "log"
279version = "0.4.34"
280source = "registry+https://github.com/rust-lang/crates.io-index"
281checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
204283[[package]]
205284name = "memchr"
206285version = "2.8.3"
269348dependencies = [
270349 "getrandom 0.2.17",
271350 "libredox",
272 "thiserror 1.0.69",
351 "thiserror",
354[[package]]
355name = "regex-automata"
356version = "0.4.18"
357source = "registry+https://github.com/rust-lang/crates.io-index"
358checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
359dependencies = [
360 "aho-corasick",
361 "memchr",
362 "regex-syntax",
363]
365[[package]]
366name = "regex-syntax"
367version = "0.8.11"
368source = "registry+https://github.com/rust-lang/crates.io-index"
369checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
275371[[package]]
276372name = "rustversion"
277373version = "1.0.23"
278374source = "registry+https://github.com/rust-lang/crates.io-index"
279375checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
377[[package]]
378name = "same-file"
379version = "1.0.6"
380source = "registry+https://github.com/rust-lang/crates.io-index"
381checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
382dependencies = [
383 "winapi-util",
384]
281386[[package]]
282387name = "serde"
283388version = "1.0.229"
333438version = "0.1.0"
334439dependencies = [
335440 "ciborium",
441 "dirs",
336442 "serde",
337443 "serde_json",
338 "thiserror 2.0.20",
339444 "uuid",
359464version = "0.1.0"
360465dependencies = [
361466 "ciborium",
362 "dirs",
363467 "fs2",
468 "ignore",
364469 "nix",
365470 "serde",
366471 "serde_json",
367472 "smith",
368 "thiserror 2.0.20",
369473 "uuid",
414518source = "registry+https://github.com/rust-lang/crates.io-index"
415519checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
416520dependencies = [
417 "thiserror-impl 1.0.69",
418]
420[[package]]
421name = "thiserror"
422version = "2.0.20"
423source = "registry+https://github.com/rust-lang/crates.io-index"
424checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
425dependencies = [
426 "thiserror-impl 2.0.20",
521 "thiserror-impl",
429524[[package]]
437532 "syn 2.0.119",
440[[package]]
441name = "thiserror-impl"
442version = "2.0.20"
443source = "registry+https://github.com/rust-lang/crates.io-index"
444checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
445dependencies = [
446 "proc-macro2",
447 "quote",
448 "syn 3.0.5",
449]
451535[[package]]
452536name = "unicode-ident"
453537version = "1.0.24"
466550 "wasm-bindgen",
553[[package]]
554name = "walkdir"
555version = "2.5.0"
556source = "registry+https://github.com/rust-lang/crates.io-index"
557checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
558dependencies = [
559 "same-file",
560 "winapi-util",
561]
469563[[package]]
470564name = "wasi"
471565version = "0.11.1+wasi-snapshot-preview1"
533627source = "registry+https://github.com/rust-lang/crates.io-index"
534628checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
630[[package]]
631name = "winapi-util"
632version = "0.1.11"
633source = "registry+https://github.com/rust-lang/crates.io-index"
634checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
635dependencies = [
636 "windows-sys",
637]
536639[[package]]
537640name = "winapi-x86_64-pc-windows-gnu"
538641version = "0.4.0"

smith-core/Cargo.toml

Modified

+1 / −2 text lines

1212serde = { workspace = true }
1313serde_json = { workspace = true }
1414ciborium = { workspace = true }
15thiserror = { workspace = true }
1615uuid = { workspace = true }
17dirs = { workspace = true }
1816fs2 = { workspace = true }
17ignore = { workspace = true }
2019[target.'cfg(unix)'.dependencies]
2120nix = { version = "0.29", features = ["signal"] }No final newline

smith-core/src/bash.rs

Modified

+27 / −19 text lines

3737/// Run `cmd` under `bash -c` in `workdir` with a hard deadline, per-stream
3838/// output caps, and a shared cancellation handle.
39///
40/// # Errors
41///
42/// Returns [`SmithError::Tool`] when the process cannot be spawned.
3943pub fn execute(
4044 cmd: &str,
4145 workdir: Option<&str>,
5155 let stderr_remaining = Arc::new(AtomicUsize::new(max_output_bytes));
5256 let handles = drain_pipes(
5357 &mut child,
54 tx.clone(),
55 stdout_remaining.clone(),
56 stderr_remaining.clone(),
58 &tx,
59 Arc::clone(&stdout_remaining),
60 Arc::clone(&stderr_remaining),
5761 );
5862 drop(tx); // reader threads hold the only senders
9195 status = Some(st);
9296 }
9397 }
94 if status.is_none() {
95 if let Ok(Some(st)) = child.try_wait() {
96 status = Some(st);
97 }
98 if status.is_none()
99 && let Ok(Some(st)) = child.try_wait()
100 {
101 status = Some(st);
98102 }
99103 }
100104 }
101 if status.is_none() {
102 if let Ok(Some(st)) = child.try_wait() {
103 status = Some(st);
104 break;
105 }
105 if status.is_none()
106 && let Ok(Some(st)) = child.try_wait()
107 {
108 status = Some(st);
109 break;
106110 }
107111 }
115119 Stream::Stdout => stdout.extend_from_slice(&chunk),
116120 Stream::Stderr => stderr.extend_from_slice(&chunk),
117121 },
118 Err(RecvTimeoutError::Timeout) => continue,
122 Err(RecvTimeoutError::Timeout) => {}
119123 Err(RecvTimeoutError::Disconnected) => break,
120124 }
121125 }
129133 stderr: String::from_utf8_lossy(&stderr).into_owned(),
130134 cancelled,
131135 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),
133137 })
169173 {
170174 use nix::sys::signal::{Signal, killpg};
171175 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));
173177 let _ = killpg(pgid, Signal::SIGKILL);
174178 }
175179 let _ = child.kill();
180184/// chatty descendant can never deadlock the parent.
181185fn drain_pipes(
182186 child: &mut Child,
183 tx: mpsc::Sender<(Stream, Vec<u8>)>,
187 tx: &mpsc::Sender<(Stream, Vec<u8>)>,
184188 stdout_remaining: Arc<AtomicUsize>,
185189 stderr_remaining: Arc<AtomicUsize>,
186190) -> Vec<std::thread::JoinHandle<()>> {
204208 handles
211/// Forward capped prefixes from one pipe until it closes.
207212fn spawn_reader<R: Read + Send + 'static>(
208213 mut pipe: R,
209214 tx: mpsc::Sender<(Stream, Vec<u8>)>,
214219 let mut buf = vec![0u8; READ_CHUNK];
215220 loop {
216221 match pipe.read(&mut buf) {
217 Ok(0) => break,
222 // End of pipe or a read failure both end this reader.
223 Ok(0) | Err(_) => break,
218224 Ok(n) => {
219225 let keep = n.min(remaining.load(Ordering::Relaxed));
220226 if keep > 0 {
226232 // Beyond the cap we keep reading (without retaining) so
227233 // the pipe never back-pressures the child indefinitely.
228234 }
229 Err(_) => break,
230235 }
231236 }
232237 })
235240#[cfg(test)]
236241#[cfg(unix)]
237#[allow(clippy::unwrap_used, clippy::expect_used)]
242#[expect(
243 clippy::unwrap_used,
244 reason = "tests may panic on invariant violations"
245)]
238246mod tests {
239247 use super::*;
240248 use std::thread;

smith-core/src/config.rs

Deleted
deleted file mode 100644

+0 / −54 text lines

1use serde::{Deserialize, Serialize};
2
3/// Runtime configuration (validated, no plugin loading).
4#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
5pub struct Config {
6 /// Session directory path.
7 pub session_dir: String,
8 /// Maximum frame size in bytes.
9 pub max_frame_bytes: usize,
10 /// Timeout for tool effects.
11 pub tool_timeout_ms: u64,
12 /// Whether to preserve unknown frames during repair.
13 pub preserve_unknown_frames: bool,
14}
16impl Config {
17 /// Default validated configuration. Session data resolves under the
18 /// platform data directory (XDG data home on Linux).
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"),
23 };
24 Self {
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,
29 }
30 }
32 /// Validate the configuration.
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());
36 }
37 if self.max_frame_bytes < 1024 {
38 return Err("max_frame_bytes must be at least 1024".to_string());
39 }
40 if self.max_frame_bytes > 1024 * 1024 * 100 {
41 return Err("max_frame_bytes exceeds safe limit of 100MB".to_string());
42 }
43 if self.tool_timeout_ms < 100 {
44 return Err("tool_timeout_ms must be at least 100ms".to_string());
45 }
46 Ok(())
47 }
48}
50impl Default for Config {
51 fn default() -> Self {
52 Self::default_valid()
53 }
54}

smith-core/src/frame.rs

Modified

+502 / −172 text lines

1//! Length-prefixed CBOR session framing.
1//! Length-prefixed, checksummed CBOR session framing.
22//!
3//! Wire format: `[4-byte little-endian payload length][CBOR payload]`.
4//! Encoding is size-bounded; decoding is slice-based and reports exactly
5//! how many bytes were consumed, whether a frame is incomplete, or whether
6//! a corrupt oversized frame was skipped by its intact length.
3//! Wire format, little endian:
4//!
5//! ```text
6//! [len u32][kind u16][version u16][crc32 u32][CBOR payload]
7//! ```
8//!
9//! `len` counts every byte after itself, so a damaged frame is skipped by its
10//! declared length instead of scanning payload bytes for a plausible header.
11//! `kind` and `version` say what the payload is; `crc32` covers kind, version,
12//! and payload, which is what keeps corruption distinguishable from a frame
13//! kind that a future build introduced.
8use crate::session::Entry;
9use smith::error::{Result, SmithError};
10use std::io::Write;
15use crate::session::{Entry, SessionHeader};
16use smith::error::{FrameFault, Result, SmithError};
17use std::io::{Read, Write};
1219/// Default frame size ceiling when no configuration is supplied.
1320pub const DEFAULT_MAX_FRAME_BYTES: usize = 1024 * 1024;
15/// Maximum representable declared length (u32 LE header).
16pub const MAX_DECLARED_LENGTH: usize = u32::MAX as usize;
22/// Length of the frame length prefix.
23pub const HEADER_LEN: usize = 4;
18pub(crate) const HEADER_LEN: usize = 4;
25/// Length of the body prefix: kind, version, and checksum.
26pub const BODY_PREFIX_LEN: usize = 8;
28/// Frame kind of a session entry payload.
29pub const KIND_ENTRY: u16 = 1;
31/// Supported version of the [`KIND_ENTRY`] payload schema.
32pub const VERSION_ENTRY: u16 = 1;
34/// Frame kind of the session header payload.
35pub const KIND_SESSION_HEADER: u16 = 2;
37/// Supported version of the [`KIND_SESSION_HEADER`] payload schema.
38pub const VERSION_SESSION_HEADER: u16 = 1;
40/// Chunk size used when skipping a damaged frame body.
41const SKIP_CHUNK: usize = 64 * 1024;
2043/// A decoded session frame.
21#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
44#[derive(Clone, PartialEq, Eq, Debug)]
2245pub enum Frame {
46 /// Durable session identity; the first frame of a session file.
47 Header {
48 /// Decoded header.
49 header: SessionHeader,
50 },
2351 /// A known session entry.
2452 Known {
2553 /// Decoded entry.
2654 entry: Entry,
2755 },
28 /// An opaque future frame; raw payload is preserved unchanged.
56 /// A checksum-valid frame of a kind this build does not know.
57 /// Kind, version, and payload are preserved so it round-trips unchanged.
2958 Unknown {
59 /// Frame kind tag.
60 kind: u16,
61 /// Frame version tag.
62 version: u16,
3063 /// Exact payload bytes as read.
31 raw_bytes: Vec<u8>,
32 /// Declared payload length (equals `raw_bytes.len()`).
33 declared_length: usize,
64 payload: Vec<u8>,
3465 },
3768impl Frame {
38 /// Serialize a known entry into a frame payload, rejecting sizes above `max_frame_bytes`
69 /// Serialize a payload value, rejecting sizes above `max_frame_bytes`
3970 /// before unbounded allocation occurs.
40 pub fn encode_entry(entry: &Entry, max_frame_bytes: usize) -> Result<Vec<u8>> {
71 ///
72 /// # Errors
73 ///
74 /// Returns a [`FrameFault::TooLarge`] or [`FrameFault::Encode`] error.
75 pub fn encode_payload<T: serde::Serialize>(
76 value: &T,
77 max_frame_bytes: usize,
78 ) -> Result<Vec<u8>> {
4179 let mut limited = LimitedWriter::new(max_frame_bytes);
42 match ciborium::ser::into_writer(entry, &mut limited) {
43 Ok(()) => {}
44 Err(e) => {
45 if limited.overflowed() {
46 return Err(SmithError::FrameTooLarge {
47 max_bytes: max_frame_bytes,
48 actual: max_frame_bytes + 1,
49 });
50 }
51 return Err(SmithError::FrameEncode {
52 message: e.to_string(),
53 });
54 }
55 }
80 let result = ciborium::ser::into_writer(value, &mut limited);
5681 if limited.overflowed() {
57 return Err(SmithError::FrameTooLarge {
58 max_bytes: max_frame_bytes,
59 actual: max_frame_bytes + 1,
60 });
82 return Err(too_large(max_frame_bytes, max_frame_bytes + 1));
83 }
84 match result {
85 Ok(()) => Ok(limited.into_inner()),
86 Err(e) => Err(fault(FrameFault::Encode {
87 message: e.to_string(),
88 })),
6189 }
62 Ok(limited.into_inner())
6390 }
65 /// Encode the full frame (header + payload) enforcing `max_frame_bytes`.
92 /// Encode the full frame (length prefix, body prefix, payload) enforcing
93 /// `max_frame_bytes` on the payload.
94 ///
95 /// # Errors
96 ///
97 /// Returns a [`FrameFault::TooLarge`] or [`FrameFault::Encode`] error.
6698 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)?,
104 ),
105 Self::Known { entry } => (
106 KIND_ENTRY,
107 VERSION_ENTRY,
108 Self::encode_payload(entry, max_frame_bytes)?,
109 ),
69110 Self::Unknown {
70 raw_bytes,
71 declared_length,
111 kind,
112 version,
113 payload,
72114 } => {
73 if raw_bytes.len() != *declared_length || *declared_length > max_frame_bytes {
74 return Err(SmithError::FrameEncode {
75 message: format!(
76 "unknown frame length {} inconsistent or above limit {}",
77 declared_length, max_frame_bytes
78 ),
79 });
115 if payload.len() > max_frame_bytes {
116 return Err(too_large(max_frame_bytes, payload.len()));
80117 }
81 raw_bytes.clone()
118 (*kind, *version, payload.clone())
82119 }
83120 };
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()));
129 };
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);
87133 Ok(out)
88134 }
135}
90 /// Decode a payload into a frame. Payloads that are not valid known entries
91 /// are retained verbatim as `Unknown`.
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(),
97 raw_bytes: payload,
98 },
137/// Classify one frame body: verify the checksum first, then the kind and
138/// version, then the payload schema.
139fn 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(),
143 });
144 }
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(),
152 });
153 }
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 })
99158 }
159 (KIND_ENTRY | KIND_SESSION_HEADER, _) => {
160 Err(FrameFault::UnsupportedVersion { kind, version })
161 }
162 _ => Ok(Frame::Unknown {
163 kind,
164 version,
165 payload: payload.to_vec(),
166 }),
100167 }
103/// Outcome of decoding one frame from a byte slice.
104#[derive(Clone, PartialEq, Eq, Debug)]
105pub enum DecodeOutcome {
106 /// A frame plus the number of bytes consumed (header + payload).
107 Frame(Frame, usize),
108 /// A corrupt frame with an intact declared length above the configured limit.
109 /// The whole declared frame was skipped; the value is the consumed byte count.
110 Skipped(usize),
111 /// Fewer than one complete frame is present in the slice (torn tail).
112 Incomplete,
170fn decode_payload<T: serde::de::DeserializeOwned>(
171 payload: &[u8],
172) -> std::result::Result<T, FrameFault> {
173 ciborium::de::from_reader::<T, _>(payload).map_err(|e| FrameFault::SchemaDecode {
174 message: e.to_string(),
175 })
115/// Decode the first frame from `buf`, enforcing `max_frame_bytes`.
178/// Frames recovered from a frame stream, plus explicit damage.
116179///
117/// Oversized but fully present frames are skipped by their intact length;
118/// oversized truncated frames are reported as `Incomplete` (torn tail),
119/// never interpreted by scanning payload bytes as headers.
120pub fn decode_frame(buf: &[u8], max_frame_bytes: usize) -> DecodeOutcome {
121 if buf.len() < HEADER_LEN {
122 return DecodeOutcome::Incomplete;
123 }
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;
128 }
129 if declared > max_frame_bytes {
130 return DecodeOutcome::Skipped(total);
131 }
132 let frame = Frame::decode_payload(buf[HEADER_LEN..total].to_vec());
133 DecodeOutcome::Frame(frame, total)
180/// Damage never discards the surrounding frames: a corrupt frame is reported
181/// and skipped by its declared length, and the frames after it stay readable.
182#[derive(Clone, PartialEq, Eq, Debug, Default)]
183pub struct Recovery {
184 /// Frames recovered in stream order.
185 pub frames: Vec<Frame>,
186 /// Damage reports, each locating its frame header by byte offset.
187 pub damage: Vec<SmithError>,
188 /// Offset just past the last complete frame.
189 pub good_end: u64,
190 /// Offset where an incomplete trailing frame starts, if any.
191 pub torn_tail_at: Option<u64>,
136/// Write a full frame to a writer with an enforced size limit.
194/// Read every complete frame from `reader` with per-frame bounded allocation.
195///
196/// A torn tail ends the walk and is reported through
197/// [`Recovery::torn_tail_at`]; complete frames before it are always returned.
198pub 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);
201 loop {
202 let offset = recovery.good_end;
203 let mut header = [0u8; HEADER_LEN];
204 match read_exact_or_eof(reader, &mut header) {
205 Ok(true) => {}
206 Ok(false) => break,
207 Err(_) => {
208 recovery.torn_tail_at = Some(offset);
209 break;
210 }
211 }
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);
217 break;
218 }
219 recovery.damage.push(located(
220 FrameFault::TooLarge {
221 max_bytes: max_frame_bytes,
222 actual: declared.saturating_sub(BODY_PREFIX_LEN),
223 },
224 offset,
225 ));
226 recovery.good_end = offset + total;
227 continue;
228 }
229 let mut body = vec![0u8; declared];
230 if reader.read_exact(&mut body).is_err() {
231 recovery.torn_tail_at = Some(offset);
232 break;
233 }
234 match decode_body(&body) {
235 Ok(frame) => recovery.frames.push(frame),
236 Err(f) => recovery.damage.push(located(f, offset)),
237 }
238 recovery.good_end = offset + total;
239 }
240 recovery
241}
243/// Write a full frame to a writer with an enforced payload size limit.
244///
245/// # Errors
246///
247/// Returns a framing error when encoding or writing fails.
137248pub fn write_frame(writer: &mut impl Write, frame: &Frame, max_frame_bytes: usize) -> Result<()> {
138249 let bytes = frame.encode(max_frame_bytes)?;
139 writer
140 .write_all(&bytes)
141 .map_err(|e| SmithError::FrameEncode {
250 writer.write_all(&bytes).map_err(|e| {
251 fault(FrameFault::Encode {
142252 message: e.to_string(),
143 })?;
253 })
254 })?;
144255 Ok(())
258const fn fault(f: FrameFault) -> SmithError {
259 SmithError::Frame {
260 fault: f,
261 offset: None,
262 }
263}
265const fn located(f: FrameFault, offset: u64) -> SmithError {
266 SmithError::Frame {
267 fault: f,
268 offset: Some(offset),
269 }
270}
272const fn too_large(max_bytes: usize, actual: usize) -> SmithError {
273 fault(FrameFault::TooLarge { max_bytes, actual })
274}
276/// Read exactly `buf.len()` bytes. `Ok(false)` means clean end of stream,
277/// `Err` means a partial read, which is a torn tail.
278fn read_exact_or_eof<R: Read>(reader: &mut R, buf: &mut [u8]) -> std::io::Result<bool> {
279 let mut filled = 0;
280 while filled < buf.len() {
281 match reader.read(&mut buf[filled..]) {
282 Ok(0) => {
283 if filled == 0 {
284 return Ok(false);
285 }
286 return Err(std::io::Error::new(
287 std::io::ErrorKind::UnexpectedEof,
288 "torn frame",
289 ));
290 }
291 Ok(n) => filled += n,
292 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
293 Err(e) => return Err(e),
294 }
295 }
296 Ok(true)
297}
299/// Discard `len` bytes in bounded chunks. `false` means the stream ended early.
300fn skip_exact<R: Read>(reader: &mut R, len: usize) -> bool {
301 let mut remaining = len;
302 let mut sink = vec![0u8; 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() {
306 return false;
307 }
308 remaining -= chunk;
309 }
310 true
311}
313/// CRC-32 (IEEE 802.3, reflected) over kind, version, and payload.
314fn 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];
319 };
320 for byte in kind.to_le_bytes() {
321 step(byte);
322 }
323 for byte in version.to_le_bytes() {
324 step(byte);
325 }
326 for byte in payload {
327 step(*byte);
328 }
329 !crc
330}
332const CRC32_TABLE: [u32; 256] = {
333 let mut table = [0u32; 256];
334 let mut i: u32 = 0;
335 while i < 256 {
336 let mut value = i;
337 let mut bit = 0;
338 while bit < 8 {
339 value = if value & 1 == 1 {
340 0xEDB8_8320 ^ (value >> 1)
341 } else {
342 value >> 1
343 };
344 bit += 1;
345 }
346 table[i as usize] = value;
347 i += 1;
348 }
349 table
350};
147352/// A `Vec<u8>` writer that stops accepting bytes beyond a limit,
148353/// bounding allocation during encoding.
149354struct LimitedWriter {
155360impl LimitedWriter {
156 fn new(limit: usize) -> Self {
361 const fn new(limit: usize) -> Self {
157362 Self {
158363 buf: Vec::new(),
159364 remaining: limit,
161366 }
162367 }
164 fn overflowed(&self) -> bool {
369 const fn overflowed(&self) -> bool {
165370 self.overflow
166371 }
199404/// Deterministic JSON: recursively sort object keys so equivalent values
200405/// encode to identical CBOR regardless of insertion order.
201406pub use crate::session::canonical_json;
202408#[cfg(test)]
203#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
409#[expect(
410 clippy::unwrap_used,
411 clippy::panic,
412 reason = "tests may panic on invariant violations"
413)]
204414mod tests {
205415 use super::*;
206416 use crate::session::{Entry, EntryContent};
215425 Entry::message(msg, None)
216426 }
428 fn known_bytes(text: &str) -> Vec<u8> {
429 Frame::Known {
430 entry: Entry::message(Message::with_text(Role::User, text), None),
431 }
432 .encode(DEFAULT_MAX_FRAME_BYTES)
433 .unwrap()
434 }
436 fn text_of(frame: &Frame) -> String {
437 match frame {
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:?}"),
442 },
443 other => panic!("unexpected content {other:?}"),
444 },
445 other => panic!("unexpected frame {other:?}"),
446 }
447 }
449 fn read_all(bytes: &[u8], max_frame_bytes: usize) -> Recovery {
450 read_frames(&mut &bytes[..], max_frame_bytes)
451 }
453 #[test]
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");
458 // Flip one payload byte: the length prefix stays intact, the checksum fails.
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");
469 assert_eq!(
470 recovery.damage[0],
471 SmithError::Frame {
472 fault: FrameFault::Checksum {
473 declared_length: corrupt.len() - HEADER_LEN
474 },
475 offset: Some(corrupt_at),
476 }
477 );
478 assert_eq!(recovery.good_end, bytes.len() as u64);
479 assert_eq!(recovery.torn_tail_at, None);
480 }
482 #[test]
483 fn future_frame_round_trips_byte_for_byte() {
484 let future = Frame::Unknown {
485 kind: 0xBEEF,
486 version: 7,
487 payload: vec![0xDE, 0xAD, 0x01, 0x02],
488 };
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]);
493 assert_eq!(
494 recovery.frames[0].encode(DEFAULT_MAX_FRAME_BYTES).unwrap(),
495 bytes
496 );
497 }
218499 #[test]
219500 fn known_frame_round_trips_through_cbor() {
220501 let entry = sample_entry(true);
223504 }
224505 .encode(DEFAULT_MAX_FRAME_BYTES)
225506 .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:?}"),
232 };
233 assert_eq!(msg.blocks[0], ContentBlock::Text("hello".into()));
234 assert_eq!(msg.blocks[1], ContentBlock::Thinking("internal".into()));
235 }
236 other => panic!("unexpected outcome {other:?}"),
237 }
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);
238510 }
240512 #[test]
241 fn torn_tail_reports_incomplete() {
242 let bytes = Frame::Known {
243 entry: sample_entry(false),
244 }
245 .encode(DEFAULT_MAX_FRAME_BYTES)
246 .unwrap();
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);
247518 assert_eq!(
248 decode_frame(&bytes[..3], 1 << 20),
249 DecodeOutcome::Incomplete
250 );
251 assert_eq!(
252 decode_frame(&bytes[..bytes.len() - 1], 1 << 20),
253 DecodeOutcome::Incomplete
519 recovery.frames.iter().map(text_of).collect::<Vec<_>>(),
520 vec!["kept".to_string()]
254521 );
522 assert_eq!(recovery.torn_tail_at, Some(tail_at));
523 assert_eq!(recovery.good_end, tail_at);
525 // A partial length prefix is torn too, never a fabricated header.
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));
255532 }
257534 #[test]
258535 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);
262 // Limit 50 < 100: must skip exactly the declared frame, not scan payload.
263 match decode_frame(&bytes, 50) {
264 DecodeOutcome::Skipped(consumed) => assert_eq!(consumed, bytes.len()),
265 other => panic!("unexpected outcome {other:?}"),
266 }
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);
541 assert_eq!(
542 recovery.frames.iter().map(text_of).collect::<Vec<_>>(),
543 vec!["tail".to_string()]
544 );
545 assert_eq!(recovery.damage.len(), 1);
546 assert_eq!(recovery.damage[0].code(), "FRAME_TOO_LARGE");
547 assert_eq!(
548 recovery.damage[0],
549 SmithError::Frame {
550 fault: FrameFault::TooLarge {
551 max_bytes: 1024,
552 actual: 5000 - BODY_PREFIX_LEN
553 },
554 offset: Some(0),
555 }
556 );
557 assert_eq!(recovery.good_end, bytes.len() as u64);
558 assert_eq!(skipped, 5004);
267559 }
269561 #[test]
270 fn oversized_truncated_frame_is_incomplete_not_scanned() {
562 fn oversized_truncated_frame_is_torn_not_scanned() {
271563 let mut bytes = 200_u32.to_le_bytes().to_vec();
272564 bytes.extend_from_slice(&[0u8; 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));
274569 }
276571 #[test]
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);
580 }
582 #[test]
583 fn unsupported_entry_version_is_reported_not_preserved() {
584 let payload = vec![0xA0]; // empty CBOR map
585 let frame = Frame::Unknown {
586 kind: KIND_ENTRY,
587 version: VERSION_ENTRY + 1,
588 payload,
280589 };
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");
594 }
596 #[test]
597 fn checksum_valid_entry_with_bad_schema_is_schema_damage() {
598 let frame = Frame::Unknown {
599 kind: KIND_ENTRY,
600 version: VERSION_ENTRY,
601 payload: vec![0xA0], // valid CBOR, not an Entry
283602 };
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:?}"),
289 };
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:?}"),
294 };
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");
607 }
609 #[test]
610 fn version_one_frames_without_body_prefix_are_rejected() {
611 // Old layout: [len][CBOR payload] with no kind, version, or checksum.
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);
619 }
621 #[test]
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);
626 assert_eq!(
627 recovery.frames.iter().map(text_of).collect::<Vec<_>>(),
628 vec!["one".to_string(), "two".to_string()]
629 );
630 assert_eq!(recovery.good_end, bytes.len() as u64);
297631 }
299633 #[test]
334668 // Force identical ids/timestamps so only key order could differ.
335669 e2.id = e1.id;
336670 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();
339673 assert_eq!(b1, b2);
340674 }
342676 #[test]
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(),
348681 };
349 let bytes = frame.encode(1 << 20).unwrap();
350 match decode_frame(&bytes, 1 << 20) {
351 DecodeOutcome::Frame(
352 Frame::Unknown {
353 raw_bytes,
354 declared_length,
355 },
356 used,
357 ) => {
358 assert_eq!(raw_bytes, raw);
359 assert_eq!(declared_length, raw.len());
360 assert_eq!(used, bytes.len());
361 }
362 other => panic!("unexpected {other:?}"),
363 }
682 let bytes = Frame::Header { header }
683 .encode(DEFAULT_MAX_FRAME_BYTES)
684 .unwrap();
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());
688 }
690 #[test]
691 fn checksum_matches_known_reference_value() {
692 // CRC-32 of "123456789" is a published check value.
693 assert_eq!(crc32(0x3231, 0x3433, b"56789"), 0xCBF4_3926);
364694 }

smith-core/src/lib.rs

Modified

+12 / −32 text lines

44//! and tool lifecycle events.
66#![forbid(unsafe_code)]
7#![warn(missing_docs, unused_mut)]
8#![allow(
9 clippy::all,
10 clippy::pedantic,
11 clippy::style,
12 clippy::unwrap_used,
13 clippy::expect_used,
14 clippy::manual_map,
15 clippy::redundant_clone,
16 clippy::use_self,
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,
21 missing_docs,
22 dead_code
23)]
8/// Bounded, cancellable shell execution.
259pub mod bash;
26pub mod config;
10/// Checksummed session framing.
2711pub mod frame;
12/// Branching session state.
2813pub mod session;
14/// Durable session storage.
2915pub mod store;
16/// Tool registry, validation, and recorded effects.
3017pub mod tools;
18/// Provider-free replay evidence.
3119pub mod trace;
3321pub use bash::{BashResult, execute};
34pub use config::Config;
35pub use frame::{DecodeOutcome, Frame, decode_frame, write_frame};
36pub use session::{Branch, Entry, EntryContent, Session};
37pub use store::{SessionWriter, load_session, repair_session};
22pub use frame::{Frame, Recovery, read_frames, write_frame};
23pub use session::{Branch, COMPACTION_KIND, Entry, EntryContent, Session, SessionHeader};
24pub use store::{
25 OpenSession, SessionWriter, create_session, fork_session, load_session, open_session,
26 repair_session,
27};
3828pub use tools::{ToolOutcome, ToolRegistry, ToolSession};
3929pub use trace::{TraceKind, TraceRecord, replay};
4131#[cfg(test)]
42#[allow(clippy::unwrap_used, clippy::expect_used)]
4332mod tests {
4433 use super::*;
4534 use smith::message::{Message, Role};
5241 session.append_to_active(entry);
5342 assert_eq!(session.active_branch().entries.len(), 1);
5443 }
56 #[test]
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());
63 }

smith-core/src/session.rs

Modified

+442 / −21 text lines

1//! Branching session state, entries, and restoration from durable frames.
2
13use serde::{Deserialize, Serialize};
2use smith::{id::*, message::Message};
4use smith::error::{Result, SmithError};
5use smith::id::{BranchId, EntryId, SessionId, ToolCallId};
6use smith::message::{ContentBlock, Message};
7use std::collections::{HashMap, HashSet};
8
9/// Meta entry kind that marks a compaction boundary.
10pub const COMPACTION_KIND: &str = "compaction";
412/// Deterministic JSON: recursively sort object keys so equivalent values
513/// encode to identical CBOR regardless of insertion order.
14#[must_use]
615pub fn canonical_json(value: &serde_json::Value) -> serde_json::Value {
716 match value {
817 serde_json::Value::Object(map) => {
2130 }
33/// Durable session identity, persisted as the first frame of a session file
34/// so reload reproduces the same IDs instead of minting new ones.
35#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
36pub struct SessionHeader {
37 /// Session identifier.
38 pub session_id: SessionId,
39 /// Identifier of the root branch.
40 pub branch_id: BranchId,
41}
2443/// A session entry (message, tool call/result, or metadata).
2544#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2645pub struct Entry {
3453 pub content: EntryContent,
56/// What one entry recorded.
3757#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
3858#[serde(tag = "kind", content = "data")]
3959pub enum EntryContent {
4161 Message(Message),
4262 /// Tool call (recorded for replay).
4363 ToolCall {
64 /// Invoked tool.
4465 name: String,
66 /// Canonical tool arguments.
4567 input: serde_json::Value,
46 call_id: smith::id::ToolCallId,
68 /// Identifier pairing this call with its result.
69 call_id: ToolCallId,
4770 },
4871 /// Tool result.
4972 ToolResult {
73 /// Whether the effect succeeded.
5074 ok: bool,
75 /// Recorded output or error text.
5176 output: String,
52 call_id: smith::id::ToolCallId,
77 /// Identifier of the call this result answers.
78 call_id: ToolCallId,
5379 },
5480 /// Session metadata event (compaction, branch selection).
5581 Meta {
82 /// Metadata kind, for example [`COMPACTION_KIND`].
5683 kind: String,
84 /// Kind-specific payload.
5785 detail: serde_json::Value,
5886 },
89/// Canonicalize every JSON value an entry carries, so equivalent entries
90/// encode identically no matter how their objects were built.
91fn canonicalize(content: EntryContent) -> EntryContent {
92 match content {
93 EntryContent::ToolCall {
94 name,
95 input,
96 call_id,
97 } => EntryContent::ToolCall {
98 name,
99 input: canonical_json(&input),
100 call_id,
101 },
102 EntryContent::Meta { kind, detail } => EntryContent::Meta {
103 kind,
104 detail: canonical_json(&detail),
105 },
106 EntryContent::Message(mut message) => {
107 for block in &mut message.blocks {
108 if let ContentBlock::ToolUse { input, .. } = block {
109 *input = canonical_json(input);
110 }
111 }
112 EntryContent::Message(message)
113 }
114 other @ EntryContent::ToolResult { .. } => other,
115 }
116}
118/// Wall-clock milliseconds since the Unix epoch, saturating on overflow.
119fn now_ms() -> i64 {
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)
124 })
125}
61127impl Entry {
128 /// A new entry with canonical content and a fresh identity.
129 #[must_use]
62130 pub fn new(parent: Option<EntryId>, content: EntryContent) -> Self {
63131 Self {
64132 id: EntryId::new(),
65133 parent,
66 timestamp_ms: std::time::SystemTime::now()
67 .duration_since(std::time::UNIX_EPOCH)
68 .map(|d| d.as_millis() as i64)
69 .unwrap_or(0),
70 content,
134 timestamp_ms: now_ms(),
135 content: canonicalize(content),
71136 }
72137 }
139 /// A message entry.
140 #[must_use]
74141 pub fn message(msg: Message, parent: Option<EntryId>) -> Self {
75142 Self::new(parent, EntryContent::Message(msg))
76143 }
145 /// A compaction boundary entry. `detail` records what was summarized.
146 #[must_use]
147 pub fn compaction(parent: Option<EntryId>, detail: serde_json::Value) -> Self {
148 Self::new(
149 parent,
150 EntryContent::Meta {
151 kind: COMPACTION_KIND.to_string(),
152 detail,
153 },
154 )
155 }
157 /// Whether this entry marks a compaction boundary.
158 #[must_use]
159 pub fn is_compaction(&self) -> bool {
160 matches!(&self.content, EntryContent::Meta { kind, .. } if kind == COMPACTION_KIND)
161 }
79164/// Selected branch in a session.
87172 pub selected_idx: usize,
175impl Default for Branch {
176 fn default() -> Self {
177 Self::new()
178 }
179}
90181impl Branch {
182 /// An empty branch with a fresh identity.
183 #[must_use]
91184 pub fn new() -> Self {
92185 Self {
93186 branch_id: BranchId::new(),
96189 }
97190 }
192 /// Append `entry` and select it. Returns its index.
99193 pub fn append(&mut self, entry: Entry) -> usize {
100194 self.entries.push(entry);
101195 self.selected_idx = self.entries.len().saturating_sub(1);
102196 self.selected_idx
103197 }
199 /// The currently selected entry, if the branch has any.
200 #[must_use]
105201 pub fn selected_entry(&self) -> Option<&Entry> {
106202 self.entries.get(self.selected_idx)
107203 }
120216 pub compaction_boundary: Option<EntryId>,
219impl Default for Session {
220 fn default() -> Self {
221 Self::new()
222 }
223}
123225impl Session {
226 /// A new session with one empty branch.
227 #[must_use]
124228 pub fn new() -> Self {
125229 Self {
126230 id: SessionId::new(),
130234 }
131235 }
237 /// The selected branch.
238 #[must_use]
133239 pub fn active_branch(&self) -> &Branch {
134240 &self.branches[self.active_branch_idx]
135241 }
243 /// The selected branch, mutably.
137244 pub fn active_branch_mut(&mut self) -> &mut Branch {
138245 &mut self.branches[self.active_branch_idx]
139246 }
248 /// Append `entry` to the selected branch and select it.
141249 pub fn append_to_active(&mut self, entry: Entry) {
142250 let branch = self.active_branch_mut();
143251 branch.append(entry);
144252 }
254 /// Identifier of the selected entry, if any.
255 #[must_use]
146256 pub fn selected_id(&self) -> Option<EntryId> {
147257 self.active_branch().selected_entry().map(|e| e.id)
148258 }
260 /// Append a compaction boundary entry to the active branch and select it.
261 /// Returns the entry so callers can persist it.
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());
266 entry
267 }
269 /// Every entry of this session, regardless of branch.
270 fn entries_by_id(&self) -> HashMap<EntryId, &Entry> {
271 self.branches
272 .iter()
273 .flat_map(|branch| branch.entries.iter())
274 .map(|entry| (entry.id, entry))
275 .collect()
276 }
278 /// The root-to-`at` entry chain, or `None` when `at` is unknown or its
279 /// ancestry is broken.
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;
288 }
289 chain.reverse();
290 Some(chain)
291 }
293 /// Fork the history ending at `at` into a new session.
294 ///
295 /// Entry IDs, order, and timestamps are preserved, `at` becomes the
296 /// selected leaf, and the compaction boundary carries over when it lies
297 /// on the retained path. The new session gets fresh session and branch
298 /// identity, because it is a different durable history.
299 ///
300 /// # Errors
301 ///
302 /// Returns [`SmithError::Session`] when `at` is not part of this session.
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),
307 })?;
308 let boundary = self
309 .compaction_boundary
310 .filter(|id| entries.iter().any(|entry| entry.id == *id));
311 let selected_idx = entries.len().saturating_sub(1);
312 Ok(Self {
313 id: SessionId::new(),
314 branches: vec![Branch {
315 branch_id: BranchId::new(),
316 entries,
317 selected_idx,
318 }],
319 active_branch_idx: 0,
320 compaction_boundary: boundary,
321 })
322 }
324 /// The durable identity of this session's active branch.
325 #[must_use]
326 pub fn header(&self) -> SessionHeader {
327 SessionHeader {
328 session_id: self.id,
329 branch_id: self.active_branch().branch_id,
330 }
331 }
150333 /// Restore in-memory state from decoded frames.
151 /// Known entries keep their stored order, IDs, and parent links;
152 /// the last entry becomes the selected leaf. Unknown frames are
153 /// skipped here. `compaction` meta entries set the compaction boundary.
334 ///
335 /// A header frame restores the session and branch identity, so state
336 /// rebuilt from the same file is identical on every load. Stored parent
337 /// links define the branches: each entry with no children is a leaf, and
338 /// its root-to-leaf chain is one branch. The last stored entry is the
339 /// selected leaf of the active branch. Unknown frames are skipped here,
340 /// and compaction entries restore the compaction boundary.
341 #[must_use]
154342 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;
157346 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);
347 match frame {
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);
162352 }
353 stored.push(entry.clone());
163354 }
164 restored.push(entry.clone());
355 crate::frame::Frame::Unknown { .. } => {}
165356 }
166357 }
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)
359 }
361 /// Rebuild branches from stored entries and their parent links.
362 fn from_entries(
363 header: Option<SessionHeader>,
364 stored: &[Entry],
365 boundary: Option<EntryId>,
366 ) -> Self {
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;
371 }
372 session.compaction_boundary = boundary;
373 if stored.is_empty() {
374 return session;
375 }
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);
385 // Walk to the root; a missing parent ends the recoverable chain.
386 while let Some(id) = cursor {
387 match known.get(&id) {
388 Some(entry) => {
389 entries.push((*entry).clone());
390 cursor = entry.parent;
391 }
392 None => break,
393 }
394 }
395 entries.reverse();
396 let selected_idx = entries.len().saturating_sub(1);
397 let is_active = leaf.id == last_id;
398 if is_active {
399 active_branch_idx = branches.len();
400 }
401 branches.push(Branch {
402 // The selected branch owns the persisted identity; sibling
403 // branches derive theirs from their leaf, which keeps every
404 // reload of the same file identical.
405 branch_id: if is_active {
406 session.active_branch().branch_id
407 } else {
408 BranchId::from(leaf.id.as_uuid())
409 },
410 entries,
411 selected_idx,
412 });
413 }
414 session.branches = branches;
415 session.active_branch_idx = active_branch_idx;
170416 session
171417 }
420#[cfg(test)]
421#[expect(
422 clippy::unwrap_used,
423 clippy::panic,
424 reason = "tests may panic on invariant violations"
425)]
426mod tests {
427 use super::*;
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)
433 }
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:?}"),
440 }
441 }
443 fn frames(session: &Session) -> Vec<Frame> {
444 let mut frames = vec![Frame::Header {
445 header: session.header(),
446 }];
447 frames.extend(
448 session
449 .active_branch()
450 .entries
451 .iter()
452 .map(|entry| Frame::Known {
453 entry: entry.clone(),
454 }),
455 );
456 frames
457 }
459 #[test]
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(),
468 };
469 let session = Session::from_entries(Some(header), &stored, None);
470 assert_eq!(session.branches.len(), 2);
471 // The last stored entry selects the active branch and keeps the
472 // persisted branch identity.
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> = session
476 .active_branch()
477 .entries
478 .iter()
479 .map(|entry| entry.id)
480 .collect();
481 assert_eq!(ids, vec![root.id, second.id]);
482 let sibling = &session.branches[1 - session.active_branch_idx];
483 assert_eq!(
484 sibling.entries.iter().map(|e| e.id).collect::<Vec<_>>(),
485 vec![root.id, first.id]
486 );
487 // Reconstruction is identical on a second pass, sibling ids included.
488 let again = Session::from_entries(Some(header), &stored, None);
489 assert_eq!(again, session);
490 }
492 #[test]
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);
503 assert_eq!(
504 forked
505 .active_branch()
506 .entries
507 .iter()
508 .map(|entry| entry.id)
509 .collect::<Vec<_>>(),
510 vec![root.id, boundary.id]
511 );
512 assert_eq!(forked.selected_id(), Some(boundary.id));
513 assert_eq!(forked.compaction_boundary, Some(boundary.id));
514 assert_eq!(
515 forked
516 .active_branch()
517 .entries
518 .iter()
519 .map(text_of)
520 .collect::<Vec<_>>(),
521 vec!["1".to_string(), COMPACTION_KIND.to_string()]
522 );
524 // Forking before the boundary drops it, because it is not retained.
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);
529 // The source session is untouched.
530 assert_eq!(session.active_branch().entries.len(), 3);
531 assert_eq!(session.selected_id(), Some(after.id));
532 }
534 #[test]
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(),
541 input,
542 call_id,
543 });
544 message
545 };
546 let mut first = Entry::message(
547 block(serde_json::json!({"path": "p", "content": "c"})),
548 None,
549 );
550 let mut second = Entry::message(
551 block(serde_json::json!({"content": "c", "path": "p"})),
552 None,
553 );
554 // Only key order may differ, so encodings must match.
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)
559 {
560 b.id = a.id;
561 b.timestamp_ms = a.timestamp_ms;
562 }
563 let encode = |entry: &Entry| {
564 Frame::Known {
565 entry: entry.clone(),
566 }
567 .encode(1 << 20)
568 .unwrap()
569 };
570 assert_eq!(encode(&first), encode(&second));
571 }
573 #[test]
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");
578 }
580 #[test]
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);
588 assert_eq!(
589 restored.active_branch().branch_id,
590 session.header().branch_id
591 );
592 }
593}

smith-core/src/store.rs

Modified

+512 / −172 text lines

11//! Durable session storage: append-only writer, incremental bounded loader,
22//! and atomic repair publication.
4use crate::config::Config;
5use crate::frame::{Frame, HEADER_LEN, write_frame};
4use crate::frame::{Frame, Recovery, read_frames, write_frame};
5use crate::session::Session;
6use smith::config::Config;
67use smith::error::{Result, SmithError};
8use smith::id::EntryId;
79use std::fs::{File, OpenOptions};
8use std::io::{BufReader, Read, Seek, SeekFrom, Write};
10use std::io::{BufReader, Seek, SeekFrom, Write};
911use std::path::{Path, PathBuf};
11/// Append-only session writer with an exclusive file lock.
13/// Exclusive access to one session, held on a sidecar lock file.
14///
15/// The lock lives beside the session file rather than on it, because repair
16/// publishes a replacement inode: a lock taken on the data file would leave
17/// a waiter holding a descriptor on the replaced inode, and its appends
18/// would vanish. The sidecar is never replaced, so every participant
19/// serializes on the same object and opens the data file only after winning.
20#[derive(Debug)]
21struct SessionLock {
22 file: File,
23}
25impl SessionLock {
26 /// Acquire the lock for `path`, creating parent directories and the
27 /// sidecar as needed. Blocks while another holder owns the session.
28 fn acquire(path: &Path) -> Result<Self> {
29 if let Some(parent) = path.parent()
30 && !parent.as_os_str().is_empty()
31 {
32 std::fs::create_dir_all(parent).map_err(io_err("STORE_MKDIR"))?;
33 }
34 let file = OpenOptions::new()
35 .read(true)
36 .write(true)
37 .create(true)
38 .truncate(false)
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"))?;
42 Ok(Self { file })
43 }
44}
46impl Drop for SessionLock {
47 fn drop(&mut self) {
48 // Best-effort unlock; the OS also releases on close.
49 let _ = fs2::FileExt::unlock(&self.file);
50 }
51}
53/// Sidecar lock file path for a session file.
54fn lock_path(path: &Path) -> PathBuf {
55 let mut name = path.as_os_str().to_os_string();
56 name.push(".lock");
57 PathBuf::from(name)
58}
60/// Append-only session writer holding exclusive access to its session.
1261///
1362/// Opening repairs a torn tail (truncating to the last complete frame
1463/// boundary) before appending, so acknowledged appends are always
15/// reachable by the loader. The lock serializes concurrent writers.
64/// reachable by the loader. The lock serializes writers against each other
65/// and against repair.
66#[derive(Debug)]
1667pub struct SessionWriter {
1768 file: File,
1869 config: Config,
1970 path: PathBuf,
71 /// Held for the writer's lifetime; released on drop.
72 _lock: SessionLock,
2275impl SessionWriter {
2376 /// Open (creating parent directories) and lock the session file.
77 ///
78 /// # Errors
79 ///
80 /// Returns a configuration, locking, or input/output error.
2481 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(),
27 message: e,
28 })?;
82 Self::open_with_recovery(path, config).map(|(writer, _)| writer)
83 }
85 /// Open and lock the session file, also returning what loading recovered,
86 /// so callers do not have to walk the file a second time.
87 fn open_with_recovery<P: AsRef<Path>>(path: P, config: Config) -> Result<(Self, Recovery)> {
2988 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"))?;
33 }
34 }
89 // Win the lock before opening the data file, so a repair that is
90 // publishing a replacement cannot hand out a stale descriptor.
91 let lock = SessionLock::acquire(&path)?;
92 Self::attach(path, config, lock)
93 }
95 /// Take over an already-locked session file.
96 fn attach(path: PathBuf, config: Config, lock: SessionLock) -> Result<(Self, Recovery)> {
97 // Validation already names the offending field path.
98 config.validate()?;
3599 let mut file = OpenOptions::new()
36100 .read(true)
37101 .write(true)
39103 .truncate(false)
40104 .open(&path)
41105 .map_err(io_err("STORE_OPEN"))?;
42 use fs2::FileExt;
43 file.lock_exclusive().map_err(io_err("STORE_LOCK"))?;
44 // Repair torn tail before appending so new frames stay reachable.
45 let good_end = scan_and_fix_tail(&mut file, config.max_frame_bytes)?;
46 file.seek(SeekFrom::Start(good_end))
106 // Drop a torn tail before appending so new frames stay reachable.
107 // Complete but damaged frames are left in place and stay reported.
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"))?;
113 }
114 file.seek(SeekFrom::Start(recovery.good_end))
47115 .map_err(io_err("STORE_SEEK"))?;
48 Ok(Self { file, config, path })
116 Ok((
117 Self {
118 file,
119 config,
120 path,
121 _lock: lock,
122 },
123 recovery,
124 ))
49125 }
51127 /// Append one frame. The encoded size is checked against the configured
52128 /// limit before any bytes are written; a rejected frame leaves the file
53129 /// unchanged.
130 ///
131 /// # Errors
132 ///
133 /// Returns a framing error for oversized frames, or an input/output error.
54134 pub fn append_frame(&mut self, frame: &Frame) -> Result<()> {
55135 let bytes = frame.encode(self.config.max_frame_bytes)?;
56136 self.file.write_all(&bytes).map_err(io_err("STORE_WRITE"))?;
59139 }
61141 /// Path of the underlying session file.
142 #[must_use]
62143 pub fn path(&self) -> &Path {
63144 &self.path
64145 }
67impl Drop for SessionWriter {
68 fn drop(&mut self) {
69 // Best-effort unlock; the OS also releases on close.
70 let _ = fs2::FileExt::unlock(&self.file);
71 }
148/// A session file opened for use.
149#[derive(Debug)]
150pub struct OpenSession {
151 /// Restored, or newly created, session state.
152 pub session: Session,
153 /// Locked writer positioned after the last complete frame.
154 pub writer: SessionWriter,
155 /// Damage and torn-tail information found while loading.
156 pub recovery: Recovery,
74/// Load all frames incrementally with per-frame bounded allocation.
159/// Open a session file, writing a header frame when the file is new.
75160///
76/// Complete frames are returned in order; a torn tail (partial header or
77/// payload) is dropped. Corrupt frames with intact declared lengths above
78/// `max_frame_bytes` are skipped by length when fully present, never scanned.
79pub fn load_session(path: &Path, max_frame_bytes: usize) -> Result<Vec<Frame>> {
161/// Reopening restores the persisted session and branch IDs, so state
162/// reconstructed from the same file is identical on every load. A file that
163/// holds frames but no header cannot be attributed to a session and fails
164/// explicitly instead of silently becoming a new session.
165///
166/// # Errors
167///
168/// Returns [`SmithError::Session`] when the file holds frames but no header,
169/// or a locking, framing, or input/output error.
170pub fn open_session(path: &Path, config: Config) -> Result<OpenSession> {
171 let (mut writer, recovery) = SessionWriter::open_with_recovery(path, config)?;
172 let has_header = recovery
173 .frames
174 .iter()
175 .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(),
182 })?;
183 session
184 } else {
185 return Err(SmithError::Session {
186 code: "SESSION_HEADER_MISSING".to_string(),
187 message: format!("{} holds frames but no session header", path.display()),
188 });
189 };
190 Ok(OpenSession {
191 session,
192 writer,
193 recovery,
194 })
195}
197/// Publish `session` as a new session file and open it for appending.
198///
199/// The file is written completely and then published by rename, so an
200/// interrupted fork leaves no half-written session behind. An existing
201/// non-empty target is refused rather than overwritten.
202///
203/// # Errors
204///
205/// Returns [`SmithError::Session`] when the target already holds a session,
206/// or a locking, framing, or input/output error.
207pub 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()),
213 });
214 }
215 let tmp = path.with_extension("smith-create.tmp");
216 {
217 let mut out = File::create(&tmp).map_err(io_err("CREATE_TMP"))?;
218 write_frame(
219 &mut out,
220 &Frame::Header {
221 header: session.header(),
222 },
223 config.max_frame_bytes,
224 )?;
225 for entry in &session.active_branch().entries {
226 write_frame(
227 &mut out,
228 &Frame::Known {
229 entry: entry.clone(),
230 },
231 config.max_frame_bytes,
232 )?;
233 }
234 out.sync_all().map_err(io_err("CREATE_SYNC"))?;
235 }
236 std::fs::rename(&tmp, path).map_err(io_err("CREATE_PUBLISH"))?;
237 let (writer, recovery) = SessionWriter::attach(path.to_path_buf(), config, lock)?;
238 Ok(OpenSession {
239 session: Session::from_frames(&recovery.frames),
240 writer,
241 recovery,
242 })
243}
245/// Fork the history of `source` ending at `at` into a new session file.
246///
247/// # Errors
248///
249/// Returns [`SmithError::Session`] when `at` is unknown or the target already
250/// holds a session, or a locking, framing, or input/output error.
251pub fn fork_session(
252 source: &Session,
253 at: EntryId,
254 path: &Path,
255 config: Config,
256) -> Result<OpenSession> {
257 let forked = source.fork_at(at)?;
258 create_session(path, &forked, config)
259}
261/// Load a session file, returning recovered frames and explicit damage.
262///
263/// Complete frames are returned in order with per-frame bounded allocation.
264/// A torn tail is located rather than dropped silently, and corrupt or
265/// oversized frames are reported with their byte offsets while the frames
266/// around them stay readable.
267///
268/// # Errors
269///
270/// Returns an input/output error when the file cannot be opened.
271pub fn load_session(path: &Path, max_frame_bytes: usize) -> Result<Recovery> {
80272 let file = File::open(path).map_err(io_err("STORE_OPEN"))?;
81273 let mut reader = BufReader::with_capacity(64 * 1024, file);
82 let mut frames = Vec::new();
83 loop {
84 let mut header = [0u8; HEADER_LEN];
85 match read_exact_or_eof(&mut reader, &mut header) {
86 Ok(true) => {}
87 // Clean EOF or torn partial header: stop with complete frames.
88 _ => break,
89 }
90 let declared = u32::from_le_bytes(header) as usize;
91 if declared > max_frame_bytes {
92 // Bounded skip by intact length; incomplete means torn tail.
93 let mut remaining = declared as u64;
94 loop {
95 if remaining == 0 {
96 break;
97 }
98 let chunk = remaining.min(64 * 1024) as usize;
99 let mut sink = vec![0u8; chunk];
100 match reader.read_exact(&mut sink) {
101 Ok(()) => remaining -= chunk as u64,
102 Err(_) => return Ok(frames), // torn: stop before this frame
103 }
104 }
105 continue;
106 }
107 let mut chunk = vec![0u8; declared];
108 match reader.read_exact(&mut chunk) {
109 Ok(()) => frames.push(Frame::decode_payload(chunk)),
110 Err(_) => return Ok(frames), // torn tail: drop partial frame
111 }
112 }
113 Ok(frames)
274 Ok(read_frames(&mut reader, max_frame_bytes))
116/// Repair a session file: recover all complete frames and atomically publish
117/// a rewritten file containing exactly those frames. Returns the recovered
118/// frames. The original content stays intact if any step fails before rename.
119pub fn repair_session(path: &Path, max_frame_bytes: usize) -> Result<Vec<Frame>> {
120 let frames = load_session(path, max_frame_bytes)?;
277/// Repair a session file by republishing only its complete frames.
278///
279/// Damaged frames are dropped and returned in [`Recovery::damage`]. The
280/// original content stays intact if any step fails before publication.
281/// Repair takes the session lock, so it waits for a live writer to finish
282/// instead of replacing the file underneath it.
283///
284/// # Errors
285///
286/// Returns a locking, framing, or input/output error.
287pub 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)?;
121290 let tmp = path.with_extension("smith-repair.tmp");
122291 {
123292 let mut out = File::create(&tmp).map_err(io_err("REPAIR_CREATE"))?;
124 for frame in &frames {
293 for frame in &recovery.frames {
125294 write_frame(&mut out, frame, max_frame_bytes)?;
126295 }
127296 out.sync_all().map_err(io_err("REPAIR_SYNC"))?;
128297 }
129298 std::fs::rename(&tmp, path).map_err(io_err("REPAIR_PUBLISH"))?;
130 Ok(frames)
299 Ok(recovery)
133/// Scan the file for the last complete frame boundary; truncate a torn tail.
134/// Returns the byte offset to append at.
135fn scan_and_fix_tail(file: &File, max_frame_bytes: usize) -> Result<u64> {
136 let len = file.metadata().map_err(io_err("STORE_STAT"))?.len();
137 let mut reader =
138 BufReader::with_capacity(64 * 1024, file.try_clone().map_err(io_err("STORE_OPEN"))?);
139 let mut good_end: u64 = 0;
140 loop {
141 let header_start = reader.stream_position().map_err(io_err("STORE_READ"))?;
142 let mut header = [0u8; HEADER_LEN];
143 // Clean EOF or torn partial header both end the good region.
144 if !read_exact_or_eof(&mut reader, &mut header).unwrap_or(false) {
145 break;
146 }
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![0u8; chunk];
154 match reader.read_exact(&mut sink) {
155 Ok(()) => remaining -= chunk as u64,
156 Err(_) => {
157 complete = false;
158 break;
159 }
160 }
161 }
162 if !complete {
163 // Torn tail: caller truncates to the last good boundary.
164 break;
165 }
166 let _ = max_frame_bytes; // oversized-but-complete frames are skipped, not tail
167 good_end = header_start + total;
168 }
169 if good_end < len {
170 file.set_len(good_end).map_err(io_err("STORE_TRUNCATE"))?;
171 }
172 Ok(good_end)
173}
175/// Read exactly `buf.len()` bytes. Returns Ok(false) on immediate EOF,
176/// Err on partial read (torn).
177fn read_exact_or_eof<R: Read>(reader: &mut R, buf: &mut [u8]) -> std::io::Result<bool> {
178 let mut filled = 0;
179 while filled < buf.len() {
180 match reader.read(&mut buf[filled..]) {
181 Ok(0) => {
182 if filled == 0 {
183 return Ok(false);
184 }
185 return Err(std::io::Error::new(
186 std::io::ErrorKind::UnexpectedEof,
187 "torn header",
188 ));
189 }
190 Ok(n) => filled += n,
191 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
192 Err(e) => return Err(e),
193 }
194 }
195 Ok(true)
302/// Walk an already-open file from its start using the shared frame reader.
303///
304/// # Errors
305///
306/// Returns an input/output error when the file cannot be re-read.
307fn walk_file(file: &File, max_frame_bytes: usize) -> Result<Recovery> {
308 let mut handle = file.try_clone().map_err(io_err("STORE_OPEN"))?;
309 handle
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))
198316fn io_err(code: &'static str) -> impl Fn(std::io::Error) -> SmithError {
205323#[cfg(test)]
206#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
324#[expect(
325 clippy::unwrap_used,
326 clippy::panic,
327 reason = "tests may panic on invariant violations"
328)]
207329mod tests {
208330 use super::*;
209331 use crate::session::{Entry, EntryContent, Session};
223345 Frame::Known { entry: entry(text) }
224346 }
348 fn text_of(frame: &Frame) -> String {
349 match frame {
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:?}"),
354 },
355 other => panic!("unexpected content {other:?}"),
356 },
357 other => panic!("unexpected frame {other:?}"),
358 }
359 }
226361 #[test]
227362 fn append_load_round_trip_preserves_entries() {
228363 let path = tmp_path("round_trip.smh");
229364 let _ = std::fs::remove_file(&path);
230365 let cfg = Config::default_valid();
366 let first = entry("one");
367 let second = Entry::message(Message::with_text(Role::User, "two"), Some(first.id));
231368 {
232369 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(),
372 })
373 .unwrap();
374 w.append_frame(&Frame::Known {
375 entry: second.clone(),
376 })
377 .unwrap();
235378 }
236 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
379 let frames = load_session(&path, cfg.max_frame_bytes).unwrap().frames;
237380 assert_eq!(frames.len(), 2);
238381 let session = Session::from_frames(&frames);
239 assert_eq!(session.active_branch().entries.len(), 2);
240382 assert_eq!(
241 session.active_branch().entries[1].id,
242 session.selected_id().unwrap()
383 session
384 .active_branch()
385 .entries
386 .iter()
387 .map(|e| e.id)
388 .collect::<Vec<_>>(),
389 vec![first.id, second.id]
243390 );
391 assert_eq!(session.selected_id(), Some(second.id));
244392 let _ = std::fs::remove_file(&path);
245393 }
259407 }
260408 .encode(cfg.max_frame_bytes)
261409 .unwrap();
262 let mut torn = good.clone();
410 let mut torn = good;
263411 torn.extend_from_slice(&[0x10, 0x00, 0x00, 0x00, 0xAA, 0xBB]);
264412 std::fs::write(&path, &torn).unwrap();
265413 {
267415 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
268416 w.append_frame(&frame("after")).unwrap();
269417 }
270 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
418 let frames = load_session(&path, cfg.max_frame_bytes).unwrap().frames;
271419 let texts: Vec<String> = frames
272420 .iter()
273421 .filter_map(|f| match f {
290438 let path = tmp_path("loader_torn.smh");
291439 let cfg = Config::default_valid();
292440 let good = frame("a").encode(cfg.max_frame_bytes).unwrap();
293 let mut bytes = good.clone();
441 let mut bytes = good;
294442 bytes.extend_from_slice(&[0xFF, 0xFF]); // partial header
295443 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;
297445 assert_eq!(frames.len(), 1);
298446 let _ = std::fs::remove_file(&path);
299447 }
449 #[test]
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();
454 {
455 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
456 w.append_frame(&frame("one")).unwrap();
457 w.append_frame(&frame("two")).unwrap();
458 }
459 {
460 // Reopening must not mistake a later frame boundary for a torn tail.
461 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
462 w.append_frame(&frame("three")).unwrap();
463 }
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);
469 }
301471 #[test]
302472 fn oversized_complete_frame_is_skipped_and_following_frames_reachable() {
303473 let path = tmp_path("oversized_skip.smh");
306476 bytes.extend_from_slice(&vec![0xAB_u8; 5000]);
307477 bytes.extend_from_slice(&frame("tail").encode(1 << 20).unwrap());
308478 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");
312483 let _ = std::fs::remove_file(&path);
313484 }
317488 let path = tmp_path("repair.smh");
318489 let cfg = Config::default_valid();
319490 let good = frame("a").encode(cfg.max_frame_bytes).unwrap();
320 let mut bytes = good.clone();
491 let mut bytes = good;
321492 bytes.extend_from_slice(&frame("b").encode(cfg.max_frame_bytes).unwrap()[..6]);
322493 std::fs::write(&path, &bytes).unwrap();
323494 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));
326498 let after = std::fs::metadata(&path).unwrap().len();
327499 assert!(after < before);
328 assert_eq!(load_session(&path, cfg.max_frame_bytes).unwrap().len(), 1);
500 assert_eq!(
501 load_session(&path, cfg.max_frame_bytes)
502 .unwrap()
503 .frames
504 .len(),
505 1
506 );
329507 let _ = std::fs::remove_file(&path);
330508 }
349527 let err = w.append_frame(&Frame::Known { entry: big }).unwrap_err();
350528 assert_eq!(err.code(), "FRAME_TOO_LARGE");
351529 }
352 assert_eq!(load_session(&path, cfg.max_frame_bytes).unwrap().len(), 1);
530 assert_eq!(
531 load_session(&path, cfg.max_frame_bytes)
532 .unwrap()
533 .frames
534 .len(),
535 1
536 );
353537 let _ = std::fs::remove_file(&path);
354538 }
358542 let path = tmp_path("locked.smh");
359543 let _ = std::fs::remove_file(&path);
360544 let cfg = Config::default_valid();
361 let _w1 = SessionWriter::open(&path, cfg.clone()).unwrap();
362 // While the first writer holds the lock, an independent handle cannot
363 // take it: writers cannot interleave frames.
545 let writer = SessionWriter::open(&path, cfg).unwrap();
546 // While the first writer holds the session, an independent handle
547 // cannot take it: writers cannot interleave frames.
364548 let probe = OpenOptions::new()
365549 .read(true)
366550 .write(true)
367 .open(&path)
551 .open(lock_path(&path))
368552 .unwrap();
369 use fs2::FileExt;
370 assert!(probe.try_lock_exclusive().is_err());
371 drop(_w1);
553 assert!(fs2::FileExt::try_lock_exclusive(&probe).is_err());
554 drop(writer);
555 assert!(fs2::FileExt::try_lock_exclusive(&probe).is_ok());
372556 let _ = std::fs::remove_file(&path);
373557 }
559 #[test]
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());
572 // The repair thread must block here; an append after it started is
573 // still committed to the file the repair will republish.
574 std::thread::sleep(std::time::Duration::from_millis(150));
575 writer.append_frame(&frame("two")).unwrap();
576 drop(writer);
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));
585 }
375587 #[test]
376588 fn unknown_frames_survive_write_and_load() {
377589 let path = tmp_path("unknown_frames.smh");
378590 let _ = std::fs::remove_file(&path);
379591 let cfg = Config::default_valid();
380592 let unknown = Frame::Unknown {
381 declared_length: 6,
382 raw_bytes: vec![1, 2, 3, 4, 5, 6],
593 kind: 0x4242,
594 version: 3,
595 payload: vec![1, 2, 3, 4, 5, 6],
383596 };
384597 {
385598 let mut w = SessionWriter::open(&path, cfg.clone()).unwrap();
386599 w.append_frame(&unknown).unwrap();
387600 w.append_frame(&frame("known")).unwrap();
388601 }
389 let frames = load_session(&path, cfg.max_frame_bytes).unwrap();
602 let frames = load_session(&path, cfg.max_frame_bytes).unwrap().frames;
390603 assert_eq!(frames.len(), 2);
391604 match &frames[0] {
392605 Frame::Unknown {
393 raw_bytes,
394 declared_length,
606 kind,
607 version,
608 payload,
395609 } => {
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));
398612 }
399613 other => panic!("expected unknown frame, got {other:?}"),
400614 }
420634 let session_path = dir.join("e2e.smh");
421635 let _ = std::fs::remove_file(&session_path);
422636 let cfg = Config::default_valid();
637 let opened_id;
423638 {
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(
642 workdir.clone(),
643 opened.session,
644 opened.writer,
645 );
426646 ts.invoke(
427647 "write",
428 serde_json::json!({"path": "out/hello.txt", "content": "hi"}),
648 &serde_json::json!({"path": "out/hello.txt", "content": "hi"}),
429649 )
430650 .unwrap();
431 ts.invoke("read", serde_json::json!({"path": "out/hello.txt"}))
651 ts.invoke("read", &serde_json::json!({"path": "out/hello.txt"}))
432652 .unwrap();
433653 }
434 let frames = load_session(&session_path, cfg.max_frame_bytes).unwrap();
435 assert_eq!(frames.len(), 4); // call+result x2
654 let frames = load_session(&session_path, cfg.max_frame_bytes)
655 .unwrap()
656 .frames;
657 assert_eq!(frames.len(), 5); // header + call/result x2
436658 let restored = Session::from_frames(&frames);
659 assert_eq!(restored.id, opened_id);
437660 assert_eq!(restored.active_branch().entries.len(), 4);
438661 // Tool call/result pairs stay adjacent and ordered.
439662 let kinds: Vec<&str> = restored
456679 let _ = std::fs::remove_dir_all(&dir);
457680 }
682 #[test]
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();
687 let created = {
688 let mut opened = open_session(&path, cfg.clone()).unwrap();
689 opened.writer.append_frame(&frame("one")).unwrap();
690 opened.session
691 };
692 // The lock is exclusive, so each load owns the file for its lifetime.
693 let first = {
694 let opened = open_session(&path, cfg.clone()).unwrap();
695 opened.session
696 };
697 let second = {
698 let opened = open_session(&path, cfg).unwrap();
699 opened.session
700 };
701 assert_eq!(first.id, created.id);
702 assert_eq!(
703 first.active_branch().branch_id,
704 created.active_branch().branch_id
705 );
706 assert_eq!(second.id, first.id);
708 // Replay evidence is byte-stable across independent loads.
709 let encode = |session: &Session| {
710 let mut bytes = Vec::new();
711 ciborium::ser::into_writer(&crate::trace::replay(session), &mut bytes).unwrap();
712 bytes
713 };
714 assert_eq!(encode(&first), encode(&second));
715 let _ = std::fs::remove_file(&path);
716 }
718 #[test]
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());
731 opened
732 .writer
733 .append_frame(&Frame::Known { entry: root })
734 .unwrap();
735 let boundary = opened
736 .session
737 .append_compaction(serde_json::json!({"kept": 1}));
738 opened
739 .writer
740 .append_frame(&Frame::Known {
741 entry: boundary.clone(),
742 })
743 .unwrap();
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());
747 opened
748 .writer
749 .append_frame(&Frame::Known { entry: tip })
750 .unwrap();
751 assert_ne!(root_id, tip_id);
752 (opened.session, boundary.id, tip_id)
753 };
755 let fork_id = {
756 let forked =
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());
762 forked.session.id
763 };
765 // The fork is durable: reopening restores the same identity and leaf.
766 {
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));
772 }
774 // The source keeps its own identity, tip, and entry count.
775 {
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);
780 }
782 // A populated target is refused instead of overwritten.
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);
786 }
788 #[test]
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);
796 }
459798 #[test]
460799 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);
462802 }

smith-core/src/tools.rs

Modified

+631 / −118 text lines

44use crate::frame::{Frame, canonical_json};
55use crate::session::{Entry, EntryContent, Session};
66use crate::store::SessionWriter;
7use smith::config::Config;
78use smith::error::{Result, SmithError};
89use smith::id::ToolCallId;
9use smith::tool::ToolMetadata;
10use smith::tool::{CancelHandle, ToolMetadata};
1011use std::collections::HashMap;
1112use std::fs;
1213use std::io::{BufRead, BufReader, Write};
1718const DEFAULT_OUTPUT_CAP: usize = 64 * 1024;
1819const MAX_LIST_ENTRIES: usize = 1000;
1920const MAX_GREP_MATCHES: usize = 200;
20const MAX_EDIT_FILE_BYTES: usize = 8 * 1024 * 1024;
21const MAX_EDIT_FILE_BYTES: u64 = 8 * 1024 * 1024;
2223/// Registry of available tools.
2324#[derive(Clone, Debug, Default)]
2930impl ToolRegistry {
3031 /// An empty registry.
32 #[must_use]
3133 pub fn new() -> Self {
3234 Self::default()
3335 }
3840 }
4042 /// A registry with the seven built-in coding tools and real schemas.
43 #[must_use]
4144 pub fn with_builtins() -> Self {
4245 let mut reg = Self::new();
4346 for meta in builtin_tools() {
5053/// Built-in tool definitions with schemas used for argument validation.
54#[must_use]
5155pub fn builtin_tools() -> Vec<ToolMetadata> {
5256 let object = |required: &[&str], props: serde_json::Value| {
5357 serde_json::json!({
122126 writer: Option<SessionWriter>,
123127 /// All file effects resolve relative to this directory.
124128 pub working_dir: PathBuf,
129 config: Config,
130 cancel: CancelHandle,
131 /// What `read` and `write` last observed per file, used to reject edits
132 /// whose input describes an older version of the file.
133 observed: HashMap<PathBuf, FileVersion>,
134}
136/// Cheap identity of a file version: size plus modification time.
137#[derive(Clone, Copy, PartialEq, Eq, Debug)]
138struct FileVersion {
139 len: u64,
140 modified_ms: i64,
141}
143impl FileVersion {
144 fn of(path: &Path) -> Option<Self> {
145 let meta = fs::metadata(path).ok()?;
146 let modified_ms = meta
147 .modified()
148 .ok()?
149 .duration_since(std::time::UNIX_EPOCH)
150 .ok()?
151 .as_millis();
152 Some(Self {
153 len: meta.len(),
154 modified_ms: i64::try_from(modified_ms).unwrap_or(i64::MAX),
155 })
156 }
127159impl ToolSession {
132164 session: Session::new(),
133165 writer: None,
134166 working_dir: working_dir.into(),
167 config: Config::default_valid(),
168 cancel: CancelHandle::new(),
169 observed: HashMap::new(),
135170 }
136171 }
138 /// Attach a durable writer; every recorded entry is appended to it.
139 pub fn with_writer(working_dir: impl Into<PathBuf>, writer: SessionWriter) -> Self {
173 /// Use `config` for effect timeouts and frame limits.
174 #[must_use]
175 pub fn with_config(mut self, config: Config) -> Self {
176 self.config = config;
177 self
178 }
180 /// A handle that aborts in-flight and subsequent effects of this session.
181 #[must_use]
182 pub fn cancel_handle(&self) -> CancelHandle {
183 self.cancel.clone()
184 }
186 /// Continue an existing session, appending every recorded entry to its
187 /// durable writer.
188 pub fn with_session(
189 working_dir: impl Into<PathBuf>,
190 session: Session,
191 writer: SessionWriter,
192 ) -> Self {
140193 Self {
194 session,
141195 writer: Some(writer),
142196 ..Self::new(working_dir)
143197 }
151205 /// Validate arguments against the registered schema (required fields and
152206 /// declared property types) before any effect can run.
207 ///
208 /// # Errors
209 ///
210 /// Returns [`SmithError::Tool`] for unknown tools, non-object input,
211 /// missing required fields, or mismatched field types.
153212 pub fn validate(&self, name: &str, input: &serde_json::Value) -> Result<()> {
154213 let meta = self.registry.tools.get(name).ok_or_else(|| {
155214 tool_err(
181240 .get(key)
182241 .and_then(|p| p.get("type"))
183242 .and_then(|t| t.as_str())
243 && !json_type_matches(expected, value)
184244 {
185 if !json_type_matches(expected, value) {
245 {
186246 return Err(tool_err(
187247 "VALIDATION",
188248 format!("field '{key}' for tool '{name}' must be of type {expected}"),
197257 /// Validate, execute, and durably record one tool call.
198258 ///
199 /// Recording order: call entry, effect, result entry. If the effect
200 /// succeeds but any recording step fails, an explicit `RECORD_FAILED`
201 /// error is returned instead of an unrecorded success.
202 pub fn invoke(&mut self, name: &str, input: serde_json::Value) -> Result<ToolOutcome> {
203 self.validate(name, &input)?;
259 /// Recording order is call entry, effect, result entry, so a recorded
260 /// call always precedes the effect it describes. A cancelled session
261 /// refuses to start an effect. If the effect runs but its result cannot
262 /// be recorded, the error states whether host state was already mutated,
263 /// instead of presenting an unrecorded success.
264 ///
265 /// # Errors
266 ///
267 /// Returns [`SmithError::Cancelled`] when the session was cancelled,
268 /// [`SmithError::RecordFailed`] when a completed effect could not be
269 /// recorded, or the effect's own error.
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);
274 }
204275 let call_id = ToolCallId::new();
205 let canonical_input = canonical_json(&input);
276 let canonical_input = canonical_json(input);
206277 let parent = self.session.selected_id();
207 // Execute the effect.
208 let effect = execute_file_effect(name, &canonical_input, &self.working_dir);
278 self.record_entry(Entry::new(
279 parent,
280 EntryContent::ToolCall {
281 name: name.to_string(),
282 input: canonical_input.clone(),
283 call_id,
284 },
285 ))?;
286 let effect = execute_effect(
287 name,
288 &canonical_input,
289 &self.working_dir,
290 &self.config,
291 &self.cancel,
292 &mut self.observed,
293 );
209294 let ok = effect.is_ok();
210295 let output = match &effect {
211296 Ok(text) => text.clone(),
218303 output: output.clone(),
219304 timestamp_ms: now_ms(),
220305 };
221 // Record call entry.
222 self.record_entry(Entry::new(
223 parent,
224 EntryContent::ToolCall {
225 name: name.to_string(),
226 input: canonical_input,
227 call_id,
228 },
229 ))?;
230 // Record result entry.
231306 self.record_entry(Entry::new(
232307 self.session.selected_id(),
233308 EntryContent::ToolResult {
235310 output,
236311 call_id,
237312 },
238 ))?;
313 ))
314 .map_err(|err| SmithError::RecordFailed {
315 tool: name.to_string(),
316 mutation_applied: ok && mutates_host(name),
317 message: err.to_string(),
318 })?;
239319 effect.map(move |_| outcome)
240320 }
301381/// Execute a built-in file effect. All outputs are bounded and deterministic;
302382/// filesystem errors are surfaced, never converted to empty success.
303fn execute_file_effect(
383/// Tools whose successful effect changes host state.
384fn mutates_host(name: &str) -> bool {
385 matches!(name, "write" | "edit" | "bash")
386}
388fn execute_effect(
304389 name: &str,
305390 input: &serde_json::Value,
306391 working_dir: &Path,
392 config: &Config,
393 cancel: &CancelHandle,
394 observed: &mut HashMap<PathBuf, FileVersion>,
307395) -> std::result::Result<String, SmithError> {
308396 let path_str = input.get("path").and_then(|v| v.as_str()).unwrap_or("");
309397 match name {
310 "read" => {
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;
313 let limit = input
314 .get("limit")
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 = input
319 .get("max_bytes")
320 .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)
324 }
325 "write" => {
326 let content = input
327 .get("content")
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()))
333 }
334 "edit" => {
335 let old = input
336 .get("old_string")
337 .and_then(|v| v.as_str())
338 .unwrap_or_default();
339 let new = input
340 .get("new_string")
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)
345 }
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),
346402 "ls" => {
347 let dir = if path_str.is_empty() {
348 working_dir.to_path_buf()
349 } else {
350 resolve_path(path_str, working_dir)
351 };
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"))?
356 .into_iter()
357 .map(|e| e.file_name().to_string_lossy().into_owned())
358 .collect();
359 names.sort();
403 let dir = directory_or(path_str, working_dir);
404 if !dir.is_dir() {
405 return Err(tool_err(
406 "LS_ERROR",
407 format!("{} is not a directory", dir.display()),
408 ));
409 }
410 let names = walk_relative(&dir, Some(1), config, cancel, "LS_ERROR")?;
360411 Ok(bounded_join(names, MAX_LIST_ENTRIES))
361412 }
362413 "find" => {
364415 .get("pattern")
365416 .and_then(|v| v.as_str())
366417 .unwrap_or_default();
367 let root = if path_str.is_empty() {
368 working_dir.to_path_buf()
369 } else {
370 resolve_path(path_str, working_dir)
371 };
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);
419 if !root.is_dir() {
420 return Err(tool_err(
421 "FIND_ERROR",
422 format!("{} is not a directory", root.display()),
423 ));
424 }
425 let names = walk_relative(&root, None, config, cancel, "FIND_ERROR")?
376426 .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))
379428 .collect();
380 names.sort();
381429 Ok(bounded_join(names, MAX_LIST_ENTRIES))
382430 }
383431 "grep" => {
385433 .get("query")
386434 .and_then(|v| v.as_str())
387435 .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)
439 } else {
440 grep_bounded(&target, query)
441 }
390442 }
391443 _ => Err(tool_err(
392444 "TOOL_NOT_IMPLEMENTED",
395447 }
450/// Read a bounded window and remember the version that was shown.
451fn read_effect(
452 input: &serde_json::Value,
453 path: PathBuf,
454 observed: &mut HashMap<PathBuf, FileVersion>,
455) -> std::result::Result<String, SmithError> {
456 let count = |key: &str| {
457 input
458 .get(key)
459 .and_then(serde_json::Value::as_u64)
460 .map(|value| usize::try_from(value).unwrap_or(usize::MAX))
461 };
462 let text = read_bounded(
463 &path,
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)),
467 )?;
468 remember(path, observed);
469 Ok(text)
470}
472/// Replace a file atomically and remember the version just written.
473fn write_effect(
474 input: &serde_json::Value,
475 path: PathBuf,
476 observed: &mut HashMap<PathBuf, FileVersion>,
477) -> std::result::Result<String, SmithError> {
478 let content = input
479 .get("content")
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()))
485}
487/// Apply an exact replacement, refusing input that describes an older
488/// version of the file.
489///
490/// An edit describes a file the caller has seen. If the file moved on since
491/// then, applying the replacement would silently discard the newer content.
492fn edit_effect(
493 input: &serde_json::Value,
494 path: PathBuf,
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)
500 {
501 return Err(tool_err(
502 "STALE_INPUT",
503 format!(
504 "{} changed since it was last read; read it again before editing",
505 path.display()
506 ),
507 ));
508 }
509 let result = edit_exact(&path, text("old_string"), text("new_string"))?;
510 remember(path, observed);
511 Ok(result)
512}
514/// Record the current version of `path` as the one the caller has seen.
515fn remember(path: PathBuf, observed: &mut HashMap<PathBuf, FileVersion>) {
516 if let Some(version) = FileVersion::of(&path) {
517 observed.insert(path, version);
518 }
519}
521/// The requested path, or the invocation directory when none was given.
522fn directory_or(path_str: &str, working_dir: &Path) -> PathBuf {
523 if path_str.is_empty() {
524 working_dir.to_path_buf()
525 } else {
526 resolve_path(path_str, working_dir)
527 }
528}
530/// Ignore-aware, deterministic walk of `root`.
531///
532/// Traversal order is sorted by path, and configured ignore files and hidden
533/// entries are honored, so identical trees always produce identical results.
534fn 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);
537 builder
538 .max_depth(max_depth)
539 .hidden(!config.include_hidden)
540 .ignore(respect)
541 .git_ignore(respect)
542 .git_global(respect)
543 .git_exclude(respect)
544 .parents(respect)
545 // Honor ignore files even outside a checkout, so listing behavior
546 // does not depend on whether a VCS happens to be present.
547 .require_git(false)
548 .sort_by_file_path(std::cmp::Ord::cmp);
549 builder.build()
550}
552/// Paths under `root`, relative to it, bounded and cancellable.
553fn walk_relative(
554 root: &Path,
555 max_depth: Option<usize>,
556 config: &Config,
557 cancel: &CancelHandle,
558 code: &'static str,
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);
564 }
565 let found = found.map_err(|e| tool_err(code, e.to_string()))?;
566 if found.depth() == 0 {
567 continue;
568 }
569 names.push(
570 found
571 .path()
572 .strip_prefix(root)
573 .unwrap_or_else(|_| found.path())
574 .to_string_lossy()
575 .into_owned(),
576 );
577 if names.len() >= MAX_LIST_ENTRIES {
578 break;
579 }
580 }
581 Ok(names)
582}
584/// Search every non-ignored file under `root` for `query`.
585///
586/// Matches are reported as `relative/path:line:text`, bounded by match count
587/// and total output, and unreadable or binary files are skipped rather than
588/// failing the whole search.
589fn grep_tree(
590 root: &Path,
591 query: &str,
592 config: &Config,
593 cancel: &CancelHandle,
594) -> std::result::Result<String, SmithError> {
595 let mut matches: Vec<String> = Vec::new();
596 let mut total_bytes = 0usize;
597 for found in walker(root, None, config) {
598 if cancel.is_cancelled() {
599 return Err(SmithError::Cancelled);
600 }
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()) {
603 continue;
604 }
605 let relative = found
606 .path()
607 .strip_prefix(root)
608 .unwrap_or_else(|_| found.path())
609 .to_string_lossy()
610 .into_owned();
611 let Ok(file) = fs::File::open(found.path()) else {
612 continue;
613 };
614 let mut reader = BufReader::with_capacity(64 * 1024, file);
615 let mut line = Vec::new();
616 let mut line_no = 0usize;
617 loop {
618 line.clear();
619 match reader.read_until(b'\n', &mut line) {
620 Ok(0) | Err(_) => break,
621 Ok(_) => {}
622 }
623 if line.contains(&0) {
624 break; // binary content
625 }
626 line_no += 1;
627 let text = String::from_utf8_lossy(&line).trim_end().to_string();
628 if !text.contains(query) {
629 continue;
630 }
631 let rendered = format!("{relative}:{line_no}:{text}");
632 if matches.len() >= MAX_GREP_MATCHES
633 || total_bytes + rendered.len() > DEFAULT_OUTPUT_CAP
634 {
635 matches.push("<truncated>".to_string());
636 return Ok(matches.join("\n"));
637 }
638 total_bytes += rendered.len();
639 matches.push(rendered);
640 }
641 }
642 Ok(matches.join("\n"))
643}
645/// Run one bounded, cancellable shell command in the invocation directory.
646fn run_bash(
647 input: &serde_json::Value,
648 working_dir: &Path,
649 timeout_ms: u64,
650 cancel: &CancelHandle,
651) -> std::result::Result<String, SmithError> {
652 let command = input
653 .get("command")
654 .and_then(|v| v.as_str())
655 .ok_or_else(|| tool_err("VALIDATION", "bash requires string 'command'"))?;
656 let requested = input
657 .get("timeout_ms")
658 .and_then(serde_json::Value::as_u64)
659 .unwrap_or(timeout_ms);
660 let result = crate::bash::execute(
661 command,
662 working_dir.to_str(),
663 requested.min(timeout_ms),
664 DEFAULT_OUTPUT_CAP,
665 cancel,
666 )?;
667 if result.cancelled {
668 return Err(SmithError::Cancelled);
669 }
670 let mut output = result.stdout;
671 if !result.stderr.is_empty() {
672 if !output.is_empty() {
673 output.push('\n');
674 }
675 output.push_str("[stderr] ");
676 output.push_str(&result.stderr);
677 }
678 if result.timed_out {
679 return Err(tool_err(
680 "BASH_TIMEOUT",
681 format!("timed out after {requested} ms: {output}"),
682 ));
683 }
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(
688 "BASH_KILLED",
689 format!("terminated without exit status: {output}"),
690 )),
691 }
692}
398694/// Read a bounded line window without materializing the whole file.
399695fn read_bounded(
400696 path: &Path,
427723 if line_no <= offset {
428724 continue;
429725 }
430 if out.lines().count() >= limit.min(usize::MAX - 1) && limit != usize::MAX {
431 // limit counts lines emitted
432 }
433726 let emit = if limit == usize::MAX {
434727 true
435728 } else {
472765 Ok(())
768/// A hidden sibling path used for atomic publication.
475769fn temp_sibling(path: &Path) -> PathBuf {
476770 static COUNTER: AtomicUsize = AtomicUsize::new(0);
477771 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
478 let name = path
479 .file_name()
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(),
775 );
482776 path.with_file_name(format!(".{name}.tmp-{}-{n}", std::process::id()))
485779/// Apply exactly one unambiguous replacement, publishing atomically.
486780fn edit_exact(path: &Path, old: &str, new: &str) -> std::result::Result<String, SmithError> {
487781 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 {
489783 return Err(tool_err(
490784 "FILE_TOO_LARGE",
491785 "edit input exceeds the file size limit",
544838 Ok(matches.join("\n"))
841/// Wall-clock milliseconds since the Unix epoch, saturating on overflow.
547842fn now_ms() -> i64 {
548843 std::time::SystemTime::now()
549844 .duration_since(std::time::UNIX_EPOCH)
550 .map(|d| d.as_millis() as i64)
551 .unwrap_or(0)
845 .map_or(0, |elapsed| {
846 i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX)
847 })
554850#[cfg(test)]
555#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
851#[expect(
852 clippy::unwrap_used,
853 clippy::panic,
854 reason = "tests may panic on invariant violations"
855)]
556856mod tests {
557857 use super::*;
558858 use std::path::PathBuf;
564864 dir
565865 }
867 #[test]
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);
878 // find walks recursively and drops ignored and hidden paths.
879 let found = ts
880 .invoke("find", &serde_json::json!({"pattern": ""}))
881 .unwrap()
882 .output;
883 assert_eq!(found, "keep.txt\nnested\nnested/deep.txt");
884 // ls stays one level deep, with the same filtering.
885 let listed = ts.invoke("ls", &serde_json::json!({})).unwrap().output;
886 assert_eq!(listed, "keep.txt\nnested");
887 // grep searches the tree and locates each match.
888 let hits = ts
889 .invoke("grep", &serde_json::json!({"path": "", "query": "needle"}))
890 .unwrap()
891 .output;
892 assert_eq!(
893 hits,
894 "keep.txt:1:needle here\nnested/deep.txt:1:needle deep"
895 );
897 // Configuration decides: without ignore rules, everything shows up.
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 = permissive
903 .invoke("find", &serde_json::json!({"pattern": ".txt"}))
904 .unwrap()
905 .output;
906 assert_eq!(found, ".hidden.txt\nignored.txt\nkeep.txt\nnested/deep.txt");
907 let hits = permissive
908 .invoke(
909 "grep",
910 &serde_json::json!({"path": "", "query": "needle here"}),
911 )
912 .unwrap()
913 .output;
914 assert_eq!(
915 hits,
916 ".hidden.txt:1:needle here\nignored.txt:1:needle here\nkeep.txt:1:needle here"
917 );
918 }
920 #[test]
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"}))
927 .unwrap();
929 // Somebody else rewrites the file after the read.
930 std::thread::sleep(std::time::Duration::from_millis(20));
931 std::fs::write(&target, "alpha edited elsewhere\n").unwrap();
933 let err = ts
934 .invoke(
935 "edit",
936 &serde_json::json!({"path": "doc.txt", "old_string": "alpha", "new_string": "beta"}),
937 )
938 .unwrap_err();
939 assert_eq!(err.code(), "STALE_INPUT");
940 assert_eq!(
941 std::fs::read_to_string(&target).unwrap(),
942 "alpha edited elsewhere\n"
943 );
945 // Re-reading refreshes the observed version and unblocks the edit.
946 ts.invoke("read", &serde_json::json!({"path": "doc.txt"}))
947 .unwrap();
948 ts.invoke(
949 "edit",
950 &serde_json::json!({"path": "doc.txt", "old_string": "alpha", "new_string": "beta"}),
951 )
952 .unwrap();
953 assert_eq!(
954 std::fs::read_to_string(&target).unwrap(),
955 "beta edited elsewhere\n"
956 );
957 }
959 #[test]
960 fn bash_effect_runs_in_the_workdir_and_is_recorded() {
961 let dir = workdir("bash_effect");
962 let mut ts = ToolSession::new(&dir);
963 let outcome = ts
964 .invoke(
965 "bash",
966 &serde_json::json!({"command": "printf hi > made.txt; printf done"}),
967 )
968 .unwrap();
969 assert!(outcome.ok);
970 assert_eq!(outcome.output, "done");
971 assert_eq!(std::fs::read_to_string(dir.join("made.txt")).unwrap(), "hi");
972 // A recorded call always precedes its result.
973 let kinds: Vec<&str> = ts
974 .session
975 .active_branch()
976 .entries
977 .iter()
978 .map(|e| match &e.content {
979 EntryContent::ToolCall { .. } => "call",
980 EntryContent::ToolResult { .. } => "result",
981 _ => "other",
982 })
983 .collect();
984 assert_eq!(kinds, vec!["call", "result"]);
985 }
987 #[test]
988 fn failing_and_timing_out_commands_report_explicitly() {
989 let dir = workdir("bash_failures");
990 let mut ts = ToolSession::new(&dir);
991 let err = ts
992 .invoke("bash", &serde_json::json!({"command": "exit 3"}))
993 .unwrap_err();
994 assert_eq!(err.code(), "BASH_EXIT");
995 let err = ts
996 .invoke(
997 "bash",
998 &serde_json::json!({"command": "sleep 5", "timeout_ms": 150}),
999 )
1000 .unwrap_err();
1001 assert_eq!(err.code(), "BASH_TIMEOUT");
1002 // Both failures stay durable evidence, recorded as failed results.
1003 let failed = ts
1004 .session
1005 .active_branch()
1006 .entries
1007 .iter()
1008 .filter(|e| matches!(&e.content, EntryContent::ToolResult { ok: false, .. }))
1009 .count();
1010 assert_eq!(failed, 2);
1011 }
1013 #[test]
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();
1018 cancel.cancel();
1019 let err = ts
1020 .invoke(
1021 "write",
1022 &serde_json::json!({"path": "never.txt", "content": "x"}),
1023 )
1024 .unwrap_err();
1025 assert_eq!(err.code(), "CANCELLED");
1026 assert!(!dir.join("never.txt").exists());
1027 // A refused call records nothing.
1028 assert!(ts.session.active_branch().entries.is_empty());
1029 }
1031 #[test]
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));
1038 cancel.cancel();
1039 });
1040 let started = std::time::Instant::now();
1041 let err = ts
1042 .invoke(
1043 "bash",
1044 &serde_json::json!({"command": "sleep 10", "timeout_ms": 10_000}),
1045 )
1046 .unwrap_err();
1047 waker.join().unwrap();
1048 assert_eq!(err.code(), "CANCELLED");
1049 assert!(started.elapsed() < std::time::Duration::from_secs(5));
1050 }
1052 #[test]
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();
1059 let mut ts =
1060 ToolSession::with_session(&dir, opened.session, opened.writer).with_config(cfg);
1061 // The call entry fits, the 5 KiB result does not: the effect already
1062 // ran, so the error has to admit the mutation.
1063 let err = ts
1064 .invoke(
1065 "bash",
1066 &serde_json::json!({"command": "printf 'x%.0s' $(seq 5000)"}),
1067 )
1068 .unwrap_err();
1069 assert_eq!(err.code(), "RECORD_FAILED");
1070 assert!(matches!(
1071 err,
1072 SmithError::RecordFailed {
1073 mutation_applied: true,
1074 ..
1075 }
1076 ));
1077 }
5671079 #[test]
5681080 fn write_requires_string_content_and_leaves_existing_file_untouched() {
5691081 let dir = workdir("write_schema");
5711083 std::fs::write(&target, "original").unwrap();
5721084 let mut ts = ToolSession::new(&dir);
5731085 let err = ts
574 .invoke("write", serde_json::json!({"path": "data.txt"}))
1086 .invoke("write", &serde_json::json!({"path": "data.txt"}))
5751087 .unwrap_err();
5761088 assert_eq!(err.code(), "VALIDATION");
5771089 assert_eq!(std::fs::read_to_string(&target).unwrap(), "original");
5781090 let err = ts
5791091 .invoke(
5801092 "write",
581 serde_json::json!({"path": "data.txt", "content": 42}),
1093 &serde_json::json!({"path": "data.txt", "content": 42}),
5831095 .unwrap_err();
5841096 assert_eq!(err.code(), "VALIDATION");
5921104 let mut ts = ToolSession::new(&dir);
5931105 ts.invoke(
5941106 "write",
595 serde_json::json!({"path": "a/b/c.txt", "content": "deep"}),
1107 &serde_json::json!({"path": "a/b/c.txt", "content": "deep"}),
5971109 .unwrap();
5981110 assert_eq!(
6011113 );
6021114 let leftovers: Vec<_> = std::fs::read_dir(&dir)
6031115 .unwrap()
604 .filter_map(|e| e.ok())
1116 .filter_map(std::result::Result::ok)
6051117 .flat_map(|e| {
6061118 std::fs::read_dir(e.path())
6071119 .unwrap()
608 .filter_map(|x| x.ok())
1120 .filter_map(std::result::Result::ok)
6091121 .map(|x| x.file_name().to_string_lossy().into_owned())
6101122 .collect::<Vec<_>>()
6111123 })
6271139 let err = ts
6281140 .invoke(
6291141 "edit",
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"}),
6321144 .unwrap_err();
6331145 assert_eq!(err.code(), "EDIT_AMBIGUOUS");
6351147 let err = ts
6361148 .invoke(
6371149 "edit",
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"}),
6401152 .unwrap_err();
6411153 assert_eq!(err.code(), "EDIT_NOT_FOUND");
6431155 // Unambiguous edit succeeds.
6441156 ts.invoke(
6451157 "edit",
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"}),
6481160 .unwrap();
6491161 assert_eq!(std::fs::read_to_string(&target).unwrap(), "b");
6551167 let dir = workdir("read_caps");
6561168 let mut body = String::new();
6571169 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}");
6601173 std::fs::write(dir.join("lines.txt"), &body).unwrap();
6611174 let mut ts = ToolSession::new(&dir);
6621175 let out = ts
6631176 .invoke(
6641177 "read",
665 serde_json::json!({"path": "lines.txt", "offset": 2, "limit": 3}),
1178 &serde_json::json!({"path": "lines.txt", "offset": 2, "limit": 3}),
6671180 .unwrap();
6681181 assert_eq!(out.output, "line-2\nline-3\nline-4\n");
6691182 let capped = ts
6701183 .invoke(
6711184 "read",
672 serde_json::json!({"path": "lines.txt", "max_bytes": 20}),
1185 &serde_json::json!({"path": "lines.txt", "max_bytes": 20}),
6741187 .unwrap();
6751188 assert!(capped.output.len() <= 20);
6761189 std::fs::write(dir.join("bin.dat"), [0x62, 0x00, 0x62]).unwrap();
6771190 let err = ts
678 .invoke("read", serde_json::json!({"path": "bin.dat"}))
1191 .invoke("read", &serde_json::json!({"path": "bin.dat"}))
6791192 .unwrap_err();
6801193 assert_eq!(err.code(), "BINARY_CONTENT");
6811194 let _ = std::fs::remove_dir_all(&dir);
6881201 std::fs::write(dir.join(name), "").unwrap();
6901203 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();
6921205 assert_eq!(out.output, "alpha\nmid\nzeta");
6931206 let found = ts
694 .invoke("find", serde_json::json!({"pattern": "a"}))
1207 .invoke("find", &serde_json::json!({"pattern": "a"}))
6951208 .unwrap();
6961209 assert_eq!(found.output, "alpha\nzeta");
6971210 let err = ts
6981211 .invoke(
6991212 "find",
700 serde_json::json!({"path": "missing-dir", "pattern": "x"}),
1213 &serde_json::json!({"path": "missing-dir", "pattern": "x"}),
7021215 .unwrap_err();
7031216 assert_eq!(err.code(), "FIND_ERROR");
7161229 let out = ts
7171230 .invoke(
7181231 "grep",
719 serde_json::json!({"path": "log.txt", "query": "hit"}),
1232 &serde_json::json!({"path": "log.txt", "query": "hit"}),
7211234 .unwrap();
7221235 assert_eq!(out.output, "hit one\nhit two\nhit three");
7271240 fn unregistered_tools_and_non_object_input_are_rejected() {
7281241 let dir = workdir("registry");
7291242 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();
7311244 assert_eq!(err.code(), "TOOL_NOT_REGISTERED");
7321245 let err = ts
733 .invoke("read", serde_json::json!("not-an-object"))
1246 .invoke("read", &serde_json::json!("not-an-object"))
7341247 .unwrap_err();
7351248 assert_eq!(err.code(), "INVALID_INPUT");
7361249 let _ = std::fs::remove_dir_all(&dir);
7401253 fn failed_effects_are_recorded_as_failures() {
7411254 let dir = workdir("record_fail");
7421255 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"}));
7441257 assert!(res.is_err());
7451258 // Two entries: call + failed result, both recorded.
7461259 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)]
2use crate::session::{Entry, Session};
3use smith::id::*;
1//! Replay evidence derived from durable session state.
2//!
3//! A trace is an ordered, provider-free reconstruction of what a session
4//! recorded. It is derived only from persisted values, so the same session
5//! file always produces the same trace, byte for byte.
6
7use crate::session::{EntryContent, Session};
8use smith::id::SessionId;
510/// Replay-relevant trace record (durable replay evidence).
611#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
712pub struct TraceRecord {
8 /// Replay timestamp.
13 /// Timestamp of the recorded event, in Unix milliseconds.
914 pub timestamp_ms: i64,
10 /// Session ID.
15 /// Session the event belongs to.
1116 pub session_id: SessionId,
1217 /// Event kind.
1318 pub kind: TraceKind,
14 /// Ordered event reference (entry ID or message ID).
19 /// Stable reference to the recorded event.
1520 pub event_ref: String,
1823/// Kind of replay event.
19#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
24#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
2025pub enum TraceKind {
2126 /// Session created.
2227 SessionCreated,
3641 ReplayCompleted,
39/// Build a replay trace from a session.
44/// Build the trace of a session's active branch.
45///
46/// Every entry contributes the record kind that matches what it recorded, so
47/// tool activity and compaction stay visible instead of collapsing into one
48/// generic kind.
49#[must_use]
4050pub 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 {
4353 timestamp_ms: 0,
4454 session_id: session.id,
4555 kind: TraceKind::SessionCreated,
46 event_ref: format!("branch:{}", session.active_branch_idx),
47 });
48 for entry in &session.active_branch().entries {
56 event_ref: format!("branch:{}", branch.branch_id),
57 }];
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),
63 ),
64 EntryContent::ToolCall { call_id, name, .. } => {
65 (TraceKind::ToolCallEmitted, format!("call:{name}:{call_id}"))
66 }
67 EntryContent::ToolResult { call_id, ok, .. } => (
68 TraceKind::ToolResultReceived,
69 format!("result:{call_id}:{}", if *ok { "ok" } else { "failed" }),
70 ),
71 EntryContent::Meta { kind, .. } if entry.is_compaction() => {
72 (TraceKind::Compaction, format!("meta:{kind}:{}", entry.id))
73 }
74 EntryContent::Meta { kind, .. } => {
75 (TraceKind::EntryAdded, format!("meta:{kind}:{}", entry.id))
76 }
77 };
4978 trace.push(TraceRecord {
5079 timestamp_ms: entry.timestamp_ms,
5180 session_id: session.id,
52 kind: TraceKind::EntryAdded,
53 event_ref: format!("entry:{}", entry.id),
81 kind,
82 event_ref,
5483 });
5584 }
5685 trace
59/// Replay a session from frames deterministically.
60/// Reconstructs session state without a provider.
88/// Replay a session without a provider.
89///
90/// The trace is framed by explicit start and completion records and uses only
91/// persisted timestamps, so replaying the same session twice is identical.
92#[must_use]
6193pub fn replay(session: &Session) -> Vec<TraceRecord> {
62 build_trace(session)
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 {
98 timestamp_ms: 0,
99 session_id: session.id,
100 kind: TraceKind::ReplayStarted,
101 event_ref: format!("session:{}", session.id),
102 });
103 trace.extend(body);
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()),
109 });
110 trace
65113#[cfg(test)]
66#[allow(clippy::unwrap_used, clippy::expect_used)]
114#[expect(
115 clippy::unwrap_used,
116 reason = "tests may panic on invariant violations"
117)]
67118mod tests {
68119 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;
69124 use smith::message::{Message, Role};
126 fn kinds(trace: &[TraceRecord]) -> Vec<TraceKind> {
127 trace.iter().map(|record| record.kind).collect()
128 }
71130 #[test]
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(
75134 Message::with_text(Role::User, "hello"),
76135 None,
77136 ));
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;
139 tools
140 .invoke("ls", &serde_json::json!({"path": "."}))
141 .unwrap();
142 tools.session.append_compaction(serde_json::json!({}));
144 assert_eq!(
145 kinds(&replay(&tools.session)),
146 vec![
147 TraceKind::ReplayStarted,
148 TraceKind::SessionCreated,
149 TraceKind::MessageStreamed,
150 TraceKind::ToolCallEmitted,
151 TraceKind::ToolResultReceived,
152 TraceKind::Compaction,
153 TraceKind::ReplayCompleted,
154 ]
155 );
156 }
158 #[test]
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();
165 {
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());
169 tools
170 .invoke(
171 "write",
172 &serde_json::json!({"path": "note.txt", "content": "hi"}),
173 )
174 .unwrap();
175 tools
176 .invoke("read", &serde_json::json!({"path": "note.txt"}))
177 .unwrap();
178 }
179 let encode = |session: &Session| {
180 let mut bytes = Vec::new();
181 ciborium::ser::into_writer(&replay(session), &mut bytes).unwrap();
182 bytes
183 };
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);
189 assert_eq!(
190 kinds(&replay(&Session::from_frames(&first))),
191 vec![
192 TraceKind::ReplayStarted,
193 TraceKind::SessionCreated,
194 TraceKind::ToolCallEmitted,
195 TraceKind::ToolResultReceived,
196 TraceKind::ToolCallEmitted,
197 TraceKind::ToolResultReceived,
198 TraceKind::ReplayCompleted,
199 ]
200 );
201 let _ = std::fs::remove_dir_all(&dir);
81202 }

smith/Cargo.toml

Modified

+1 / −1 text lines

1212serde = { workspace = true }
1313ciborium = { workspace = true }
1414serde_json = { workspace = true }
15thiserror = { workspace = true }
15dirs = { workspace = true }
1717[features]
1818default = []No final newline

smith/src/config.rs

Added
new file mode 100644

+96 / −0 text lines

1use crate::error::{Result, SmithError};
2use serde::{Deserialize, Serialize};
3
4/// Validated runtime configuration.
5///
6/// Values are plain data; validation reports the field that is wrong so a
7/// rejected value can be traced back to the setting that produced it.
8#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
9pub struct Config {
10 /// Directory holding session files.
11 pub session_dir: String,
12 /// Maximum frame payload size in bytes.
13 pub max_frame_bytes: usize,
14 /// Deadline applied to one tool effect, in milliseconds.
15 pub tool_timeout_ms: u64,
16 /// Whether repair keeps frames written by newer builds.
17 pub preserve_unknown_frames: bool,
18 /// Whether listing and searching obey `.gitignore` and `.ignore` files.
19 pub respect_ignore_files: bool,
20 /// Whether listing and searching include dot-prefixed entries.
21 pub include_hidden: bool,
22}
24/// Smallest accepted frame payload limit, in bytes.
25const MIN_FRAME_BYTES: usize = 1024;
27/// Largest accepted frame payload limit, in bytes.
28const MAX_FRAME_BYTES: usize = 100 * 1024 * 1024;
30/// Smallest accepted tool deadline, in milliseconds.
31const MIN_TOOL_TIMEOUT_MS: u64 = 100;
33impl Config {
34 /// Default validated configuration. Session data resolves under the
35 /// platform data directory (XDG data home on Linux).
36 #[must_use]
37 pub fn default_valid() -> Self {
38 let session_dir = dirs::data_dir()
39 .map_or_else(
40 || std::path::PathBuf::from(".smith"),
41 |base| base.join("smith"),
42 )
43 .join("sessions");
44 Self {
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,
51 }
52 }
54 /// Validate every field, naming the field that fails.
55 ///
56 /// # Errors
57 ///
58 /// Returns [`SmithError::Config`] with the offending field path.
59 pub fn validate(&self) -> Result<()> {
60 if self.session_dir.trim().is_empty() {
61 return Err(invalid("session_dir", "must not be empty"));
62 }
63 if self.max_frame_bytes < MIN_FRAME_BYTES {
64 return Err(invalid(
65 "max_frame_bytes",
66 &format!("must be at least {MIN_FRAME_BYTES}"),
67 ));
68 }
69 if self.max_frame_bytes > MAX_FRAME_BYTES {
70 return Err(invalid(
71 "max_frame_bytes",
72 &format!("must not exceed {MAX_FRAME_BYTES}"),
73 ));
74 }
75 if self.tool_timeout_ms < MIN_TOOL_TIMEOUT_MS {
76 return Err(invalid(
77 "tool_timeout_ms",
78 &format!("must be at least {MIN_TOOL_TIMEOUT_MS}"),
79 ));
80 }
81 Ok(())
82 }
83}
85fn invalid(field: &str, message: &str) -> SmithError {
86 SmithError::Config {
87 field: field.to_string(),
88 message: message.to_string(),
89 }
90}
92impl Default for Config {
93 fn default() -> Self {
94 Self::default_valid()
95 }
96}

smith/src/error.rs

Modified

+140 / −21 text lines

1//! Recoverable, serializable Smith errors.
2
13use std::fmt;
5/// A framing fault, classified so corruption, schema damage, and frames
6/// written by a future build stay distinguishable.
7#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
8pub enum FrameFault {
9 /// Declared payload exceeds the configured limit.
10 TooLarge {
11 /// Configured payload limit in bytes.
12 max_bytes: usize,
13 /// Declared payload size in bytes.
14 actual: usize,
15 },
16 /// Encoding failed during serialization or output.
17 Encode {
18 /// Underlying encoder message.
19 message: String,
20 },
21 /// Declared length is too small to hold a frame body prefix.
22 Malformed {
23 /// Declared body length in bytes.
24 declared_length: usize,
25 },
26 /// Checksum mismatch: the frame body is corrupt.
27 Checksum {
28 /// Declared body length in bytes.
29 declared_length: usize,
30 },
31 /// A known frame kind carrying an unsupported version.
32 UnsupportedVersion {
33 /// Frame kind tag.
34 kind: u16,
35 /// Frame version tag.
36 version: u16,
37 },
38 /// Checksum-valid payload that does not decode as its kind's schema.
39 SchemaDecode {
40 /// Underlying decoder message.
41 message: String,
42 },
43}
45impl FrameFault {
46 /// Short fault code.
47 #[must_use]
48 pub const fn code(&self) -> &'static str {
49 match self {
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",
56 }
57 }
58}
60impl fmt::Display for FrameFault {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 Self::TooLarge { max_bytes, actual } => {
64 write!(f, "too large: {actual} > {max_bytes} bytes")
65 }
66 Self::Encode { message } => write!(f, "encode: {message}"),
67 Self::Malformed { declared_length } => {
68 write!(
69 f,
70 "malformed: declared length {declared_length} is too short"
71 )
72 }
73 Self::Checksum { declared_length } => {
74 write!(f, "checksum mismatch in {declared_length} declared bytes")
75 }
76 Self::UnsupportedVersion { kind, version } => {
77 write!(f, "unsupported version {version} for kind {kind}")
78 }
79 Self::SchemaDecode { message } => write!(f, "schema decode: {message}"),
80 }
81 }
82}
384/// Recoverable Smith errors.
485#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
586pub enum SmithError {
687 /// Session error.
7 Session { code: String, message: String },
88 Session {
89 /// Stable session fault code.
90 code: String,
91 /// Human-readable detail.
92 message: String,
93 },
894 /// Provider error.
9 Provider { code: String, message: String },
95 Provider {
96 /// Stable provider fault code.
97 code: String,
98 /// Human-readable detail.
99 message: String,
100 },
10101 /// Tool error.
11 Tool { code: String, message: String },
12 /// Frame decode error.
13 FrameDecode { message: String },
14 /// Frame encode error (size or serialization).
15 FrameEncode { message: String },
16 /// Frame too large for safe decode.
17 FrameTooLarge { max_bytes: usize, actual: usize },
102 Tool {
103 /// Stable tool fault code.
104 code: String,
105 /// Human-readable detail.
106 message: String,
107 },
108 /// A tool effect finished but its durable recording failed.
109 /// `mutation_applied` says whether the effect already changed the host.
110 RecordFailed {
111 /// Tool whose outcome could not be recorded.
112 tool: String,
113 /// Whether the effect already mutated host state.
114 mutation_applied: bool,
115 /// Underlying recording failure.
116 message: String,
117 },
118 /// Framing fault, located in the session file when the offset is known.
119 Frame {
120 /// Classified framing fault.
121 fault: FrameFault,
122 /// Byte offset of the frame header, when reading a file.
123 offset: Option<u64>,
124 },
18125 /// Cancellation.
19126 Cancelled,
20127 /// Configuration error.
21 Config { field: String, message: String },
128 Config {
129 /// Dotted path of the offending field.
130 field: String,
131 /// Why the value was rejected.
132 message: String,
133 },
24136impl fmt::Display for SmithError {
27139 Self::Session { code, message } => write!(f, "session [{code}]: {message}"),
28140 Self::Provider { code, message } => write!(f, "provider [{code}]: {message}"),
29141 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")
34 }
142 Self::RecordFailed {
143 tool,
144 mutation_applied,
145 message,
146 } => write!(
147 f,
148 "tool [RECORD_FAILED]: {tool} recording failed (mutation applied: {mutation_applied}): {message}"
149 ),
150 Self::Frame { fault, offset } => match offset {
151 Some(at) => write!(f, "frame at offset {at}: {fault}"),
152 None => write!(f, "frame: {fault}"),
153 },
35154 Self::Cancelled => write!(f, "operation cancelled"),
36155 Self::Config { field, message } => {
37156 write!(f, "config [{field}]: {message}")
48167impl SmithError {
49168 /// Short error code.
169 #[must_use]
50170 pub fn code(&self) -> &str {
51171 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, .. } => {
173 code
174 }
175 Self::RecordFailed { .. } => "RECORD_FAILED",
176 Self::Frame { fault, .. } => fault.code(),
58177 Self::Cancelled => "CANCELLED",
59178 Self::Config { .. } => "CONFIG",
60179 }

smith/src/id.rs

Modified

+58 / −235 text lines

1//! Stable identifiers.
2//!
3//! Every identifier is a `UUIDv7` newtype: distinct types cannot be confused
4//! for each other, and the time-ordered layout keeps generated IDs sortable.
5
16use std::fmt;
7
8use serde::{Deserialize, Serialize};
29use uuid::Uuid;
4/// Session identifier (UUIDv7)
5#[derive(
6 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
7)]
8pub struct SessionId(Uuid);
11/// Define one `UUIDv7` newtype identifier.
12macro_rules! smith_id {
13 ($name:ident, $what:literal) => {
14 #[doc = concat!("Identifier of ", $what, ".")]
15 #[derive(
16 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, Serialize, Deserialize,
17 )]
18 pub struct $name(Uuid);
10impl SessionId {
11 pub fn new() -> Self {
12 Self(Uuid::now_v7())
13 }
20 impl $name {
21 /// A fresh, time-ordered identifier.
22 #[must_use]
23 pub fn new() -> Self {
24 Self(Uuid::now_v7())
25 }
15 pub fn as_uuid(&self) -> Uuid {
16 self.0
17 }
27 /// The underlying UUID.
28 #[must_use]
29 pub const fn as_uuid(&self) -> Uuid {
30 self.0
31 }
32 }
34 impl fmt::Display for $name {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "{}", self.0)
37 }
38 }
40 impl From<Uuid> for $name {
41 fn from(value: Uuid) -> Self {
42 Self(value)
43 }
44 }
46 impl From<$name> for Uuid {
47 fn from(id: $name) -> Self {
48 id.0
49 }
50 }
52 impl Default for $name {
53 fn default() -> Self {
54 Self::new()
55 }
56 }
57 };
20impl fmt::Display for SessionId {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 self.0.fmt(f)
23 }
24}
26impl From<Uuid> for SessionId {
27 fn from(u: Uuid) -> Self {
28 Self(u)
29 }
30}
32impl From<SessionId> for Uuid {
33 fn from(id: SessionId) -> Uuid {
34 id.0
35 }
36}
38impl Default for SessionId {
39 fn default() -> Self {
40 Self::new()
41 }
42}
44/// Branch identifier (UUIDv7)
45#[derive(
46 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
47)]
48pub struct BranchId(Uuid);
50impl BranchId {
51 pub fn new() -> Self {
52 Self(Uuid::now_v7())
53 }
55 pub fn as_uuid(&self) -> Uuid {
56 self.0
57 }
58}
60impl fmt::Display for BranchId {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 self.0.fmt(f)
63 }
64}
66impl From<Uuid> for BranchId {
67 fn from(u: Uuid) -> Self {
68 Self(u)
69 }
70}
72impl From<BranchId> for Uuid {
73 fn from(id: BranchId) -> Uuid {
74 id.0
75 }
76}
78impl Default for BranchId {
79 fn default() -> Self {
80 Self::new()
81 }
82}
84/// Entry identifier (UUIDv7)
85#[derive(
86 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
87)]
88pub struct EntryId(Uuid);
90impl EntryId {
91 pub fn new() -> Self {
92 Self(Uuid::now_v7())
93 }
95 pub fn as_uuid(&self) -> Uuid {
96 self.0
97 }
98}
100impl fmt::Display for EntryId {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 self.0.fmt(f)
103 }
104}
106impl From<Uuid> for EntryId {
107 fn from(u: Uuid) -> Self {
108 Self(u)
109 }
110}
112impl From<EntryId> for Uuid {
113 fn from(id: EntryId) -> Uuid {
114 id.0
115 }
116}
118impl Default for EntryId {
119 fn default() -> Self {
120 Self::new()
121 }
122}
124/// Tool call identifier (UUIDv7)
125#[derive(
126 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
127)]
128pub struct ToolCallId(Uuid);
130impl ToolCallId {
131 pub fn new() -> Self {
132 Self(Uuid::now_v7())
133 }
135 pub fn as_uuid(&self) -> Uuid {
136 self.0
137 }
138}
140impl fmt::Display for ToolCallId {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 self.0.fmt(f)
143 }
144}
146impl From<Uuid> for ToolCallId {
147 fn from(u: Uuid) -> Self {
148 Self(u)
149 }
150}
152impl From<ToolCallId> for Uuid {
153 fn from(id: ToolCallId) -> Uuid {
154 id.0
155 }
156}
158impl Default for ToolCallId {
159 fn default() -> Self {
160 Self::new()
161 }
162}
164/// Tool result identifier (UUIDv7)
165#[derive(
166 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
167)]
168pub struct ToolResultId(Uuid);
170impl ToolResultId {
171 pub fn new() -> Self {
172 Self(Uuid::now_v7())
173 }
175 pub fn as_uuid(&self) -> Uuid {
176 self.0
177 }
178}
180impl fmt::Display for ToolResultId {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 self.0.fmt(f)
183 }
184}
186impl From<Uuid> for ToolResultId {
187 fn from(u: Uuid) -> Self {
188 Self(u)
189 }
190}
192impl From<ToolResultId> for Uuid {
193 fn from(id: ToolResultId) -> Uuid {
194 id.0
195 }
196}
198impl Default for ToolResultId {
199 fn default() -> Self {
200 Self::new()
201 }
202}
204/// Message identifier (UUIDv7)
205#[derive(
206 Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, serde::Serialize, serde::Deserialize,
207)]
208pub struct MessageId(Uuid);
210impl MessageId {
211 pub fn new() -> Self {
212 Self(Uuid::now_v7())
213 }
215 pub fn as_uuid(&self) -> Uuid {
216 self.0
217 }
218}
220impl fmt::Display for MessageId {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 self.0.fmt(f)
223 }
224}
226impl From<Uuid> for MessageId {
227 fn from(u: Uuid) -> Self {
228 Self(u)
229 }
230}
232impl From<MessageId> for Uuid {
233 fn from(id: MessageId) -> Uuid {
234 id.0
235 }
236}
238impl Default for MessageId {
239 fn default() -> Self {
240 Self::new()
241 }
242}
60smith_id!(SessionId, "one session");
61smith_id!(BranchId, "one branch of a session");
62smith_id!(EntryId, "one session entry");
63smith_id!(ToolCallId, "one tool call");
64smith_id!(ToolResultId, "one tool result");
65smith_id!(MessageId, "one message");

smith/src/lib.rs

Modified

+36 / −28 text lines

33//! Provider-neutral values, errors, cancellation, and tool contracts.
55#![forbid(unsafe_code)]
6#![warn(missing_docs)]
7#![allow(
8 clippy::pedantic,
9 clippy::style,
10 clippy::use_self,
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,
19 clippy::expect_used
20)]
22#[doc(hidden)]
7/// Validated runtime configuration.
8pub mod config;
9/// Recoverable error taxonomy.
2310pub mod error;
24#[doc(hidden)]
11/// Stable identifiers.
2512pub mod id;
26#[doc(hidden)]
13/// Messages and content blocks.
2714pub mod message;
28#[doc(hidden)]
15/// Normalized provider stream events.
2916pub mod stream;
30#[doc(hidden)]
17/// Tool contracts and cancellation.
3118pub mod tool;
33pub use error::{Result, SmithError};
20pub use config::Config;
21pub use error::{FrameFault, Result, SmithError};
3422pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};
3523pub use message::{ContentBlock, Message, Role};
3624pub use stream::{StopReason, StreamEvent, Usage};
37pub use tool::{CancelHandle, CancellationToken, ToolCall, ToolMetadata, ToolResult};
25pub use tool::{CancelHandle, ToolCall, ToolMetadata, ToolResult};
3927#[cfg(test)]
40#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic_in_result_fn)]
28#[expect(
29 clippy::unwrap_used,
30 reason = "tests may panic on invariant violations"
31)]
4132mod tests {
4233 use super::*;
9788 }
9990 #[test]
100 fn cancellation_is_cooperative() {
101 let mut token = CancellationToken::new();
102 assert!(!token.is_cancelled());
103 token.cancel();
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");
96 assert_eq!(
97 err,
98 SmithError::Config {
99 field: "max_frame_bytes".to_string(),
100 message: "must be at least 1024".to_string(),
101 }
102 );
103 config.max_frame_bytes = 1024;
104 assert!(config.validate().is_ok());
105 config.session_dir = " ".to_string();
106 assert_eq!(
107 config.validate().unwrap_err(),
108 SmithError::Config {
109 field: "session_dir".to_string(),
110 message: "must not be empty".to_string(),
111 }
112 );
105113 }
107115 #[test]

smith/src/message.rs

Modified

+24 / −9 text lines

1use crate::id::*;
1//! Provider-neutral messages and content blocks.
2
3use crate::id::{MessageId, ToolCallId};
24use serde::{Deserialize, Serialize};
35use std::fmt;
1820impl fmt::Display for Role {
1921 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022 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"),
2527 }
2628 }
5961impl ContentBlock {
62 /// A plain text block.
63 #[must_use]
6064 pub fn text<S: Into<String>>(s: S) -> Self {
6165 Self::Text(s.into())
6266 }
68 /// A thinking block, kept distinct from text on the wire.
69 #[must_use]
6470 pub fn thinking<S: Into<String>>(s: S) -> Self {
6571 Self::Thinking(s.into())
6672 }
74 /// A tool use request block.
75 #[must_use]
6876 pub fn tool_use<N: Into<String>>(
6977 name: N,
7078 input: serde_json::Value,
7785 }
7886 }
88 /// A tool result block paired to `call_id`.
89 #[must_use]
8090 pub fn tool_result(call_id: ToolCallId, ok: bool, output: impl Into<String>) -> Self {
8191 Self::ToolResult {
8292 call_id,
102112impl Message {
113 /// An empty message with a fresh identity.
114 #[must_use]
103115 pub fn new(role: Role) -> Self {
104116 Self {
105117 id: MessageId::new(),
109121 }
110122 }
124 /// A message holding one text block.
125 #[must_use]
112126 pub fn with_text<S: Into<String>>(role: Role, text: S) -> Self {
113127 Self {
114128 id: MessageId::new(),
118132 }
119133 }
135 /// Append one content block, preserving order.
121136 pub fn add_block(&mut self, block: ContentBlock) {
122137 self.blocks.push(block);
123138 }
136151 ContentBlock::Text(t) => write!(f, "text: {t}")?,
137152 ContentBlock::Thinking(t) => write!(f, "thinking: {t}")?,
138153 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} }}")?;
140155 }
141156 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} }}")?;
143158 }
144159 }
145160 }
148163 }
166/// Wall-clock milliseconds since the Unix epoch, saturating on overflow.
151167fn now_ms() -> i64 {
152168 use std::time::{SystemTime, UNIX_EPOCH};
153169 SystemTime::now()
154170 .duration_since(UNIX_EPOCH)
155 .map(|d| d.as_millis() as i64)
156 .unwrap_or(0)
171 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))

smith/src/stream.rs

Modified

+19 / −3 text lines

1use crate::id::*;
1//! Normalized provider stream events, stop reasons, and usage.
2
3use crate::id::{MessageId, ToolCallId};
24use serde::{Deserialize, Serialize};
46/// Normalized provider stream event.
8587impl Usage {
86 pub fn new() -> Self {
88 /// Usage with every counter at zero.
89 #[must_use]
90 pub const fn new() -> Self {
8791 Self {
8892 input_tokens: 0,
8993 output_tokens: 0,
102106impl StreamEvent {
107 /// A text delta for `message_id`.
108 #[must_use]
103109 pub fn text_delta(message_id: MessageId, delta: impl Into<String>) -> Self {
104110 Self::TextDelta {
105111 message_id,
107113 }
108114 }
116 /// A thinking delta for `message_id`.
117 #[must_use]
110118 pub fn thinking_delta(message_id: MessageId, delta: impl Into<String>) -> Self {
111119 Self::ThinkingDelta {
112120 message_id,
114122 }
115123 }
125 /// A tool use request emitted while streaming `message_id`.
126 #[must_use]
117127 pub fn tool_use(
118128 message_id: MessageId,
119129 name: impl Into<String>,
128138 }
129139 }
141 /// A tool result emitted while streaming `message_id`.
142 #[must_use]
131143 pub fn tool_result(
132144 message_id: MessageId,
133145 call_id: ToolCallId,
142154 }
143155 }
145 pub fn stop(reason: StopReason, usage: Option<Usage>) -> Self {
157 /// A terminal stop event.
158 #[must_use]
159 pub const fn stop(reason: StopReason, usage: Option<Usage>) -> Self {
146160 Self::Stop { reason, usage }
147161 }
163 /// A terminal error event.
164 #[must_use]
149165 pub fn error(error: impl Into<String>) -> Self {
150166 Self::Error {
151167 error: error.into(),

smith/src/tool.rs

Modified

+9 / −23 text lines

1use crate::id::*;
1//! Provider-neutral tool contracts and cancellation.
2
3use crate::id::ToolCallId;
24use serde::{Deserialize, Serialize};
46/// Tool specification (provider-neutral definition).
1517impl ToolMetadata {
18 /// Metadata with an empty object schema.
19 #[must_use]
1620 pub fn new<N: Into<String>, D: Into<String>>(name: N, description: D) -> Self {
1721 Self {
1822 name: name.into(),
2529 }
2630 }
32 /// Replace the input schema.
33 #[must_use]
2834 pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
2935 self.input_schema = schema;
3036 self
5359 pub output: String,
56/// Cancellation token for bounded cancellation.
57/// A simple flag that can be polled or triggered externally.
58#[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]
59pub struct CancellationToken {
60 /// Whether cancellation has been requested.
61 pub cancelled: bool,
62}
64impl CancellationToken {
65 pub fn new() -> Self {
66 Self { cancelled: false }
67 }
69 pub fn cancel(&mut self) {
70 self.cancelled = true;
71 }
73 pub fn is_cancelled(&self) -> bool {
74 self.cancelled
75 }
76}
7862/// Shared, thread-safe cancellation handle for active effects.
7963/// Clone into a running effect; `cancel` from the owner thread.
8064#[derive(Clone, Debug, Default)]
8569impl CancelHandle {
8670 /// A handle that starts uncancelled.
71 #[must_use]
8772 pub fn new() -> Self {
8873 Self::default()
8974 }
9479 }
9681 /// Whether cancellation was requested.
82 #[must_use]
9783 pub fn is_cancelled(&self) -> bool {
9884 self.flag.load(std::sync::atomic::Ordering::Acquire)
9985 }