repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

refactor(core): deslop pass over session arena

4eda77442a630e4ccdf981818ab33d9a977ff51d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (8)

+177 / −125 text lines

Diff layout

smith-core/src/agent.rs

Modified

+42 / −19 text lines

643643 /// reader of entry content.
644644 fn build_request(&self) -> Result<ProviderRequest> {
645645 let session = &self.tools.session;
646 let since = session.compaction_boundary;
646 let since = session.compaction_boundary();
647647 let mut messages = Vec::new();
648648 let mut include = since.is_none();
649 for entry in &session.active_branch().entries {
649 for entry in session.active_branch().entries() {
650650 if since == Some(entry.id) {
651651 include = true;
652652 continue;
654654 if !include || !matches!(entry.kind, EntryKind::Message { .. }) {
655655 continue;
656656 }
657 let EntryContent::Message(mut message) = session.content(entry)? else {
658 return Err(SmithError::Session {
659 code: "ENTRY_KIND_MISMATCH".to_string(),
660 message: format!("message entry {} holds other content", entry.id),
661 });
662 };
663 // Provider-bound context never receives registered plaintext.
664 self.secrets.mask_message(&mut message);
665 messages.push(message);
657 // `content` verifies the record kind, so a message record
658 // decodes to a message or fails with `ENTRY_KIND_MISMATCH`.
659 if let EntryContent::Message(mut message) = session.content(entry)? {
660 // Provider-bound context never receives registered plaintext.
661 self.secrets.mask_message(&mut message);
662 messages.push(message);
663 }
666664 }
667665 let mut request = ProviderRequest::new(self.model.clone(), messages);
668666 request.tools = self.tools.registered_tools();
756754 fn decoded(session: &Session) -> String {
757755 let contents: Vec<EntryContent> = session
758756 .active_branch()
759 .entries
757 .entries()
760758 .iter()
761759 .map(|entry| session.content(entry).unwrap())
762760 .collect();
815813 let kinds: Vec<&str> = agent
816814 .session()
817815 .active_branch()
818 .entries
816 .entries()
819817 .iter()
820818 .map(|entry| match entry.kind {
821819 EntryKind::Message { role, .. } => match role {
904902 let durable_ids: Vec<ToolCallId> = agent
905903 .session()
906904 .active_branch()
907 .entries
905 .entries()
908906 .iter()
909907 .filter_map(|entry| match entry.kind {
910908 EntryKind::ToolCall { call_id } | EntryKind::ToolResult { call_id, .. } => {
944942 let kinds: Vec<&str> = agent
945943 .session()
946944 .active_branch()
947 .entries
945 .entries()
948946 .iter()
949947 .map(|entry| match entry.kind {
950948 EntryKind::ToolCall { .. } => "call",
970968 let err = agent.run_turn("hello").unwrap_err();
971969 assert_eq!(err.code(), "CANCELLED");
972970 // Only the user message was recorded; no assistant claims exist.
973 assert_eq!(agent.session().active_branch().entries.len(), 1);
971 assert_eq!(agent.session().active_branch().entries().len(), 1);
972 }
974 #[test]
975 fn request_build_rejects_a_message_record_holding_other_content() {
976 let mut forged = crate::session::EntryFrame::new(
977 None,
978 &EntryContent::ToolResult {
979 ok: true,
980 output: "not a message".to_string(),
981 call_id: ToolCallId::new(),
982 },
983 )
984 .unwrap();
985 forged.kind = EntryKind::Message {
986 id: smith::id::MessageId::new(),
987 role: Role::User,
988 };
989 let (stream, seen) = recording(vec![final_response()]);
990 let mut tools = temp_tools("kind_mismatch");
991 tools.session =
992 Session::from_frames(&[crate::frame::Frame::Known { entry: forged }]).unwrap();
993 let mut agent = Agent::new(stream, tools, "mock-smith");
994 let err = agent.run_turn("hello").unwrap_err();
995 assert_eq!(err.code(), "ENTRY_KIND_MISMATCH");
996 assert!(seen.lock().unwrap().is_empty());
974997 }
976999 #[test]
11931216 let (stream, _seen) = recording(vec![final_response()]);
11941217 let mut agent = Agent::new(stream, tools, "mock-smith");
11951218 agent.run_turn("persisted").unwrap();
1196 let session_id = agent.session().id;
1219 let session_id = agent.session().id();
11971220 drop(agent);
11981221 let reopened = open_session(&path, Config::default_valid()).unwrap();
1199 assert_eq!(reopened.session.id, session_id);
1200 assert_eq!(reopened.session.active_branch().entries.len(), 2);
1222 assert_eq!(reopened.session.id(), session_id);
1223 assert_eq!(reopened.session.active_branch().entries().len(), 2);
12011224 let _ = std::fs::remove_dir_all(&dir);

smith-core/src/frame.rs

Modified

+0 / −8 text lines

463463 }
466/// Deterministic JSON: recursively sort object keys so equivalent values
467/// encode to identical CBOR regardless of insertion order.
468pub use crate::session::canonical_json;
470466#[cfg(test)]
471467#[expect(
472468 clippy::unwrap_used,
753749 fn equivalent_inputs_encode_identically_despite_key_order() {
754750 let a = serde_json::json!({"path": "p", "content": {"b": 1, "a": 2}});
755751 let b = serde_json::json!({"content": {"a": 2, "b": 1}, "path": "p"});
756 assert_eq!(
757 canonical_json(&a).to_string(),
758 canonical_json(&b).to_string()
759 );
760752 let call_id = ToolCallId::new();
761753 let e1 = EntryFrame::new(
762754 None,

smith-core/src/lib.rs

Modified

+1 / −1 text lines

4646 let mut session = Session::new();
4747 let msg = Message::with_text(Role::User, "hello");
4848 let entry = *session.append(None, &EntryContent::Message(msg)).unwrap();
49 assert_eq!(session.active_branch().entries, vec![entry]);
49 assert_eq!(session.active_branch().entries(), vec![entry]);
5050 assert_eq!(session.selected_id(), Some(entry.id));
5151 }

smith-core/src/session.rs

Modified

+98 / −58 text lines

2222/// Deterministic JSON: recursively sort object keys so equivalent values
2323/// encode to identical CBOR regardless of insertion order.
24#[must_use]
25pub fn canonical_json(value: &serde_json::Value) -> serde_json::Value {
24fn canonical_json(value: &serde_json::Value) -> serde_json::Value {
2625 match value {
2726 serde_json::Value::Object(map) => {
2827 let mut keys: Vec<&String> = map.keys().collect();
6463/// Byte range of one entry's content in its session's payload arena.
6564///
6665/// `u32` offsets cap one session arena at 4 GiB.
67#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
66#[derive(Clone, Copy, PartialEq, Eq, Debug)]
6867pub struct Span {
6968 /// First content byte.
7069 pub offset: u32,
374373 })
377/// Selected branch in a session.
376/// One root-to-leaf chain of a session.
377///
378/// Only its [`Session`] mutates a branch, so every record's span points into
379/// that session's arena.
378380#[derive(Clone, PartialEq, Eq, Debug)]
379381pub struct Branch {
380 /// Branch ID.
381 pub branch_id: BranchId,
382 /// Entry records ordered root to leaf.
383 pub entries: Vec<Entry>,
384 /// Index of selected leaf.
385 pub selected_idx: usize,
386}
388impl Default for Branch {
389 fn default() -> Self {
390 Self::new()
391 }
382 id: BranchId,
383 entries: Vec<Entry>,
384 selected_idx: usize,
394387impl Branch {
395 /// An empty branch with a fresh identity.
396 #[must_use]
397 pub fn new() -> Self {
398 Self::with_id(BranchId::new())
399 }
401 const fn with_id(branch_id: BranchId) -> Self {
388 const fn with_id(id: BranchId) -> Self {
402389 Self {
403 branch_id,
390 id,
404391 entries: Vec::new(),
405392 selected_idx: 0,
406393 }
407394 }
409 /// Append `entry` and select it. Returns its index.
410 pub fn append(&mut self, entry: Entry) -> usize {
396 /// Branch identity.
397 #[must_use]
398 pub const fn id(&self) -> BranchId {
399 self.id
400 }
402 /// Entry records ordered root to leaf.
403 #[must_use]
404 pub fn entries(&self) -> &[Entry] {
405 &self.entries
406 }
408 /// Append `entry` and select it.
409 fn append(&mut self, entry: Entry) -> &Entry {
410 self.selected_idx = self.entries.len();
411411 self.entries.push(entry);
412 self.selected_idx = self.entries.len().saturating_sub(1);
413 self.selected_idx
412 &self.entries[self.selected_idx]
414413 }
416415 /// The currently selected entry, if the branch has any.
423422/// A session is a persistent, branching message/tool history.
423///
424/// Fields stay private so the invariants hold: at least one branch, a valid
425/// active index, every span inside the arena, and a compaction boundary
426/// that names a recorded compaction entry.
424427#[derive(Clone, PartialEq, Eq, Debug)]
425428pub struct Session {
426 /// Session identifier.
427 pub id: SessionId,
429 id: SessionId,
428430 /// All branches (default branch is index 0).
429 pub branches: Vec<Branch>,
431 branches: Vec<Branch>,
430432 /// Canonical CBOR content of every entry, addressed by [`Span`].
431433 payloads: Vec<u8>,
432 /// Index of active branch.
433 pub active_branch_idx: usize,
434 /// Compaction boundary entry (if any).
435 pub compaction_boundary: Option<EntryId>,
434 active_branch_idx: usize,
435 compaction_boundary: Option<EntryId>,
438438impl Default for Session {
447447 pub fn new() -> Self {
448448 Self {
449449 id: SessionId::new(),
450 branches: vec![Branch::new()],
450 branches: vec![Branch::with_id(BranchId::new())],
451451 payloads: Vec::new(),
452452 active_branch_idx: 0,
453453 compaction_boundary: None,
454454 }
455455 }
457 /// Session identifier.
458 #[must_use]
459 pub const fn id(&self) -> SessionId {
460 self.id
461 }
463 /// All branches; the active one is [`Session::active_branch`].
464 #[must_use]
465 pub fn branches(&self) -> &[Branch] {
466 &self.branches
467 }
469 /// The latest compaction boundary entry, if any.
470 #[must_use]
471 pub const fn compaction_boundary(&self) -> Option<EntryId> {
472 self.compaction_boundary
473 }
457475 /// The selected branch.
458476 #[must_use]
459477 pub fn active_branch(&self) -> &Branch {
460478 &self.branches[self.active_branch_idx]
461479 }
463 /// The selected branch, mutably.
464 pub fn active_branch_mut(&mut self) -> &mut Branch {
465 &mut self.branches[self.active_branch_idx]
466 }
468481 /// Identifier of the selected entry, if any.
469482 #[must_use]
470483 pub fn selected_id(&self) -> Option<EntryId> {
518531 if entry.is_compaction() {
519532 self.compaction_boundary = Some(entry.id);
520533 }
521 let branch = self.active_branch_mut();
522 let idx = branch.append(entry);
523 Ok(&branch.entries[idx])
534 Ok(self.branches[self.active_branch_idx].append(entry))
524535 }
526537 /// Append a compaction boundary entry after the selected entry and
544555 self.payloads.get(entry.content.range()).unwrap_or_default()
545556 }
547 /// Decode the content of `entry` into the caller's scope.
558 /// Decode the content of `entry` into the caller's scope, verifying it
559 /// against the record's [`EntryKind`], which traversal trusts unchecked.
548560 ///
549561 /// # Errors
550562 ///
551 /// Returns [`SmithError::Session`] when the bytes do not decode.
563 /// Returns [`SmithError::Session`] with code `ENTRY_DECODE` when the
564 /// bytes do not decode, or `ENTRY_KIND_MISMATCH` when they decode to
565 /// content of another kind than the record claims.
552566 pub fn content(&self, entry: &Entry) -> Result<EntryContent> {
553 EntryContent::decode(self.bytes(entry))
567 let content = EntryContent::decode(self.bytes(entry))?;
568 let found = content.kind();
569 if found != entry.kind {
570 return Err(SmithError::Session {
571 code: "ENTRY_KIND_MISMATCH".to_string(),
572 message: format!(
573 "entry {} records {:?} but holds {found:?}",
574 entry.id, entry.kind
575 ),
576 });
577 }
578 Ok(content)
554579 }
556581 /// The root-to-`at` entry chain, or `None` when `at` is unknown or its
600625 Ok(Self {
601626 id: SessionId::new(),
602627 branches: vec![Branch {
603 branch_id: BranchId::new(),
628 id: BranchId::new(),
604629 entries: entries.to_vec(),
605630 selected_idx: entries.len().saturating_sub(1),
606631 }],
615640 pub fn header(&self) -> SessionHeader {
616641 SessionHeader {
617642 session_id: self.id,
618 branch_id: self.active_branch().branch_id,
643 branch_id: self.active_branch().id,
619644 }
620645 }
728753 // The selected branch owns the persisted identity; sibling
729754 // branches derive theirs from their leaf, which keeps every
730755 // reload of the same file identical.
731 branch_id: if is_active {
756 id: if is_active {
732757 active_id
733758 } else {
734759 BranchId::from_u128(leaf.id.as_u128())
799824 // The last stored entry selects the active branch and keeps the
800825 // persisted branch identity.
801826 assert_eq!(session.selected_id(), Some(second.id));
802 assert_eq!(
803 session.active_branch().branch_id,
804 scratch.header().branch_id
805 );
827 assert_eq!(session.active_branch().id, scratch.header().branch_id);
806828 assert_eq!(ids(session.active_branch()), vec![root.id, second.id]);
807829 let sibling = &session.branches[1 - session.active_branch_idx];
808830 assert_eq!(ids(sibling), vec![root.id, first.id]);
977999 );
1002 #[test]
1003 fn content_of_a_record_whose_kind_lies_is_a_kind_mismatch() {
1004 let mut scratch = Session::new();
1005 scratch.append(None, &message("root")).unwrap();
1006 let mut stored = frames(&scratch);
1007 let lie = EntryKind::ToolCall {
1008 call_id: ToolCallId::new(),
1009 };
1010 if let Frame::Known { entry } = &mut stored[1] {
1011 entry.kind = lie;
1012 }
1013 // Loading trusts the record; only a decode can tell.
1014 let restored = Session::from_frames(&stored).unwrap();
1015 let record = restored.active_branch().entries[0];
1016 assert_eq!(record.kind, lie);
1017 assert_eq!(
1018 restored.content(&record).unwrap_err().code(),
1019 "ENTRY_KIND_MISMATCH"
1020 );
1021 }
9801023 #[test]
9811024 fn compaction_boundary_survives_a_frame_round_trip() {
9821025 let mut session = Session::new();
9851028 let restored = Session::from_frames(&frames(&session)).unwrap();
9861029 assert_eq!(restored.compaction_boundary, Some(boundary.id));
9871030 assert_eq!(restored.id, session.id);
988 assert_eq!(
989 restored.active_branch().branch_id,
990 session.header().branch_id
991 );
1031 assert_eq!(restored.active_branch().id, session.header().branch_id);
9921032 assert_eq!(restored, session);

smith-core/src/store.rs

Modified

+18 / −21 text lines

238238 },
239239 config.max_frame_bytes,
240240 )?;
241 for entry in &session.active_branch().entries {
241 for entry in session.active_branch().entries() {
242242 let bytes = encode_entry(entry, session.bytes(entry), config.max_frame_bytes)?;
243243 out.write_all(&bytes).map_err(io_err("CREATE_WRITE"))?;
244244 }
401401 assert_eq!(
402402 session
403403 .active_branch()
404 .entries
404 .entries()
405405 .iter()
406406 .map(|e| e.id)
407407 .collect::<Vec<_>>(),
645645 let opened_id;
646646 {
647647 let opened = open_session(&session_path, cfg.clone()).unwrap();
648 opened_id = opened.session.id;
648 opened_id = opened.session.id();
649649 let mut ts = crate::tools::ToolSession::with_session(
650650 workdir.clone(),
651651 opened.session,
664664 .frames;
665665 assert_eq!(frames.len(), 5); // header + call/result x2
666666 let restored = Session::from_frames(&frames).unwrap();
667 assert_eq!(restored.id, opened_id);
668 assert_eq!(restored.active_branch().entries.len(), 4);
667 assert_eq!(restored.id(), opened_id);
668 assert_eq!(restored.active_branch().entries().len(), 4);
669669 // Tool call/result pairs stay adjacent and ordered.
670670 let kinds: Vec<&str> = restored
671671 .active_branch()
672 .entries
672 .entries()
673673 .iter()
674674 .map(|e| match e.kind {
675675 EntryKind::ToolCall { .. } => "call",
706706 let opened = open_session(&path, cfg).unwrap();
707707 opened.session
708708 };
709 assert_eq!(first.id, created.id);
710 assert_eq!(
711 first.active_branch().branch_id,
712 created.active_branch().branch_id
713 );
714 assert_eq!(second.id, first.id);
709 assert_eq!(first.id(), created.id());
710 assert_eq!(first.active_branch().id(), created.active_branch().id());
711 assert_eq!(second.id(), first.id());
716713 // Replay evidence is byte-stable across independent loads.
717714 let encode = |session: &Session| {
761758 let fork_id = {
762759 let forked =
763760 fork_session(&source_session, boundary_id, &fork_path, cfg.clone()).unwrap();
764 assert_ne!(forked.session.id, source_session.id);
761 assert_ne!(forked.session.id(), source_session.id());
765762 assert_eq!(forked.session.selected_id(), Some(boundary_id));
766 assert_eq!(forked.session.compaction_boundary, Some(boundary_id));
763 assert_eq!(forked.session.compaction_boundary(), Some(boundary_id));
767764 assert!(forked.recovery.damage.is_empty());
768 forked.session.id
765 forked.session.id()
769766 };
771768 // The fork is durable: reopening restores the same identity and leaf.
772769 {
773770 let reopened = open_session(&fork_path, cfg.clone()).unwrap();
774 assert_eq!(reopened.session.id, fork_id);
771 assert_eq!(reopened.session.id(), fork_id);
775772 assert_eq!(reopened.session.selected_id(), Some(boundary_id));
776 assert_eq!(reopened.session.active_branch().entries.len(), 2);
777 assert_eq!(reopened.session.compaction_boundary, Some(boundary_id));
773 assert_eq!(reopened.session.active_branch().entries().len(), 2);
774 assert_eq!(reopened.session.compaction_boundary(), Some(boundary_id));
778775 // Published content bytes decode to what the source recorded.
779776 let content = |session: &Session| {
780777 session
781 .content(&session.active_branch().entries[0])
778 .content(&session.active_branch().entries()[0])
782779 .unwrap()
783780 };
784781 assert_eq!(content(&reopened.session), content(&source_session));
787784 // The source keeps its own identity, tip, and entry count.
788785 {
789786 let source_again = open_session(&source_path, cfg.clone()).unwrap();
790 assert_eq!(source_again.session.id, source_session.id);
787 assert_eq!(source_again.session.id(), source_session.id());
791788 assert_eq!(source_again.session.selected_id(), Some(leaf_id));
792 assert_eq!(source_again.session.active_branch().entries.len(), 3);
789 assert_eq!(source_again.session.active_branch().entries().len(), 3);
793790 }
795792 // A populated target is refused instead of overwritten.

smith-core/src/tools.rs

Modified

+6 / −6 text lines

10371037 let kinds: Vec<&str> = ts
10381038 .session
10391039 .active_branch()
1040 .entries
1040 .entries()
10411041 .iter()
10421042 .map(|e| match e.kind {
10431043 EntryKind::ToolCall { .. } => "call",
10671067 let failed = ts
10681068 .session
10691069 .active_branch()
1070 .entries
1070 .entries()
10711071 .iter()
10721072 .filter(|e| matches!(e.kind, EntryKind::ToolResult { ok: false, .. }))
10731073 .count();
10891089 assert_eq!(err.code(), "CANCELLED");
10901090 assert!(!dir.join("never.txt").exists());
10911091 // A refused call records nothing.
1092 assert!(ts.session.active_branch().entries.is_empty());
1092 assert!(ts.session.active_branch().entries().is_empty());
10951095 #[test]
11421142 let kinds: Vec<EntryKind> = ts
11431143 .session
11441144 .active_branch()
1145 .entries
1145 .entries()
11461146 .iter()
11471147 .map(|e| e.kind)
11481148 .collect();
13291329 let res = ts.invoke("read", &serde_json::json!({"path": "nope.txt"}));
13301330 assert!(res.is_err());
13311331 // Two entries: call + failed result, both recorded.
1332 assert_eq!(ts.session.active_branch().entries.len(), 2);
1333 let last = &ts.session.active_branch().entries[1];
1332 assert_eq!(ts.session.active_branch().entries().len(), 2);
1333 let last = &ts.session.active_branch().entries()[1];
13341334 match ts.session.content(last).unwrap() {
13351335 EntryContent::ToolResult { ok, output, .. } => {
13361336 assert!(!ok);

smith-core/src/trace.rs

Modified

+8 / −8 text lines

5252 let branch = session.active_branch();
5353 let mut trace = vec![TraceRecord {
5454 timestamp_ms: 0,
55 session_id: session.id,
55 session_id: session.id(),
5656 kind: TraceKind::SessionCreated,
57 event_ref: format!("branch:{}", branch.branch_id),
57 event_ref: format!("branch:{}", branch.id()),
5858 }];
59 for entry in &branch.entries {
59 for entry in branch.entries() {
6060 let (kind, event_ref) = match entry.kind {
6161 EntryKind::Message { id, .. } => (TraceKind::MessageStreamed, format!("message:{id}")),
6262 EntryKind::ToolCall { call_id } => {
7676 };
7777 trace.push(TraceRecord {
7878 timestamp_ms: entry.timestamp_ms,
79 session_id: session.id,
79 session_id: session.id(),
8080 kind,
8181 event_ref,
8282 });
9595 let mut trace = Vec::with_capacity(body.len() + 2);
9696 trace.push(TraceRecord {
9797 timestamp_ms: 0,
98 session_id: session.id,
98 session_id: session.id(),
9999 kind: TraceKind::ReplayStarted,
100 event_ref: format!("session:{}", session.id),
100 event_ref: format!("session:{}", session.id()),
101101 });
102102 trace.extend(body);
103103 trace.push(TraceRecord {
104104 timestamp_ms: last_ms,
105 session_id: session.id,
105 session_id: session.id(),
106106 kind: TraceKind::ReplayCompleted,
107 event_ref: format!("entries:{}", session.active_branch().entries.len()),
107 event_ref: format!("entries:{}", session.active_branch().entries().len()),
108108 });
109109 trace

smith-core/tests/alloc_bounds.rs

Modified

+4 / −4 text lines

5555 let leaf = session.selected_id().expect("non-empty session");
5656 let (cost, fork) = session_cost(|| session.fork_at(leaf).expect("leaf is known"));
5757 assert_eq!(
58 fork.active_branch().entries.len(),
59 session.active_branch().entries.len()
58 fork.active_branch().entries().len(),
59 session.active_branch().entries().len()
6060 );
61 let last = fork.active_branch().entries[fork.active_branch().entries.len() - 1];
61 let last = fork.active_branch().entries()[fork.active_branch().entries().len() - 1];
6262 assert_eq!(fork.bytes(&last), session.bytes(&last));
6363 cost
7272 frames.extend(
7373 session
7474 .active_branch()
75 .entries
75 .entries()
7676 .iter()
7777 .map(|entry| Frame::Known {
7878 entry: EntryFrame {