nexil 0.8.0

Provider-agnostic LLM toolkit — streaming, tool calls, tape storage, OAuth
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! Tape manager helpers for Conduit.

use serde_json::Value;

use crate::core::errors::ConduitError;
use crate::core::results::ErrorPayload;
use crate::tape::context::{TapeContext, build_messages};
use crate::tape::entries::{TapeEntry, latest_system_content};
use crate::tape::query::TapeQuery;
use crate::tape::store::{AsyncTapeStore, AsyncTapeStoreAdapter, InMemoryTapeStore, TapeStore};

fn run_event_data(
    error: Option<&ErrorPayload>,
    usage: Option<Value>,
    provider: Option<&str>,
    model: Option<&str>,
) -> Value {
    let mut data = serde_json::Map::new();
    let status = if error.is_some() { "error" } else { "ok" };
    data.insert("status".into(), Value::String(status.into()));
    if let Some(u) = usage {
        data.insert("usage".into(), u);
    }
    if let Some(p) = provider
        && !p.is_empty()
    {
        data.insert("provider".into(), Value::String(p.into()));
    }
    if let Some(m) = model
        && !m.is_empty()
    {
        data.insert("model".into(), Value::String(m.into()));
    }
    Value::Object(data)
}

#[allow(clippy::too_many_arguments)]
fn build_chat_entries(
    meta: &Value,
    context_error: Option<&ErrorPayload>,
    new_messages: &[Value],
    tool_calls: Option<&[Value]>,
    response_text: Option<&str>,
    tool_results: Option<&[Value]>,
    error: Option<&ErrorPayload>,
    usage: Option<Value>,
    provider: Option<&str>,
    model: Option<&str>,
) -> Vec<TapeEntry> {
    let mut entries: Vec<TapeEntry> = context_error
        .iter()
        .map(|ce| TapeEntry::error(ce, meta.clone()))
        .chain(
            new_messages
                .iter()
                .map(|msg| TapeEntry::message(msg.clone(), meta.clone())),
        )
        .collect();

    if let Some(tc) = tool_calls
        && !tc.is_empty()
    {
        entries.push(TapeEntry::tool_call(tc.to_vec(), meta.clone()));
    }
    if let Some(rt) = response_text {
        let msg = serde_json::json!({ "role": "assistant", "content": rt });
        entries.push(TapeEntry::message(msg, meta.clone()));
    }
    if let Some(tr) = tool_results {
        entries.push(TapeEntry::tool_result(tr.to_vec(), meta.clone()));
    }
    if let Some(err) = error
        && !context_error.is_some_and(|ce| ce == err)
    {
        entries.push(TapeEntry::error(err, meta.clone()));
    }
    entries.push(TapeEntry::event(
        "run",
        Some(run_event_data(error, usage, provider, model)),
        meta.clone(),
    ));
    entries
}

// ---------------------------------------------------------------------------
// TapeManager (sync)
// ---------------------------------------------------------------------------

/// Global tape manager that owns storage and default context.
pub struct TapeManager {
    store: Box<dyn TapeStore>,
    default_context: TapeContext,
}

impl TapeManager {
    /// Create a new TapeManager with optional store and default context.
    pub fn new(store: Option<Box<dyn TapeStore>>, default_context: Option<TapeContext>) -> Self {
        Self {
            store: store.unwrap_or_else(|| Box::new(InMemoryTapeStore::new())),
            default_context: default_context.unwrap_or_default(),
        }
    }

    /// Get a reference to the default context.
    pub fn default_context(&self) -> &TapeContext {
        &self.default_context
    }

    /// Set the default context.
    pub fn set_default_context(&mut self, ctx: TapeContext) {
        self.default_context = ctx;
    }

    /// List all tape names.
    pub fn list_tapes(&self) -> Result<Vec<String>, ConduitError> {
        self.store.list_tapes()
    }

    /// Read messages from a tape, applying the given or default context.
    pub fn read_messages(
        &self,
        tape: &str,
        context: Option<&TapeContext>,
    ) -> Result<Vec<Value>, ConduitError> {
        let active_context = context.unwrap_or(&self.default_context);
        let query = self.query_tape(tape);
        let query = active_context.build_query(query);
        let entries = self.store.fetch_all(&query)?;
        Ok(build_messages(&entries, active_context))
    }

    /// Append an entry to a tape.
    pub fn append_entry(&self, tape: &str, entry: &TapeEntry) -> Result<(), ConduitError> {
        self.store.append(tape, entry)
    }

    /// Create a new TapeQuery for the given tape.
    pub fn query_tape(&self, tape: &str) -> TapeQuery {
        TapeQuery::new(tape)
    }

    /// Reset (delete) a tape.
    pub fn reset_tape(&self, tape: &str) -> Result<(), ConduitError> {
        self.store.reset(tape)
    }

    /// Record a handoff: creates an anchor and handoff event, appends both.
    pub fn handoff(
        &self,
        tape: &str,
        name: &str,
        state: Option<Value>,
        meta: Value,
    ) -> Result<Vec<TapeEntry>, ConduitError> {
        let entry = TapeEntry::anchor(name, state.clone(), meta.clone());
        let handoff_data = serde_json::json!({
            "name": name,
            "state": state.clone().unwrap_or_else(|| serde_json::json!({})),
        });
        let event = TapeEntry::event("handoff", Some(handoff_data), meta);
        self.store.append(tape, &entry)?;
        self.store.append(tape, &event)?;
        Ok(vec![entry, event])
    }

    /// Append a system entry only if the tape has no system entry or the content changed.
    /// Returns true if the entry was written.
    pub fn append_system_if_changed(
        &self,
        tape: &str,
        content: &str,
        meta: Value,
    ) -> Result<bool, ConduitError> {
        let query = self.query_tape(tape);
        let dominated = self
            .store
            .fetch_all(&query)
            .ok()
            .and_then(|entries| latest_system_content(&entries).map(|s| s == content))
            .unwrap_or(false);
        if dominated {
            return Ok(false);
        }
        self.store.append(tape, &TapeEntry::system(content, meta))?;
        Ok(true)
    }

    /// Record a complete chat turn to the tape.
    #[allow(clippy::too_many_arguments)]
    pub fn record_chat(
        &self,
        tape: &str,
        run_id: &str,
        system_prompt: Option<&str>,
        context_error: Option<&ErrorPayload>,
        new_messages: &[Value],
        response_text: Option<&str>,
        tool_calls: Option<&[Value]>,
        tool_results: Option<&[Value]>,
        error: Option<&ErrorPayload>,
        usage: Option<Value>,
        provider: Option<&str>,
        model: Option<&str>,
    ) -> Result<(), ConduitError> {
        let meta = serde_json::json!({ "run_id": run_id });
        if let Some(sp) = system_prompt
            && !sp.is_empty()
        {
            self.append_system_if_changed(tape, sp, meta.clone())?;
        }
        for entry in build_chat_entries(
            &meta,
            context_error,
            new_messages,
            tool_calls,
            response_text,
            tool_results,
            error,
            usage,
            provider,
            model,
        ) {
            self.store.append(tape, &entry)?;
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// AsyncTapeManager
// ---------------------------------------------------------------------------

/// Async tape manager for async chat and tool-call paths.
pub struct AsyncTapeManager {
    store: Box<dyn AsyncTapeStore>,
    default_context: TapeContext,
}

impl AsyncTapeManager {
    /// Create a new AsyncTapeManager. Accepts either an AsyncTapeStore or a sync TapeStore
    /// (which will be wrapped in AsyncTapeStoreAdapter).
    pub fn new(
        store: Option<Box<dyn AsyncTapeStore>>,
        default_context: Option<TapeContext>,
    ) -> Self {
        Self {
            store: store
                .unwrap_or_else(|| Box::new(AsyncTapeStoreAdapter::new(InMemoryTapeStore::new()))),
            default_context: default_context.unwrap_or_default(),
        }
    }

    /// Create from a sync TapeStore, wrapping it automatically.
    pub fn from_sync_store<S: TapeStore + 'static>(
        store: S,
        default_context: Option<TapeContext>,
    ) -> Self {
        Self {
            store: Box::new(AsyncTapeStoreAdapter::new(store)),
            default_context: default_context.unwrap_or_default(),
        }
    }

    /// Get a reference to the default context.
    pub fn default_context(&self) -> &TapeContext {
        &self.default_context
    }

    /// Set the default context.
    pub fn set_default_context(&mut self, ctx: TapeContext) {
        self.default_context = ctx;
    }

    /// Create a TapeQuery for the given tape.
    pub fn query_tape(&self, tape: &str) -> TapeQuery {
        TapeQuery::new(tape)
    }

    /// List all tape names.
    pub async fn list_tapes(&self) -> Result<Vec<String>, ConduitError> {
        self.store.list_tapes().await
    }

    /// Read messages from a tape, applying the given or default context.
    pub async fn read_messages(
        &self,
        tape: &str,
        context: Option<&TapeContext>,
    ) -> Result<Vec<Value>, ConduitError> {
        let active_context = context.unwrap_or(&self.default_context);
        let query = self.query_tape(tape);
        let query = active_context.build_query(query);
        let entries = self.store.fetch_all(&query).await?;
        Ok(build_messages(&entries, active_context))
    }

    /// Fetch raw tape entries matching a query.
    pub async fn fetch_entries(&self, query: &TapeQuery) -> Result<Vec<TapeEntry>, ConduitError> {
        self.store.fetch_all(query).await
    }

    /// Append an entry to a tape.
    pub async fn append_entry(&self, tape: &str, entry: &TapeEntry) -> Result<(), ConduitError> {
        self.store.append(tape, entry).await
    }

    /// Reset (delete) a tape.
    pub async fn reset_tape(&self, tape: &str) -> Result<(), ConduitError> {
        self.store.reset(tape).await
    }

    /// Record a handoff: creates an anchor and handoff event, appends both.
    pub async fn handoff(
        &self,
        tape: &str,
        name: &str,
        state: Option<Value>,
        meta: Value,
    ) -> Result<Vec<TapeEntry>, ConduitError> {
        let entry = TapeEntry::anchor(name, state.clone(), meta.clone());
        let handoff_data = serde_json::json!({
            "name": name,
            "state": state.clone().unwrap_or_else(|| serde_json::json!({})),
        });
        let event = TapeEntry::event("handoff", Some(handoff_data), meta);
        self.store.append(tape, &entry).await?;
        self.store.append(tape, &event).await?;
        Ok(vec![entry, event])
    }

    /// Append a system entry only if the tape has no system entry or the content changed.
    /// Returns true if the entry was written.
    pub async fn append_system_if_changed(
        &self,
        tape: &str,
        content: &str,
        meta: Value,
    ) -> Result<bool, ConduitError> {
        let query = self.query_tape(tape);
        let dominated = self
            .store
            .fetch_all(&query)
            .await
            .ok()
            .and_then(|entries| latest_system_content(&entries).map(|s| s == content))
            .unwrap_or(false);
        if dominated {
            return Ok(false);
        }
        self.store
            .append(tape, &TapeEntry::system(content, meta))
            .await?;
        Ok(true)
    }

    /// Record a complete chat turn to the tape.
    #[allow(clippy::too_many_arguments)]
    pub async fn record_chat(
        &self,
        tape: &str,
        run_id: &str,
        system_prompt: Option<&str>,
        context_error: Option<&ErrorPayload>,
        new_messages: &[Value],
        response_text: Option<&str>,
        tool_calls: Option<&[Value]>,
        tool_results: Option<&[Value]>,
        error: Option<&ErrorPayload>,
        usage: Option<Value>,
        provider: Option<&str>,
        model: Option<&str>,
    ) -> Result<(), ConduitError> {
        let meta = serde_json::json!({ "run_id": run_id });
        if let Some(sp) = system_prompt
            && !sp.is_empty()
        {
            self.append_system_if_changed(tape, sp, meta.clone())
                .await?;
        }
        for entry in build_chat_entries(
            &meta,
            context_error,
            new_messages,
            tool_calls,
            response_text,
            tool_results,
            error,
            usage,
            provider,
            model,
        ) {
            self.store.append(tape, &entry).await?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tape::entries::TapeEntryKind;
    use crate::tape::store::InMemoryTapeStore;
    use serde_json::json;

    #[test]
    fn test_record_chat_skips_duplicate_system_prompt() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store.clone())), None);
        let tape = "record-chat-dedup";

        manager
            .record_chat(
                tape,
                "run-1",
                Some("system prompt"),
                None,
                &[json!({"role": "user", "content": "hello"})],
                Some("hi"),
                None,
                None,
                None,
                None,
                Some("openai"),
                Some("gpt-4o"),
            )
            .unwrap();

        manager
            .record_chat(
                tape,
                "run-2",
                Some("system prompt"),
                None,
                &[json!({"role": "user", "content": "again"})],
                Some("there"),
                None,
                None,
                None,
                None,
                Some("openai"),
                Some("gpt-4o"),
            )
            .unwrap();

        let entries = store.read(tape).unwrap();
        let system_count = entries
            .iter()
            .filter(|e| e.kind == TapeEntryKind::System)
            .count();
        let message_count = entries
            .iter()
            .filter(|e| e.kind == TapeEntryKind::Message)
            .count();

        assert_eq!(system_count, 1);
        assert_eq!(latest_system_content(&entries), Some("system prompt"));
        assert_eq!(message_count, 4);
    }

    #[tokio::test]
    async fn test_async_record_chat_skips_duplicate_system_prompt() {
        let store = InMemoryTapeStore::new();
        let manager = AsyncTapeManager::new(
            Some(Box::new(AsyncTapeStoreAdapter::new(store.clone()))),
            None,
        );
        let tape = "async-record-chat-dedup";

        manager
            .record_chat(
                tape,
                "run-1",
                Some("system prompt"),
                None,
                &[json!({"role": "user", "content": "hello"})],
                Some("hi"),
                None,
                None,
                None,
                None,
                Some("openai"),
                Some("gpt-4o"),
            )
            .await
            .unwrap();

        manager
            .record_chat(
                tape,
                "run-2",
                Some("system prompt"),
                None,
                &[json!({"role": "user", "content": "again"})],
                Some("there"),
                None,
                None,
                None,
                None,
                Some("openai"),
                Some("gpt-4o"),
            )
            .await
            .unwrap();

        let entries = store.read(tape).unwrap();
        let system_count = entries
            .iter()
            .filter(|e| e.kind == TapeEntryKind::System)
            .count();
        let message_count = entries
            .iter()
            .filter(|e| e.kind == TapeEntryKind::Message)
            .count();

        assert_eq!(system_count, 1);
        assert_eq!(latest_system_content(&entries), Some("system prompt"));
        assert_eq!(message_count, 4);
    }

    #[tokio::test]
    async fn test_async_append_system_if_changed_first_write() {
        let store = InMemoryTapeStore::new();
        let manager =
            AsyncTapeManager::new(Some(Box::new(AsyncTapeStoreAdapter::new(store))), None);
        assert!(
            manager
                .append_system_if_changed("t", "hello", json!({}))
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_async_append_system_if_changed_duplicate() {
        let store = InMemoryTapeStore::new();
        let manager =
            AsyncTapeManager::new(Some(Box::new(AsyncTapeStoreAdapter::new(store))), None);
        assert!(
            manager
                .append_system_if_changed("t", "hello", json!({}))
                .await
                .unwrap()
        );
        assert!(
            !manager
                .append_system_if_changed("t", "hello", json!({}))
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_async_append_system_if_changed_on_change() {
        let store = InMemoryTapeStore::new();
        let manager =
            AsyncTapeManager::new(Some(Box::new(AsyncTapeStoreAdapter::new(store))), None);
        assert!(
            manager
                .append_system_if_changed("t", "v1", json!({}))
                .await
                .unwrap()
        );
        assert!(
            manager
                .append_system_if_changed("t", "v2", json!({}))
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_async_record_chat_with_none_system() {
        let store = InMemoryTapeStore::new();
        let manager = AsyncTapeManager::new(
            Some(Box::new(AsyncTapeStoreAdapter::new(store.clone()))),
            None,
        );
        manager
            .record_chat(
                "t",
                "r1",
                None,
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("hey"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            0
        );
    }

    #[tokio::test]
    async fn test_async_record_chat_with_empty_system() {
        let store = InMemoryTapeStore::new();
        let manager = AsyncTapeManager::new(
            Some(Box::new(AsyncTapeStoreAdapter::new(store.clone()))),
            None,
        );
        manager
            .record_chat(
                "t",
                "r1",
                Some(""),
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("hey"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            0
        );
    }

    #[tokio::test]
    async fn test_async_record_chat_writes_on_change() {
        let store = InMemoryTapeStore::new();
        let manager = AsyncTapeManager::new(
            Some(Box::new(AsyncTapeStoreAdapter::new(store.clone()))),
            None,
        );
        manager
            .record_chat(
                "t",
                "r1",
                Some("v1"),
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("hey"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        manager
            .record_chat(
                "t",
                "r2",
                Some("v2"),
                None,
                &[json!({"role": "user", "content": "bye"})],
                Some("cya"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .await
            .unwrap();
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            2
        );
        assert_eq!(latest_system_content(&entries), Some("v2"));
    }

    #[tokio::test]
    async fn test_async_record_chat_three_calls_same_prompt() {
        let store = InMemoryTapeStore::new();
        let manager = AsyncTapeManager::new(
            Some(Box::new(AsyncTapeStoreAdapter::new(store.clone()))),
            None,
        );
        for i in 0..3 {
            manager
                .record_chat(
                    "t",
                    &format!("r{i}"),
                    Some("stable"),
                    None,
                    &[json!({"role": "user", "content": format!("msg {i}")})],
                    Some("ok"),
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .await
                .unwrap();
        }
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            1
        );
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::Message)
                .count(),
            6
        );
    }

    #[test]
    fn test_append_system_if_changed_returns_true_on_first_write() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store)), None);
        let wrote = manager
            .append_system_if_changed("t", "hello", json!({}))
            .unwrap();
        assert!(wrote);
    }

    #[test]
    fn test_append_system_if_changed_returns_false_on_duplicate() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store)), None);
        assert!(
            manager
                .append_system_if_changed("t", "hello", json!({}))
                .unwrap()
        );
        assert!(
            !manager
                .append_system_if_changed("t", "hello", json!({}))
                .unwrap()
        );
    }

    #[test]
    fn test_append_system_if_changed_returns_true_on_changed_content() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store)), None);
        assert!(
            manager
                .append_system_if_changed("t", "v1", json!({}))
                .unwrap()
        );
        assert!(
            manager
                .append_system_if_changed("t", "v2", json!({}))
                .unwrap()
        );
    }

    #[test]
    fn test_record_chat_with_none_system_prompt_skips_system_entry() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store.clone())), None);
        manager
            .record_chat(
                "t",
                "r1",
                None,
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("hey"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .unwrap();
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            0
        );
    }

    #[test]
    fn test_record_chat_with_empty_system_prompt_skips_system_entry() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store.clone())), None);
        manager
            .record_chat(
                "t",
                "r1",
                Some(""),
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("hey"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .unwrap();
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            0
        );
    }

    #[test]
    fn test_record_chat_writes_new_system_on_change() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store.clone())), None);
        manager
            .record_chat(
                "t",
                "r1",
                Some("v1"),
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("hey"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .unwrap();
        manager
            .record_chat(
                "t",
                "r2",
                Some("v2"),
                None,
                &[json!({"role": "user", "content": "bye"})],
                Some("cya"),
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .unwrap();
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            2
        );
        assert_eq!(latest_system_content(&entries), Some("v2"));
    }

    #[test]
    fn test_record_chat_response_text_before_tool_results() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store.clone())), None);

        let tool_calls = vec![
            json!({"id": "c1", "type": "function", "function": {"name": "greet", "arguments": "{}"}}),
        ];
        let tool_results = vec![json!({"tool_call_id": "c1", "content": "hello"})];

        manager
            .record_chat(
                "t",
                "r1",
                None,
                None,
                &[json!({"role": "user", "content": "hi"})],
                Some("thinking aloud"),
                Some(&tool_calls),
                Some(&tool_results),
                None,
                None,
                None,
                None,
            )
            .unwrap();

        let entries = store.read("t").unwrap();
        let kinds: Vec<TapeEntryKind> = entries.iter().map(|e| e.kind).collect();

        // Find the assistant response message (has role=assistant in payload)
        let response_pos = entries.iter().position(|e| {
            e.kind == TapeEntryKind::Message
                && e.payload.get("role").and_then(|v| v.as_str()) == Some("assistant")
        });
        let tool_result_pos = kinds.iter().position(|k| *k == TapeEntryKind::ToolResult);

        assert!(
            response_pos.is_some(),
            "expected an assistant message entry"
        );
        assert!(tool_result_pos.is_some(), "expected a tool_result entry");
        assert!(
            response_pos.unwrap() < tool_result_pos.unwrap(),
            "response_text (pos {}) must appear before tool_result (pos {}), got kinds: {:?}",
            response_pos.unwrap(),
            tool_result_pos.unwrap(),
            kinds,
        );
    }

    #[test]
    fn test_record_chat_three_calls_same_prompt_only_one_system() {
        let store = InMemoryTapeStore::new();
        let manager = TapeManager::new(Some(Box::new(store.clone())), None);
        for i in 0..3 {
            manager
                .record_chat(
                    "t",
                    &format!("r{i}"),
                    Some("stable prompt"),
                    None,
                    &[json!({"role": "user", "content": format!("msg {i}")})],
                    Some("ok"),
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                )
                .unwrap();
        }
        let entries = store.read("t").unwrap();
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::System)
                .count(),
            1
        );
        assert_eq!(
            entries
                .iter()
                .filter(|e| e.kind == TapeEntryKind::Message)
                .count(),
            6
        ); // 3 user + 3 assistant
    }
}