mentra 0.17.0

An agent runtime for tool-using LLM applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
use std::{
    collections::BTreeMap,
    sync::atomic::{AtomicU64, Ordering},
    time::{SystemTime, UNIX_EPOCH},
};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use crate::{ContentBlock, Message, Role};

static NEXT_ENTRY_SUFFIX: AtomicU64 = AtomicU64::new(0);

/// Identifier for one transcript entry.
///
/// Entries form a tree through [`TranscriptItem::parent_id`]; this is how a
/// conversation can return to an earlier point and continue along a different
/// path without copying history.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct EntryId(String);

impl EntryId {
    pub fn new() -> Self {
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let suffix = NEXT_ENTRY_SUFFIX.fetch_add(1, Ordering::Relaxed);
        Self(format!("entry-{stamp:x}-{suffix:x}"))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Default for EntryId {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for EntryId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// Why a branch operation could not be performed.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum BranchError {
    #[error("no entry '{0}' anywhere in the transcript")]
    UnknownEntry(EntryId),
    /// An archived entry whose parent chain does not reach a root.
    ///
    /// Impossible in a well-formed tree: every entry either is a root or names
    /// a parent that exists. Reported rather than papered over, because
    /// installing a partial path would silently hand the model a conversation
    /// missing its beginning.
    #[error("entry '{entry}' has a broken parent chain: '{missing}' is not in the transcript")]
    BrokenChain { entry: EntryId, missing: EntryId },
}

/// An agent's conversation, as a tree of entries with one active path.
///
/// [`items`](Self::items) is that active path, root to leaf — the messages
/// the model actually sees, and the only view most code needs. Entries left
/// behind by [`branch_from`](Self::branch_from) move to
/// [`archived`](Self::archived) rather than being deleted, so a branch is a
/// move of the leaf pointer rather than a copy of history — and moving it back
/// is how an abandoned branch is returned to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(from = "AgentTranscriptWire")]
pub struct AgentTranscript {
    items: Vec<TranscriptItem>,
    /// Entries off the active path. Reachable through
    /// [`children`](Self::children), and returnable-to through
    /// [`branch_from`](Self::branch_from), which accepts an archived entry and
    /// rebuilds its path from the `parent_id` links.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    archive: Vec<TranscriptItem>,
}

/// Deserialization shape, so transcripts written before entries had ids load
/// unchanged and get their parent links filled in on the way through.
#[derive(Deserialize)]
struct AgentTranscriptWire {
    #[serde(default)]
    items: Vec<TranscriptItem>,
    #[serde(default)]
    archive: Vec<TranscriptItem>,
}

impl From<AgentTranscriptWire> for AgentTranscript {
    fn from(wire: AgentTranscriptWire) -> Self {
        let mut transcript = Self {
            items: wire.items,
            archive: wire.archive,
        };
        transcript.link_active_path();
        transcript
    }
}

impl AgentTranscript {
    pub fn new(items: Vec<TranscriptItem>) -> Self {
        let mut transcript = Self {
            items,
            archive: Vec::new(),
        };
        transcript.link_active_path();
        transcript
    }

    pub fn from_messages(messages: Vec<Message>) -> Self {
        Self::new(
            messages
                .into_iter()
                .map(transcript_item_from_message)
                .collect(),
        )
    }

    /// Fills in parent links the active path implies.
    ///
    /// The active path is a root-to-leaf chain by construction, so an entry's
    /// parent is the entry before it. Only missing links are written, which
    /// leaves a tree loaded from disk alone and repairs a transcript written
    /// before entries had ids.
    fn link_active_path(&mut self) {
        for index in 1..self.items.len() {
            if self.items[index].parent_id.is_none() {
                self.items[index].parent_id = Some(self.items[index - 1].id.clone());
            }
        }
    }

    /// The entry the next append will hang from.
    pub fn leaf(&self) -> Option<&EntryId> {
        self.items.last().map(|item| &item.id)
    }

    /// Entries that are not on the active path.
    pub fn archived(&self) -> &[TranscriptItem] {
        &self.archive
    }

    /// Looks up an entry anywhere in the tree.
    pub fn entry(&self, id: &EntryId) -> Option<&TranscriptItem> {
        self.items
            .iter()
            .chain(self.archive.iter())
            .find(|item| &item.id == id)
    }

    /// The entries recorded as continuing from `id`, in creation order.
    ///
    /// More than one means the conversation branched there: each is the start
    /// of a different path explored from the same point.
    pub fn children(&self, id: &EntryId) -> Vec<&TranscriptItem> {
        self.items
            .iter()
            .chain(self.archive.iter())
            .filter(|item| item.parent_id.as_ref() == Some(id))
            .collect()
    }

    /// Moves the leaf to `id`, so subsequent appends continue from there.
    ///
    /// `id` may be anywhere in the tree: on the active path, which shortens it,
    /// or on a branch abandoned earlier, which returns to it. Either way no
    /// entry is deleted — whatever leaves the active path moves to
    /// [`archived`](Self::archived) and stays reachable through
    /// [`children`](Self::children). Returns how many entries left the path.
    ///
    /// Returning to an abandoned branch is what makes this a tree rather than
    /// an undo stack: "try something else" and "actually, go back" are the same
    /// operation in opposite directions.
    pub fn branch_from(&mut self, id: &EntryId) -> Result<usize, BranchError> {
        if let Some(position) = self.items.iter().position(|item| &item.id == id) {
            let abandoned = self.items.split_off(position + 1);
            let count = abandoned.len();
            self.archive.extend(abandoned);
            return Ok(count);
        }

        if !self.archive.iter().any(|item| &item.id == id) {
            return Err(BranchError::UnknownEntry(id.clone()));
        }

        // The target is on an abandoned branch. Its path is reconstructible
        // because every entry names its parent, so walk to the root and make
        // that chain the active path.
        let path = self.path_to(id)?;
        let restored: Vec<TranscriptItem> = path
            .iter()
            .map(|id| {
                self.take_anywhere(id)
                    .expect("path_to only names entries that exist")
            })
            .collect();

        let count = self.items.len();
        let previous = std::mem::replace(&mut self.items, restored);
        self.archive.extend(previous);

        Ok(count)
    }

    /// The ids from the root down to `id`, inclusive.
    fn path_to(&self, id: &EntryId) -> Result<Vec<EntryId>, BranchError> {
        let mut path = Vec::new();
        let mut cursor = Some(id.clone());

        while let Some(current) = cursor {
            let Some(item) = self.entry(&current) else {
                return Err(BranchError::BrokenChain {
                    entry: id.clone(),
                    missing: current,
                });
            };
            cursor = item.parent_id.clone();
            path.push(current);

            // A parent link that cycles would loop forever. It cannot happen
            // through `push`, which only ever points at an existing leaf, but
            // a transcript loaded from disk is data rather than a promise.
            if path.len() > self.items.len() + self.archive.len() {
                return Err(BranchError::BrokenChain {
                    entry: id.clone(),
                    missing: id.clone(),
                });
            }
        }

        path.reverse();
        Ok(path)
    }

    /// Removes an entry from whichever vector holds it.
    fn take_anywhere(&mut self, id: &EntryId) -> Option<TranscriptItem> {
        if let Some(index) = self.items.iter().position(|item| &item.id == id) {
            return Some(self.items.remove(index));
        }
        let index = self.archive.iter().position(|item| &item.id == id)?;
        Some(self.archive.remove(index))
    }

    pub fn items(&self) -> &[TranscriptItem] {
        &self.items
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Appends an entry as a child of the current leaf.
    pub fn push(&mut self, mut item: TranscriptItem) {
        item.parent_id = self.leaf().cloned();
        self.items.push(item);
    }

    pub fn to_messages(&self) -> Vec<Message> {
        self.items
            .iter()
            .filter_map(TranscriptItem::project_message)
            .collect()
    }

    pub fn projected_messages_from(&self, start: usize) -> Vec<Message> {
        self.items
            .iter()
            .skip(start)
            .filter_map(TranscriptItem::project_message)
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TranscriptItem {
    /// Identity of this entry within the transcript tree.
    #[serde(default)]
    pub id: EntryId,
    /// The entry this one continues from. `None` marks a root.
    ///
    /// Set by [`AgentTranscript::push`] rather than by the constructors: an
    /// entry's parent is a property of where it is appended, not of what it
    /// contains.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<EntryId>,
    pub kind: TranscriptKind,
    pub message: Option<Message>,
    /// Opaque per-call host metadata attached via [`TranscriptItem::with_details`]
    /// (populated from [`crate::tool::ToolOutput::details`]), keyed by
    /// `tool_use_id` because one tool-result message can carry several
    /// results. mentra never interprets these values; they survive
    /// transcript persistence and replay but are never projected into a
    /// provider request — [`TranscriptItem::project_message`] only ever
    /// returns `message`. `serde(default)` keeps transcripts persisted
    /// before this field existed deserializing unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    details: Option<BTreeMap<String, Value>>,
}

impl TranscriptItem {
    pub fn user_turn(message: Message) -> Self {
        Self {
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::UserTurn,
            message: Some(message),
            details: None,
        }
    }

    pub fn assistant_turn(message: Message) -> Self {
        Self {
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::AssistantTurn,
            message: Some(message),
            details: None,
        }
    }

    pub fn tool_exchange(message: Message, tool_use_id: Option<String>, is_error: bool) -> Self {
        Self {
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::ToolExchange {
                tool_use_id,
                is_error,
            },
            message: Some(message),
            details: None,
        }
    }

    pub fn canonical_context(message: Message) -> Self {
        Self {
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::CanonicalContext,
            message: Some(message),
            details: None,
        }
    }

    pub fn delegation_request(
        message: Message,
        delegation: DelegationArtifact,
        edge: Option<DelegationEdge>,
    ) -> Self {
        Self {
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::DelegationRequest { delegation, edge },
            message: Some(message),
            details: None,
        }
    }

    pub fn delegation_result(
        message: Message,
        delegation: DelegationArtifact,
        edge: Option<DelegationEdge>,
    ) -> Self {
        Self {
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::DelegationResult { delegation, edge },
            message: Some(message),
            details: None,
        }
    }

    pub fn compaction_summary(summary: CompactionSummary) -> Self {
        Self {
            message: Some(Message::user(ContentBlock::text(
                summary.render_for_handoff(),
            ))),
            id: EntryId::new(),
            parent_id: None,
            kind: TranscriptKind::CompactionSummary { summary },
            details: None,
        }
    }

    /// Attaches opaque per-call host metadata to this item, keyed by
    /// `tool_use_id`. A no-op for an empty map, so attaching a possibly-empty
    /// collected map never turns a details-free item into one carrying
    /// `Some(empty map)`.
    pub fn with_details(mut self, details: BTreeMap<String, Value>) -> Self {
        if !details.is_empty() {
            self.details = Some(details);
        }
        self
    }

    /// This item's opaque per-call host metadata, if any. mentra never
    /// interprets these values — a host recovers its own metadata after a
    /// round through this accessor alone, without mentra knowing any host
    /// type.
    pub fn details(&self) -> Option<&BTreeMap<String, Value>> {
        self.details.as_ref()
    }

    /// Looks up this item's opaque metadata for one `tool_use_id`.
    pub fn detail(&self, tool_use_id: &str) -> Option<&Value> {
        self.details.as_ref()?.get(tool_use_id)
    }

    pub fn project_message(&self) -> Option<Message> {
        self.message.clone()
    }

    pub fn is_real_user_turn(&self) -> bool {
        matches!(self.kind, TranscriptKind::UserTurn)
    }

    pub fn is_delegation_result(&self) -> bool {
        matches!(self.kind, TranscriptKind::DelegationResult { .. })
    }

    pub fn text(&self) -> String {
        self.message.as_ref().map(Message::text).unwrap_or_default()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum TranscriptKind {
    UserTurn,
    AssistantTurn,
    ToolExchange {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        tool_use_id: Option<String>,
        is_error: bool,
    },
    CanonicalContext,
    MemoryRecall,
    DelegationRequest {
        delegation: DelegationArtifact,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        edge: Option<DelegationEdge>,
    },
    DelegationResult {
        delegation: DelegationArtifact,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        edge: Option<DelegationEdge>,
    },
    CompactionSummary {
        summary: CompactionSummary,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DelegationKind {
    Subagent,
    Teammate,
    Parent,
    Child,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DelegationStatus {
    Requested,
    Finished,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DelegationEdge {
    pub kind: DelegationKind,
    pub local_agent_id: String,
    pub remote_agent_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DelegationArtifact {
    pub kind: DelegationKind,
    pub agent_id: String,
    pub agent_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    pub status: DelegationStatus,
    pub task_summary: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_summary: Option<String>,
    #[serde(default)]
    pub artifacts: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CompactionSummary {
    pub goal: String,
    pub progress: String,
    #[serde(default)]
    pub decisions: Vec<String>,
    #[serde(default)]
    pub constraints: Vec<String>,
    #[serde(default)]
    pub delegated_work: Vec<String>,
    #[serde(default)]
    pub artifacts: Vec<String>,
    #[serde(default)]
    pub open_questions: Vec<String>,
    #[serde(default)]
    pub next_steps: Vec<String>,
    /// Files the agent has read or modified, accumulated across every
    /// compaction in this transcript's history.
    ///
    /// Carried structurally rather than left to the model's prose: a summary
    /// is itself summarized by the next compaction, so a file list that lived
    /// only in `progress` decayed out of context after two or three rounds,
    /// silently. The agent would simply stop knowing it edited something an
    /// hour ago.
    #[serde(default)]
    pub files_touched: Vec<String>,
}

impl CompactionSummary {
    pub fn render_for_handoff(&self) -> String {
        let mut lines = vec![
            "[Compaction summary]".to_string(),
            format!("Goal: {}", fallback_text(&self.goal)),
            format!("Progress: {}", fallback_text(&self.progress)),
        ];
        append_list(&mut lines, "Decisions", &self.decisions);
        append_list(&mut lines, "Constraints", &self.constraints);
        append_list(&mut lines, "Delegated work", &self.delegated_work);
        append_list(&mut lines, "Artifacts", &self.artifacts);
        append_list(&mut lines, "Open questions", &self.open_questions);
        append_list(&mut lines, "Next steps", &self.next_steps);
        append_list(&mut lines, "Files touched", &self.files_touched);
        lines.join("\n")
    }

    pub fn from_fallback_text(text: String) -> Self {
        Self {
            progress: text,
            next_steps: vec![
                "Review the preserved transcript tail and continue from there.".to_string(),
            ],
            ..Self::default()
        }
    }
}

pub(crate) fn transcript_item_from_message(message: Message) -> TranscriptItem {
    match message.role {
        Role::Assistant => TranscriptItem::assistant_turn(message),
        Role::User => {
            if let Some((tool_use_id, is_error)) =
                message.content.first().and_then(|block| match block {
                    ContentBlock::ToolResult {
                        tool_use_id,
                        is_error,
                        ..
                    } => Some((tool_use_id.clone(), *is_error)),
                    _ => None,
                })
            {
                TranscriptItem::tool_exchange(message, Some(tool_use_id), is_error)
            } else {
                TranscriptItem::user_turn(message)
            }
        }
        Role::Unknown(_) => TranscriptItem::user_turn(message),
    }
}

fn append_list(lines: &mut Vec<String>, label: &str, items: &[String]) {
    if items.is_empty() {
        return;
    }
    lines.push(format!("{label}:"));
    for item in items {
        lines.push(format!("- {item}"));
    }
}

fn fallback_text(text: &str) -> &str {
    if text.trim().is_empty() {
        "(none)"
    } else {
        text
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    // Old-format compatibility (M3 test 6): a transcript persisted before
    // `details` existed is exactly the JSON a details-free item serializes
    // to today (the field is `skip_serializing_if` on `None`), so proving
    // that JSON deserializes back to `details: None` proves genuinely old
    // persisted transcripts still load.
    #[test]
    fn item_without_details_serializes_and_deserializes_as_old_format() {
        let item = TranscriptItem::user_turn(Message::user(ContentBlock::text("hello")));
        let json = serde_json::to_string(&item).expect("serialize");
        assert!(
            !json.contains("details"),
            "a details-free item must serialize identically to pre-M3 transcripts, got: {json}"
        );

        let reloaded: TranscriptItem = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(reloaded.details(), None);
        assert_eq!(reloaded, item);
    }

    #[test]
    fn details_round_trip_through_json_keyed_by_tool_use_id() {
        let mut details = BTreeMap::new();
        details.insert("call-1".to_string(), json!({ "secret": "shh" }));
        let item = TranscriptItem::tool_exchange(
            Message::user(ContentBlock::text("result")),
            Some("call-1".to_string()),
            false,
        )
        .with_details(details.clone());

        let json = serde_json::to_string(&item).expect("serialize");
        let reloaded: TranscriptItem = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(reloaded.details(), Some(&details));
        assert_eq!(reloaded.detail("call-1"), Some(&json!({ "secret": "shh" })));
        assert_eq!(reloaded.detail("call-2"), None);
    }

    #[test]
    fn with_details_is_a_no_op_for_an_empty_map() {
        let item = TranscriptItem::user_turn(Message::user(ContentBlock::text("hello")))
            .with_details(BTreeMap::new());
        assert_eq!(item.details(), None);
    }

    // M3 test 2 (projection-boundary half): `to_messages()`/`project_message`
    // are the single place internal transcript state turns into what a
    // provider request carries (`Message`/`ContentBlock`) — proving details
    // never appears in that projection, independent of any live agent
    // plumbing, is what makes "provider requests receive only content" true
    // by construction rather than by convention. The live round-trip through
    // a real model request is covered by
    // `agent::tests::tool_output::structured_tool_projects_content_and_hides_details_from_provider`.
    #[test]
    fn to_messages_projection_never_carries_details() {
        let mut details = BTreeMap::new();
        details.insert("call-1".to_string(), json!({ "secret": "shh" }));
        let transcript = AgentTranscript::new(vec![
            TranscriptItem::user_turn(Message::user(ContentBlock::text("go"))),
            TranscriptItem::assistant_turn(Message::assistant(ContentBlock::ToolUse {
                id: "call-1".to_string(),
                name: "structured_details_tool".to_string(),
                input: json!({}),
            })),
            TranscriptItem::tool_exchange(
                Message::user(ContentBlock::ToolResult {
                    tool_use_id: "call-1".to_string(),
                    content: crate::tool::ToolResultContent::Structured(json!({ "answer": 42 })),
                    is_error: false,
                }),
                Some("call-1".to_string()),
                false,
            )
            .with_details(details),
        ]);

        let projected = serde_json::to_string(&transcript.to_messages()).expect("serialize");
        assert!(projected.contains("answer"), "content must still project");
        assert!(!projected.contains("secret"));
        assert!(!projected.contains("shh"));
    }

    /// Builds a transcript of `n` user turns whose text is its index, so a
    /// path can be described by the numbers it contains.
    fn numbered(count: usize) -> AgentTranscript {
        let mut transcript = AgentTranscript::default();
        for index in 0..count {
            transcript.push(TranscriptItem::user_turn(Message::user(
                ContentBlock::text(index.to_string()),
            )));
        }
        transcript
    }

    /// The active path, as the numbers its entries carry.
    fn path(transcript: &AgentTranscript) -> Vec<String> {
        transcript
            .items()
            .iter()
            .filter_map(|item| item.message.as_ref())
            .map(|message| message.text())
            .collect()
    }

    #[test]
    fn branching_back_shortens_the_active_path() {
        let mut transcript = numbered(4);
        let second = transcript.items()[1].id.clone();

        let moved = transcript.branch_from(&second).expect("branches");

        assert_eq!(moved, 2, "two entries left the path");
        assert_eq!(path(&transcript), vec!["0", "1"]);
        assert_eq!(transcript.archived().len(), 2);
    }

    #[test]
    fn an_abandoned_branch_can_be_returned_to() {
        let mut transcript = numbered(3);
        let original_leaf = transcript.leaf().expect("a leaf").clone();
        let first = transcript.items()[0].id.clone();

        // Leave the original line of work, then explore a different one.
        transcript.branch_from(&first).expect("branches away");
        transcript.push(TranscriptItem::user_turn(Message::user(
            ContentBlock::text("elsewhere"),
        )));
        assert_eq!(path(&transcript), vec!["0", "elsewhere"]);

        // Going back is the half that never worked: the entry is archived, so
        // the old code could not find it at all.
        let moved = transcript
            .branch_from(&original_leaf)
            .expect("returns to the abandoned branch");

        // One, not two: entry "0" is on both paths, so only "elsewhere"
        // actually left. The count is entries that stopped being active, which
        // is what a caller wants to report, not the length of the old path.
        assert_eq!(moved, 1, "only the entry unique to the old path left it");
        assert_eq!(
            path(&transcript),
            vec!["0", "1", "2"],
            "the original path comes back whole and in order"
        );
    }

    #[test]
    fn alternating_between_two_branches_converges() {
        let mut transcript = numbered(2);
        let fork = transcript.items()[0].id.clone();
        let left = transcript.leaf().expect("a leaf").clone();

        transcript.branch_from(&fork).expect("branches away");
        transcript.push(TranscriptItem::user_turn(Message::user(
            ContentBlock::text("right"),
        )));
        let right = transcript.leaf().expect("a leaf").clone();

        // Three round trips: a scheme that copied entries rather than moving
        // them would grow the transcript on every switch.
        let total = transcript.items().len() + transcript.archived().len();
        for _ in 0..3 {
            transcript.branch_from(&left).expect("goes left");
            assert_eq!(path(&transcript), vec!["0", "1"]);
            transcript.branch_from(&right).expect("goes right");
            assert_eq!(path(&transcript), vec!["0", "right"]);
        }

        assert_eq!(
            transcript.items().len() + transcript.archived().len(),
            total,
            "switching branches moves entries, never copies them"
        );
    }

    #[test]
    fn an_unknown_entry_is_still_refused() {
        let mut transcript = numbered(2);
        let stranger = EntryId::new();

        assert_eq!(
            transcript.branch_from(&stranger),
            Err(BranchError::UnknownEntry(stranger))
        );
    }

    #[test]
    fn a_returned_to_branch_survives_a_round_trip_through_json() {
        let mut transcript = numbered(3);
        let leaf = transcript.leaf().expect("a leaf").clone();
        let first = transcript.items()[0].id.clone();

        transcript.branch_from(&first).expect("branches away");
        transcript.push(TranscriptItem::user_turn(Message::user(
            ContentBlock::text("elsewhere"),
        )));

        let text = serde_json::to_string(&transcript).expect("serializes");
        let mut reloaded: AgentTranscript = serde_json::from_str(&text).expect("deserializes");

        // The archive has to survive persistence, or a branch is returnable-to
        // only until the process restarts.
        reloaded
            .branch_from(&leaf)
            .expect("a reloaded transcript can still return to its branch");
        assert_eq!(path(&reloaded), vec!["0", "1", "2"]);
    }

    #[test]
    fn a_child_of_an_abandoned_entry_is_still_reachable() {
        let mut transcript = numbered(3);
        let first = transcript.items()[0].id.clone();
        let second = transcript.items()[1].id.clone();

        transcript.branch_from(&first).expect("branches away");

        // `children` is what a UI offers as "you have another line of work
        // here", so what it names must be what `branch_from` accepts.
        let children = transcript.children(&first);
        assert!(children.iter().any(|item| item.id == second));
        assert!(transcript.branch_from(&second).is_ok());
    }
}