infinity-agent-core 0.2.0

Core time-sliced agent runtime for Infinity: event processing, threads, and tool dispatch.
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
//! Simple in-memory implementations of the platform traits.
//!
//! These are fully functional [`ConversationStore`] / [`StateStore`]
//! implementations backed by `HashMap`s, suitable for tests, examples, and
//! embedded runtimes that do not need their own persistence. Production
//! embeddings usually bring their own stores (the Lambda binding uses Aurora
//! DSQL + DynamoDB; the Infinity Code daemon adds file persistence, titles,
//! and per-thread model tracking on top of an in-memory core).

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use rap_protocol::{ChoiceId, ThreadId, ToolCallId};
use serde::{Deserialize, Serialize};

use crate::message::InfinityMessage;
use crate::system::UserChoice;
use crate::traits::{ConversationStore, SpawnContext, StateStore};

/// Error type for the in-memory stores. The operations themselves are
/// infallible; this exists to satisfy the trait signatures.
#[derive(Debug)]
pub struct InMemoryStoreError(pub String);

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

impl std::error::Error for InMemoryStoreError {}

/// One thread's bookkeeping in an [`InMemoryConversationStore`].
///
/// Public and serializable so embeddings that layer persistence on top (like
/// the Infinity Code daemon) can snapshot and restore threads through
/// [`InMemoryConversationStore::thread_info`] /
/// [`set_thread_info`](InMemoryConversationStore::set_thread_info) without
/// re-implementing the store semantics.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ThreadInfo {
    pub parent_thread_id: Option<ThreadId>,
    pub root_thread_id: ThreadId,
    /// Number of parent messages the child inherits (history cutoff).
    pub spawn_message_order: Option<i64>,
    pub spawn_tool_call_id: Option<ToolCallId>,
    pub closed: bool,
    pub is_subscription_event: bool,
    #[serde(default)]
    pub is_compaction: bool,
    /// Spawned with [`SpawnContext::Fresh`]: inherits no ancestor history.
    #[serde(default)]
    pub fresh_context: bool,
}

/// One compaction summary entry (public and serializable for the same
/// snapshot/restore purposes as [`ThreadInfo`]).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CompactionSummary {
    pub summary: String,
    pub up_to_order: i64,
}

/// An in-memory [`ConversationStore`]: threads, message history, the thread
/// tree, and compaction summaries, all in process memory.
#[derive(Clone, Default)]
pub struct InMemoryConversationStore {
    #[expect(clippy::type_complexity, reason = "shared state")]
    messages: Arc<Mutex<HashMap<ThreadId, Vec<(InfinityMessage, String)>>>>,
    threads: Arc<Mutex<HashMap<ThreadId, ThreadInfo>>>,
    compaction_summaries: Arc<Mutex<HashMap<ThreadId, Vec<CompactionSummary>>>>,
}

impl InMemoryConversationStore {
    pub fn new() -> Self {
        Self::default()
    }

    // ── Snapshot/restore accessors ──
    //
    // Synchronous inherent methods for embeddings that layer persistence (or
    // other bookkeeping) on top of this store: they can export a thread's
    // state piece by piece, persist it however they like, and restore it
    // later — while every trait-level semantic (spawn orders, ancestor
    // chains, compaction cutoffs) stays implemented here, once.

    /// Snapshot one thread's bookkeeping, if the thread exists.
    pub fn thread_info(&self, thread_id: &ThreadId<str>) -> Option<ThreadInfo> {
        self.threads
            .lock()
            .expect("bug: mutex poisoned")
            .get(thread_id)
            .cloned()
    }

    /// Restore (or overwrite) one thread's bookkeeping.
    pub fn set_thread_info(&self, thread_id: &ThreadId<str>, info: ThreadInfo) {
        self.threads
            .lock()
            .expect("bug: mutex poisoned")
            .insert(thread_id.to_owned(), info);
    }

    /// Snapshot one thread's messages (with their dedup IDs), if any were
    /// ever appended.
    pub fn thread_messages(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Option<Vec<(InfinityMessage, String)>> {
        self.messages
            .lock()
            .expect("bug: mutex poisoned")
            .get(thread_id)
            .cloned()
    }

    /// Restore one thread's messages. Returns `true` if messages for the
    /// thread were already present (and have been overwritten).
    pub fn set_thread_messages(
        &self,
        thread_id: &ThreadId<str>,
        messages: Vec<(InfinityMessage, String)>,
    ) -> bool {
        self.messages
            .lock()
            .expect("bug: mutex poisoned")
            .insert(thread_id.to_owned(), messages)
            .is_some()
    }

    /// Snapshot one thread's compaction summaries.
    pub fn thread_compaction_summaries(&self, thread_id: &ThreadId<str>) -> Vec<CompactionSummary> {
        self.compaction_summaries
            .lock()
            .expect("bug: mutex poisoned")
            .get(thread_id)
            .cloned()
            .unwrap_or_default()
    }

    /// Restore one thread's compaction summaries. Returns `true` if
    /// summaries for the thread were already present (and overwritten).
    pub fn set_thread_compaction_summaries(
        &self,
        thread_id: &ThreadId<str>,
        summaries: Vec<CompactionSummary>,
    ) -> bool {
        self.compaction_summaries
            .lock()
            .expect("bug: mutex poisoned")
            .insert(thread_id.to_owned(), summaries)
            .is_some()
    }

    /// Spawn a child thread under `parent_thread_id` with a caller-chosen ID
    /// (the trait-level [`spawn_thread`](ConversationStore::spawn_thread)
    /// generates a UUID and delegates here). The spawn order — how much of
    /// the parent's history the child inherits — is derived from `context`:
    /// the given cutoff for [`SpawnContext::InheritUpTo`], and zero for
    /// [`SpawnContext::Fresh`] (which additionally marks the thread as a
    /// fresh-context boundary).
    pub fn spawn_thread_with_id(
        &self,
        new_thread_id: &ThreadId<str>,
        parent_thread_id: &ThreadId<str>,
        spawn_tool_call_id: &ToolCallId<str>,
        is_for_subscription_event: bool,
        context: SpawnContext,
    ) {
        let (spawn_message_order, fresh_context) = match context {
            SpawnContext::InheritUpTo(order) => (order as i64, false),
            SpawnContext::Fresh => (0, true),
        };

        let mut threads = self.threads.lock().expect("bug: mutex poisoned");
        let root = threads
            .get(parent_thread_id)
            .map(|t| t.root_thread_id.clone())
            .unwrap_or_else(|| parent_thread_id.to_owned());
        threads.insert(
            new_thread_id.to_owned(),
            ThreadInfo {
                parent_thread_id: Some(parent_thread_id.to_owned()),
                root_thread_id: root,
                spawn_message_order: Some(spawn_message_order),
                spawn_tool_call_id: Some(spawn_tool_call_id.to_owned()),
                closed: false,
                is_subscription_event: is_for_subscription_event,
                is_compaction: false,
                fresh_context,
            },
        );
    }
}

#[async_trait]
impl ConversationStore for InMemoryConversationStore {
    type Error = InMemoryStoreError;

    async fn ensure_root_thread(&self, thread_id: &ThreadId<str>) -> Result<(), Self::Error> {
        let mut threads = self.threads.lock().expect("bug: mutex poisoned");
        threads
            .entry(thread_id.to_owned())
            .or_insert_with(|| ThreadInfo {
                parent_thread_id: None,
                root_thread_id: thread_id.to_owned(),
                spawn_message_order: None,
                spawn_tool_call_id: None,
                closed: false,
                is_subscription_event: false,
                is_compaction: false,
                fresh_context: false,
            });
        Ok(())
    }

    async fn thread_exists(&self, thread_id: &ThreadId<str>) -> Result<bool, Self::Error> {
        Ok(self
            .threads
            .lock()
            .expect("bug: mutex poisoned")
            .contains_key(thread_id))
    }

    async fn load_history_up_to(
        &self,
        session_id: &ThreadId<str>,
        start_from: Option<i64>,
        up_to: Option<i64>,
    ) -> Result<Vec<InfinityMessage>, Self::Error> {
        let msgs = self.messages.lock().expect("bug: mutex poisoned");
        Ok(msgs
            .get(session_id)
            .map(|v| {
                let start = start_from.unwrap_or(0) as usize;
                let end = up_to.map(|u| u as usize).unwrap_or(v.len()).min(v.len());
                let start = start.min(end);
                v[start..end].iter().map(|(m, _)| m.clone()).collect()
            })
            .unwrap_or_default())
    }

    async fn append_messages(
        &self,
        session_id: &ThreadId<str>,
        messages: Vec<(InfinityMessage, String)>,
    ) -> Result<(), Self::Error> {
        let mut store = self.messages.lock().expect("bug: mutex poisoned");
        store
            .entry(session_id.to_owned())
            .or_default()
            .extend(messages);
        Ok(())
    }

    async fn spawn_thread(
        &self,
        parent_thread_id: &ThreadId<str>,
        spawn_tool_call_id: &ToolCallId<str>,
        is_for_subscription_event: bool,
        context: SpawnContext,
    ) -> Result<ThreadId, Self::Error> {
        let new_id = ThreadId::from(uuid::Uuid::new_v4().to_string());
        self.spawn_thread_with_id(
            &new_id,
            parent_thread_id,
            spawn_tool_call_id,
            is_for_subscription_event,
            context,
        );
        Ok(new_id)
    }

    async fn is_thread_closed(&self, thread_id: &ThreadId<str>) -> Result<bool, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        Ok(threads.get(thread_id).map(|t| t.closed).unwrap_or(false))
    }

    async fn close_thread(&self, thread_id: &ThreadId<str>) -> Result<(), Self::Error> {
        let mut threads = self.threads.lock().expect("bug: mutex poisoned");
        if let Some(t) = threads.get_mut(thread_id) {
            t.closed = true;
        }
        Ok(())
    }

    async fn is_subscription_event_thread(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<bool, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        Ok(threads
            .get(thread_id)
            .map(|t| t.is_subscription_event)
            .unwrap_or(false))
    }

    async fn is_fresh_context_thread(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<bool, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        Ok(threads
            .get(thread_id)
            .map(|t| t.fresh_context)
            .unwrap_or(false))
    }

    async fn get_thread_parent_info(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<Option<(ThreadId, ToolCallId)>, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        Ok(threads.get(thread_id).and_then(|t| {
            match (&t.parent_thread_id, &t.spawn_tool_call_id) {
                (Some(p), Some(tc)) => Some((p.clone(), tc.clone())),
                _ => None,
            }
        }))
    }

    async fn get_ancestor_chain(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<Vec<(ThreadId, i64)>, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        let mut result = Vec::new();
        let mut current = thread_id.to_owned();
        while let Some(info) = threads.get(&current) {
            let Some(parent) = info.parent_thread_id.clone() else {
                break;
            };
            let order = info.spawn_message_order.unwrap_or(0);
            result.push((parent.clone(), order));
            current = parent;
        }
        result.reverse();
        Ok(result)
    }

    async fn mark_thread_as_compaction(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<(), Self::Error> {
        let mut threads = self.threads.lock().expect("bug: mutex poisoned");
        if let Some(t) = threads.get_mut(thread_id) {
            t.is_compaction = true;
        }
        Ok(())
    }

    async fn is_compaction_thread(&self, thread_id: &ThreadId<str>) -> Result<bool, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        Ok(threads
            .get(thread_id)
            .map(|t| t.is_compaction)
            .unwrap_or(false))
    }

    async fn get_thread_spawn_order(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<Option<i64>, Self::Error> {
        let threads = self.threads.lock().expect("bug: mutex poisoned");
        Ok(threads.get(thread_id).and_then(|t| t.spawn_message_order))
    }

    async fn save_compaction_summary(
        &self,
        thread_id: &ThreadId<str>,
        summary: &str,
        up_to_order: i64,
    ) -> Result<(), Self::Error> {
        let mut cs = self
            .compaction_summaries
            .lock()
            .expect("bug: mutex poisoned");
        cs.entry(thread_id.to_owned())
            .or_default()
            .push(CompactionSummary {
                summary: summary.to_owned(),
                up_to_order,
            });
        Ok(())
    }

    async fn load_latest_compaction_summary_up_to(
        &self,
        thread_id: &ThreadId<str>,
        up_to_order: Option<i64>,
    ) -> Result<Option<(String, i64)>, Self::Error> {
        let cs = self
            .compaction_summaries
            .lock()
            .expect("bug: mutex poisoned");
        Ok(cs.get(thread_id).and_then(|v| {
            v.iter()
                .rev()
                .find(|s| up_to_order.is_none_or(|n| s.up_to_order <= n))
                .map(|s| (s.summary.clone(), s.up_to_order))
        }))
    }
}

/// Serializable snapshot of one thread's [`InMemoryStateStore`] entry, for
/// embeddings that layer persistence on top (export/restore).
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ThreadState {
    #[serde(default)]
    pub processed_message_ids: HashSet<String>,
    #[serde(default)]
    pub metadata: Option<serde_json::Value>,
    #[serde(default)]
    pub subscriptions: HashSet<ToolCallId>,
    #[serde(default)]
    pub pending_user_choices: Vec<UserChoice>,
}

/// An in-memory [`StateStore`]: processed IDs, metadata, and active
/// subscription tracking in process memory.
#[derive(Clone, Default)]
pub struct InMemoryStateStore {
    processed_ids: Arc<Mutex<HashMap<ThreadId, HashSet<String>>>>,
    metadata: Arc<Mutex<HashMap<ThreadId, serde_json::Value>>>,
    subscriptions: Arc<Mutex<HashMap<ThreadId, HashSet<ToolCallId>>>>,
    pending_user_choices: Arc<Mutex<HashMap<ThreadId, Vec<UserChoice>>>>,
}

impl InMemoryStateStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Snapshot one thread's state (see [`ThreadState`]).
    pub fn thread_state(&self, thread_id: &ThreadId<str>) -> ThreadState {
        let processed = self.processed_ids.lock().expect("bug: mutex poisoned");
        let metadata = self.metadata.lock().expect("bug: mutex poisoned");
        let subscriptions = self.subscriptions.lock().expect("bug: mutex poisoned");
        let pending_user_choices = self
            .pending_user_choices
            .lock()
            .expect("bug: mutex poisoned");
        ThreadState {
            processed_message_ids: processed.get(thread_id).cloned().unwrap_or_default(),
            metadata: metadata.get(thread_id).cloned(),
            subscriptions: subscriptions.get(thread_id).cloned().unwrap_or_default(),
            pending_user_choices: pending_user_choices
                .get(thread_id)
                .cloned()
                .unwrap_or_default(),
        }
    }

    /// Restore one thread's state (see [`ThreadState`]).
    pub fn set_thread_state(&self, thread_id: &ThreadId<str>, state: ThreadState) {
        self.processed_ids
            .lock()
            .expect("bug: mutex poisoned")
            .insert(thread_id.to_owned(), state.processed_message_ids);
        if let Some(meta) = state.metadata {
            self.metadata
                .lock()
                .expect("bug: mutex poisoned")
                .insert(thread_id.to_owned(), meta);
        }
        if !state.subscriptions.is_empty() {
            self.subscriptions
                .lock()
                .expect("bug: mutex poisoned")
                .insert(thread_id.to_owned(), state.subscriptions);
        }
        if !state.pending_user_choices.is_empty() {
            self.pending_user_choices
                .lock()
                .expect("bug: mutex poisoned")
                .insert(thread_id.to_owned(), state.pending_user_choices);
        }
    }
}

#[async_trait]
impl StateStore for InMemoryStateStore {
    type Error = InMemoryStoreError;

    async fn get_processed_ids(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<HashSet<String>, Self::Error> {
        let store = self.processed_ids.lock().expect("bug: mutex poisoned");
        Ok(store.get(thread_id).cloned().unwrap_or_default())
    }

    async fn add_processed_message_ids(
        &self,
        thread_id: &ThreadId<str>,
        message_ids: Vec<String>,
    ) -> Result<(), Self::Error> {
        let mut store = self.processed_ids.lock().expect("bug: mutex poisoned");
        store
            .entry(thread_id.to_owned())
            .or_default()
            .extend(message_ids);
        Ok(())
    }

    async fn get_metadata(
        &self,
        root_thread_id: &ThreadId<str>,
    ) -> Result<Option<serde_json::Value>, Self::Error> {
        let store = self.metadata.lock().expect("bug: mutex poisoned");
        Ok(store.get(root_thread_id).cloned())
    }

    async fn set_metadata(
        &self,
        root_thread_id: &ThreadId<str>,
        metadata: serde_json::Value,
    ) -> Result<(), Self::Error> {
        let mut store = self.metadata.lock().expect("bug: mutex poisoned");
        store.insert(root_thread_id.to_owned(), metadata);
        Ok(())
    }

    async fn get_active_subscriptions(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<Vec<ToolCallId>, Self::Error> {
        let store = self.subscriptions.lock().expect("bug: mutex poisoned");
        Ok(store
            .get(thread_id)
            .map(|s| s.iter().cloned().collect())
            .unwrap_or_default())
    }

    async fn add_active_subscription(
        &self,
        thread_id: &ThreadId<str>,
        tool_call_id: &ToolCallId<str>,
    ) -> Result<(), Self::Error> {
        let mut store = self.subscriptions.lock().expect("bug: mutex poisoned");
        store
            .entry(thread_id.to_owned())
            .or_default()
            .insert(tool_call_id.to_owned());
        Ok(())
    }

    async fn remove_active_subscription(
        &self,
        thread_id: &ThreadId<str>,
        tool_call_id: &ToolCallId<str>,
    ) -> Result<(), Self::Error> {
        let mut store = self.subscriptions.lock().expect("bug: mutex poisoned");
        if let Some(s) = store.get_mut(thread_id) {
            s.remove(tool_call_id);
        }
        Ok(())
    }

    async fn add_pending_user_choice(
        &self,
        thread_id: &ThreadId<str>,
        choice: UserChoice,
    ) -> Result<(), Self::Error> {
        let mut store = self
            .pending_user_choices
            .lock()
            .expect("bug: mutex poisoned");
        let choices = store.entry(thread_id.to_owned()).or_default();
        if let Some(existing) = choices.iter_mut().find(|existing| existing.id == choice.id) {
            *existing = choice;
        } else {
            choices.push(choice);
        }
        Ok(())
    }

    async fn remove_pending_user_choice(
        &self,
        thread_id: &ThreadId<str>,
        choice_id: &ChoiceId<str>,
    ) -> Result<(), Self::Error> {
        if let Some(choices) = self
            .pending_user_choices
            .lock()
            .expect("bug: mutex poisoned")
            .get_mut(thread_id)
        {
            choices.retain(|choice| choice.id != *choice_id);
        }
        Ok(())
    }

    async fn get_pending_user_choices(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<Vec<UserChoice>, Self::Error> {
        Ok(self
            .pending_user_choices
            .lock()
            .expect("bug: mutex poisoned")
            .get(thread_id)
            .cloned()
            .unwrap_or_default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::ConversationStore;

    fn user_msg(text: &str) -> InfinityMessage {
        InfinityMessage::User {
            content: infinity_provider_protocol::message::UserContent::Text(
                infinity_provider_protocol::message::Text {
                    text: text.to_owned(),
                },
            ),
        }
    }

    fn texts(history: &[InfinityMessage]) -> Vec<String> {
        history
            .iter()
            .filter_map(|m| match m {
                InfinityMessage::User {
                    content: infinity_provider_protocol::message::UserContent::Text(t),
                } => Some(t.text.clone()),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn fresh_spawn_inherits_no_history() {
        let store = InMemoryConversationStore::new();
        store
            .ensure_root_thread(ThreadId::from_ref("root"))
            .await
            .expect("root");
        store
            .append_messages(
                ThreadId::from_ref("root"),
                vec![
                    (user_msg("root one"), "m1".to_owned()),
                    (user_msg("root two"), "m2".to_owned()),
                ],
            )
            .await
            .expect("append");

        let child = store
            .spawn_thread(
                ThreadId::from_ref("root"),
                ToolCallId::from_ref("tc-fresh"),
                false,
                SpawnContext::Fresh,
            )
            .await
            .expect("spawn fresh child");
        store
            .append_messages(&child, vec![(user_msg("child own"), "c1".to_owned())])
            .await
            .expect("append child");

        let (history, _, ancestor_prefix_len) = store
            .load_history_with_ancestors(&child)
            .await
            .expect("load history");
        assert_eq!(ancestor_prefix_len, 0, "fresh child has no ancestor prefix");
        assert_eq!(texts(&history), vec!["child own"]);
    }

    #[tokio::test]
    async fn fresh_boundary_blocks_grandparent_context_for_descendants() {
        let store = InMemoryConversationStore::new();
        store
            .ensure_root_thread(ThreadId::from_ref("root"))
            .await
            .expect("root");
        store
            .append_messages(
                ThreadId::from_ref("root"),
                vec![(user_msg("root secret"), "m1".to_owned())],
            )
            .await
            .expect("append");

        // root → fresh child → normal grandchild
        let fresh = store
            .spawn_thread(
                ThreadId::from_ref("root"),
                ToolCallId::from_ref("tc-fresh"),
                false,
                SpawnContext::Fresh,
            )
            .await
            .expect("spawn fresh child");
        store
            .append_messages(&fresh, vec![(user_msg("fresh work"), "f1".to_owned())])
            .await
            .expect("append fresh");

        let grandchild = store
            .spawn_thread(
                &fresh,
                ToolCallId::from_ref("tc-inherit"),
                false,
                SpawnContext::InheritUpTo(1),
            )
            .await
            .expect("spawn grandchild");
        store
            .append_messages(&grandchild, vec![(user_msg("gc work"), "g1".to_owned())])
            .await
            .expect("append grandchild");

        let (history, _, ancestor_prefix_len) = store
            .load_history_with_ancestors(&grandchild)
            .await
            .expect("load history");
        assert_eq!(
            texts(&history),
            vec!["fresh work", "gc work"],
            "grandchild sees the fresh thread's context but nothing above the fresh boundary"
        );
        assert_eq!(ancestor_prefix_len, 1);
    }

    #[tokio::test]
    async fn inherit_spawn_still_sees_full_ancestor_history() {
        let store = InMemoryConversationStore::new();
        store
            .ensure_root_thread(ThreadId::from_ref("root"))
            .await
            .expect("root");
        store
            .append_messages(
                ThreadId::from_ref("root"),
                vec![(user_msg("root one"), "m1".to_owned())],
            )
            .await
            .expect("append");

        let child = store
            .spawn_thread(
                ThreadId::from_ref("root"),
                ToolCallId::from_ref("tc-1"),
                false,
                SpawnContext::InheritUpTo(1),
            )
            .await
            .expect("spawn child");
        store
            .append_messages(&child, vec![(user_msg("child own"), "c1".to_owned())])
            .await
            .expect("append child");

        let (history, _, ancestor_prefix_len) = store
            .load_history_with_ancestors(&child)
            .await
            .expect("load history");
        assert_eq!(texts(&history), vec!["root one", "child own"]);
        assert_eq!(ancestor_prefix_len, 1);
    }
}