codescout 0.12.1

High-performance coding agent toolkit MCP server
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
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
use super::*;
use crate::agent::Agent;
use std::sync::Arc;
use tempfile::tempdir;

fn lsp() -> Arc<dyn crate::lsp::LspProvider> {
    crate::lsp::LspManager::new_arc()
}

/// Memory writes may return either `"ok"` (no best-effort side-effect
/// failures) or `{"status":"ok", "warnings":[…]}` (one or more non-fatal
/// side effects failed — e.g. no semantic index built in the test fixture
/// so `cross_embed_memory` fails). Both count as a successful write; this
/// helper keeps tests indifferent to which shape they got.
fn assert_memory_write_ok(result: &Value) {
    if result == &json!("ok") {
        return;
    }
    assert_eq!(result["status"], json!("ok"), "unexpected result: {result}");
}

async fn test_ctx_with_project() -> (tempfile::TempDir, ToolContext) {
    let dir = tempdir().unwrap();
    // Create .codescout dir so MemoryStore::open works
    std::fs::create_dir_all(dir.path().join(".codescout")).unwrap();
    let agent = Agent::new(Some(dir.path().to_path_buf())).await.unwrap();
    (
        dir,
        ToolContext {
            agent,
            lsp: lsp(),
            output_buffer: std::sync::Arc::new(crate::tools::output_buffer::OutputBuffer::new(20)),
            progress: None,
            peer: None,
            section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
                crate::tools::section_coverage::SectionCoverage::new(),
            )),
        },
    )
}

async fn test_ctx_no_project() -> ToolContext {
    ToolContext {
        agent: Agent::new(None).await.unwrap(),
        lsp: lsp(),
        output_buffer: std::sync::Arc::new(crate::tools::output_buffer::OutputBuffer::new(20)),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
    }
}

#[tokio::test]
async fn write_and_read_roundtrip() {
    let (_dir, ctx) = test_ctx_with_project().await;
    let result = WriteMemory
        .call(
            json!({
                "topic": "test-topic",
                "content": "hello memory"
            }),
            &ctx,
        )
        .await
        .unwrap();
    assert_eq!(result, "ok");

    let result = ReadMemory
        .call(json!({ "topic": "test-topic" }), &ctx)
        .await
        .unwrap();
    assert_eq!(result["content"], "hello memory");
}

#[tokio::test]
async fn read_missing_returns_null() {
    let (_dir, ctx) = test_ctx_with_project().await;
    let err = ReadMemory
        .call(json!({ "topic": "nonexistent" }), &ctx)
        .await;
    assert!(err.is_err());
    let msg = err.unwrap_err().to_string();
    assert!(msg.contains("nonexistent"), "got: {msg}");
}

#[tokio::test]
async fn list_after_writes() {
    let (_dir, ctx) = test_ctx_with_project().await;
    WriteMemory
        .call(json!({ "topic": "b-topic", "content": "b" }), &ctx)
        .await
        .unwrap();
    WriteMemory
        .call(json!({ "topic": "a-topic", "content": "a" }), &ctx)
        .await
        .unwrap();

    let result = ListMemories.call(json!({}), &ctx).await.unwrap();
    let topics: Vec<&str> = result["topics"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert_eq!(topics, vec!["a-topic", "b-topic"]);
}

#[tokio::test]
async fn delete_removes_entry() {
    let (_dir, ctx) = test_ctx_with_project().await;
    WriteMemory
        .call(json!({ "topic": "to-delete", "content": "bye" }), &ctx)
        .await
        .unwrap();
    DeleteMemory
        .call(json!({ "topic": "to-delete" }), &ctx)
        .await
        .unwrap();

    let err = ReadMemory.call(json!({ "topic": "to-delete" }), &ctx).await;
    assert!(err.is_err());
}

#[tokio::test]
async fn memory_delete_removes_anchor_sidecar() {
    use crate::memory::anchors::anchor_path_for_topic;

    let (dir, ctx) = test_ctx_with_project().await;

    // Write a memory; this also creates the path-anchor sidecar
    // (see write_creates_anchor_sidecar).
    Memory
        .call(
            json!({
                "action": "write",
                "topic": "anchor-leak-fixture",
                "content": "anchors should not leak on delete"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let memories_dir = dir.path().join(".codescout/memories");
    let sidecar = anchor_path_for_topic(&memories_dir, "anchor-leak-fixture");

    // Sidecar may or may not exist depending on whether path-anchor
    // computation found matching files in the empty fixture project.
    // Pre-create one so the test is deterministic.
    std::fs::create_dir_all(&memories_dir).unwrap();
    std::fs::write(&sidecar, "anchors = []\n").unwrap();
    assert!(sidecar.exists(), "fixture sidecar must exist pre-delete");

    Memory
        .call(
            json!({
                "action": "delete",
                "topic": "anchor-leak-fixture"
            }),
            &ctx,
        )
        .await
        .unwrap();

    assert!(
        !sidecar.exists(),
        "anchor sidecar should be removed when its memory is deleted"
    );
}

#[tokio::test]
async fn memory_forget_delegates_to_store() {
    use crate::memory::semantic_store::test_support::InMemorySemanticMemoryStore;
    use crate::memory::semantic_store::{MemoryFilter, SemanticMemoryStore};
    use crate::retrieval::memory_payload::{point_id_for, SemanticMemory};
    use std::sync::Arc;

    let (_dir, ctx) = test_ctx_with_project().await;

    // Swap in the in-memory stub before any tool call — once Agent caches a
    // store via semantic_memory_store(), set_semantic_memory_store_for_test
    // would fail with SetError.
    let stub: Arc<InMemorySemanticMemoryStore> = Arc::new(InMemorySemanticMemoryStore::new());
    ctx.agent
        .set_semantic_memory_store_for_test(stub.clone() as Arc<dyn SemanticMemoryStore>)
        .map_err(|_| ())
        .expect("set stub");

    // Resolve the active project_id (matches what the tool will look up).
    let project_id = ctx
        .agent
        .with_project(|p| Ok(p.config.project.name.clone()))
        .await
        .unwrap();

    // Pre-seed a memory with a known id.
    let id = point_id_for(&project_id, "unstructured", "to-forget");
    let mem = SemanticMemory {
        project_id: project_id.clone(),
        bucket: "unstructured".into(),
        title: "to-forget".into(),
        content: "doomed".into(),
        anchors: vec![],
        created_at: "2026-05-13T00:00:00Z".into(),
        updated_at: "2026-05-13T00:00:00Z".into(),
    };
    stub.upsert(&mem, &[0.0_f32; 8]).await.unwrap();
    assert_eq!(
        stub.list(&project_id, MemoryFilter::default())
            .await
            .unwrap()
            .len(),
        1,
        "fixture must seed exactly one memory"
    );

    // Forget via the unified tool — exercises the
    // set_semantic_memory_store_for_test seam end-to-end.
    Memory
        .call(json!({ "action": "forget", "id": id.to_string() }), &ctx)
        .await
        .unwrap();

    assert_eq!(
        stub.list(&project_id, MemoryFilter::default())
            .await
            .unwrap()
            .len(),
        0,
        "forget must remove the memory from the stub"
    );

    // Idempotency: a second forget on the same id must not error.
    Memory
        .call(json!({ "action": "forget", "id": id.to_string() }), &ctx)
        .await
        .unwrap();
}

#[tokio::test]
async fn memory_remember_then_recall_e2e_via_test_seams() {
    use crate::memory::semantic_store::test_support::InMemorySemanticMemoryStore;
    use crate::memory::semantic_store::SemanticMemoryStore;
    use crate::retrieval::embedder::DenseEmbedder;
    use std::sync::Arc;

    let (_dir, ctx) = test_ctx_with_project().await;

    // Stub the dense embedder so memory ops don't need a live retrieval
    // stack. A constant vector makes every recall match every memory at
    // cosine 1.0, which is enough to exercise the round-trip without
    // requiring real semantic similarity.
    struct FixedEmbedder;
    #[async_trait::async_trait]
    impl DenseEmbedder for FixedEmbedder {
        async fn embed(&self, _text: &str) -> anyhow::Result<Vec<f32>> {
            Ok(vec![1.0_f32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        }
    }
    ctx.agent
        .set_memory_embedder_for_test(Arc::new(FixedEmbedder) as Arc<dyn DenseEmbedder>)
        .map_err(|_| ())
        .expect("set embedder");

    // Stub the semantic memory store too — same seam pattern as 4g.
    let stub: Arc<InMemorySemanticMemoryStore> = Arc::new(InMemorySemanticMemoryStore::new());
    ctx.agent
        .set_semantic_memory_store_for_test(stub.clone() as Arc<dyn SemanticMemoryStore>)
        .map_err(|_| ())
        .expect("set store");

    // remember — exercises the full tool path: project_id resolution,
    // dense embedding via the seam, point_id derivation, upsert.
    Memory
        .call(
            json!({
                "action": "remember",
                "content": "shipped fix for migration default path",
                "title": "step-7-cli-fix",
                "bucket": "unstructured",
            }),
            &ctx,
        )
        .await
        .unwrap();

    // recall — same path in reverse: embed query, dense KNN, payload decode.
    let result = Memory
        .call(
            json!({
                "action": "recall",
                "query": "migration default path",
                "limit": 3,
            }),
            &ctx,
        )
        .await
        .unwrap();

    let hits = result["results"]
        .as_array()
        .unwrap_or_else(|| panic!("expected `results` array, got: {result}"));
    assert_eq!(hits.len(), 1, "expected exactly one hit; got: {result}");
    assert_eq!(hits[0]["title"], "step-7-cli-fix");
    assert_eq!(hits[0]["bucket"], "unstructured");
    assert!(hits[0]["content"]
        .as_str()
        .unwrap()
        .contains("migration default path"));
}

#[tokio::test]
async fn tools_error_without_active_project() {
    let ctx = test_ctx_no_project().await;
    assert!(WriteMemory
        .call(json!({ "topic": "x", "content": "y" }), &ctx)
        .await
        .is_err());
    assert!(ReadMemory
        .call(json!({ "topic": "x" }), &ctx)
        .await
        .is_err());
    assert!(ListMemories.call(json!({}), &ctx).await.is_err());
    assert!(DeleteMemory
        .call(json!({ "topic": "x" }), &ctx)
        .await
        .is_err());
}

#[tokio::test]
async fn nested_topic_works() {
    let (_dir, ctx) = test_ctx_with_project().await;
    WriteMemory
        .call(
            json!({
                "topic": "debugging/async-patterns",
                "content": "avoid blocking the runtime"
            }),
            &ctx,
        )
        .await
        .unwrap();

    let result = ReadMemory
        .call(json!({ "topic": "debugging/async-patterns" }), &ctx)
        .await
        .unwrap();
    assert_eq!(result["content"], "avoid blocking the runtime");
}

#[test]
fn list_memories_format_compact() {
    use serde_json::json;
    let tool = ListMemories;
    let r = json!({ "topics": ["a", "b", "c"] });
    let t = tool.format_compact(&r).unwrap();
    assert!(t.contains("3"), "got: {t}");
}

#[test]
fn write_memory_schema_has_private_field() {
    let schema = WriteMemory.input_schema();
    assert!(schema["properties"]["private"].is_object());
    assert_eq!(schema["properties"]["private"]["type"], "boolean");
}

#[test]
fn read_memory_schema_has_private_field() {
    let schema = ReadMemory.input_schema();
    assert!(schema["properties"]["private"].is_object());
    assert_eq!(schema["properties"]["private"]["type"], "boolean");
}

#[test]
fn delete_memory_schema_has_private_field() {
    let schema = DeleteMemory.input_schema();
    assert!(schema["properties"]["private"].is_object());
    assert_eq!(schema["properties"]["private"]["type"], "boolean");
}

#[test]
fn list_memories_schema_has_include_private_field() {
    let schema = ListMemories.input_schema();
    assert!(schema["properties"]["include_private"].is_object());
    assert_eq!(schema["properties"]["include_private"]["type"], "boolean");
}

#[tokio::test]
async fn write_private_goes_to_private_store() {
    let (_dir, ctx) = test_ctx_with_project().await;
    WriteMemory
        .call(
            json!({"topic": "prefs", "content": "verbose", "private": true}),
            &ctx,
        )
        .await
        .unwrap();
    // not in shared store
    let shared = ctx
        .agent
        .with_project(|p| p.memory.read("prefs"))
        .await
        .unwrap();
    assert_eq!(shared, None);
    // is in private store
    let private = ctx
        .agent
        .with_project(|p| p.private_memory.read("prefs"))
        .await
        .unwrap();
    assert_eq!(private, Some("verbose".to_string()));
}

#[tokio::test]
async fn read_private_reads_from_private_store() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| p.private_memory.write("wip", "issue-42"))
        .await
        .unwrap();
    let result = ReadMemory
        .call(json!({"topic": "wip", "private": true}), &ctx)
        .await
        .unwrap();
    assert_eq!(result["content"], "issue-42");
}

#[tokio::test]
async fn read_private_does_not_see_shared() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| p.memory.write("shared-topic", "data"))
        .await
        .unwrap();
    // private store doesn't have the topic → should error, not return shared data
    let err = ReadMemory
        .call(json!({"topic": "shared-topic", "private": true}), &ctx)
        .await;
    assert!(err.is_err());
}

#[tokio::test]
async fn delete_private_removes_from_private_store() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| p.private_memory.write("tmp", "gone"))
        .await
        .unwrap();
    DeleteMemory
        .call(json!({"topic": "tmp", "private": true}), &ctx)
        .await
        .unwrap();
    let result = ctx
        .agent
        .with_project(|p| p.private_memory.read("tmp"))
        .await
        .unwrap();
    assert_eq!(result, None);
}

#[tokio::test]
async fn delete_private_does_not_affect_shared_store() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| p.memory.write("tmp", "keep"))
        .await
        .unwrap();
    DeleteMemory
        .call(json!({"topic": "tmp", "private": true}), &ctx)
        .await
        .unwrap();
    let result = ctx
        .agent
        .with_project(|p| p.memory.read("tmp"))
        .await
        .unwrap();
    assert_eq!(result, Some("keep".to_string()));
}

#[tokio::test]
async fn list_memories_default_returns_topics_key() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| p.memory.write("arch", "..."))
        .await
        .unwrap();
    let result = ListMemories.call(json!({}), &ctx).await.unwrap();
    assert!(result["topics"].is_array());
    assert!(result["shared"].is_null()); // old shape preserved by default
}

#[tokio::test]
async fn list_memories_include_private_returns_shared_and_private_keys() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| {
            p.memory.write("arch", "...")?;
            p.private_memory.write("prefs", "...")?;
            Ok(())
        })
        .await
        .unwrap();
    let result = ListMemories
        .call(json!({"include_private": true}), &ctx)
        .await
        .unwrap();
    assert!(result["shared"].is_array());
    assert!(result["private"].is_array());
    assert!(result["topics"].is_null()); // new shape, no "topics" key
    let shared: Vec<_> = result["shared"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    assert!(shared.contains(&"arch"));
    let private: Vec<_> = result["private"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    assert!(private.contains(&"prefs"));
}

#[tokio::test]
async fn list_memories_include_private_empty_private_store() {
    let (_dir, ctx) = test_ctx_with_project().await;
    ctx.agent
        .with_project(|p| p.memory.write("arch", "..."))
        .await
        .unwrap();
    let result = ListMemories
        .call(json!({"include_private": true}), &ctx)
        .await
        .unwrap();
    let private = result["private"].as_array().unwrap();
    assert!(private.is_empty());
}

// --- format_list_memories / format_read_memory tests ---

#[test]
fn format_list_memories_shows_topic_names() {
    let result = serde_json::json!({
        "topics": ["architecture", "conventions", "gotchas"]
    });
    let out = format_list_memories(&result);
    assert!(out.contains("architecture"), "should list topic names");
    assert!(out.contains("conventions"), "should list topic names");
    assert!(out.contains("gotchas"), "should list topic names");
    assert!(out.contains('3'), "should include count");
}

#[test]
fn format_list_memories_empty() {
    let result = serde_json::json!({ "topics": [] });
    let out = format_list_memories(&result);
    assert!(out.contains('0'), "should say 0 topics");
}

#[test]
fn format_list_memories_include_private_shows_both() {
    let result = serde_json::json!({ "shared": ["arch", "conventions"], "private": ["prefs"] });
    let out = format_list_memories(&result);
    assert!(out.contains("2 shared"));
    assert!(out.contains("1 private"));
    assert!(out.contains("arch"));
    assert!(out.contains("prefs"));
}

#[test]
fn format_list_memories_include_private_empty_private() {
    let result = serde_json::json!({ "shared": ["arch"], "private": [] });
    let out = format_list_memories(&result);
    assert!(out.contains("1 shared"));
    assert!(out.contains("0 private"));
}

#[test]
fn format_read_memory_shows_content() {
    let result = serde_json::json!({
        "content": "## Layers\n\nAgent → Server → Tools"
    });
    let out = format_read_memory(&result);
    assert!(out.contains("Layers"), "should show content");
    assert!(
        out.contains("Agent → Server → Tools"),
        "should show full content"
    );
}

#[tokio::test]
async fn memory_write_and_read_via_dispatch() {
    let (dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;

    // write
    let w = tool
        .call(
            json!({ "action": "write", "topic": "test/key", "content": "hello" }),
            &ctx,
        )
        .await
        .unwrap();
    assert_memory_write_ok(&w);

    // read
    let r = tool
        .call(json!({ "action": "read", "topic": "test/key" }), &ctx)
        .await
        .unwrap();
    assert_eq!(r["content"], json!("hello"));

    drop(dir);
}

#[tokio::test]
async fn memory_large_read_buffers_as_file_ref() {
    // Regression: memory(action="read") for large topics must return a @file_* ref
    // rather than {"content":"..."} inline. Without this, call_content wraps the
    // result in a 3-line @tool_* JSON envelope, making start_line/end_line useless.
    let (dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;

    // Write a topic whose content exceeds TOOL_OUTPUT_BUFFER_THRESHOLD (10 KB)
    let big: String = (1..=300)
        .map(|i| format!("# line {:04} padding_padding_padding_pad\n", i))
        .collect();
    assert!(
        big.len() > crate::tools::TOOL_OUTPUT_BUFFER_THRESHOLD,
        "test data must exceed threshold ({} bytes), got {}",
        crate::tools::TOOL_OUTPUT_BUFFER_THRESHOLD,
        big.len()
    );
    tool.call(
        json!({ "action": "write", "topic": "large-topic", "content": big }),
        &ctx,
    )
    .await
    .unwrap();

    let result = tool
        .call(json!({ "action": "read", "topic": "large-topic" }), &ctx)
        .await
        .unwrap();

    // Large content: must return @file_* ref, not inline {"content": "..."}
    assert!(
        result.get("file_id").is_some(),
        "large memory read should return @file_* ref; got: {}",
        result
    );
    assert_eq!(result["total_lines"].as_u64().unwrap(), 300);

    // Verify the @file_* ref is line-navigable
    let file_id = result["file_id"].as_str().unwrap().to_string();
    let sub = crate::tools::read_file::ReadFile
        .call(
            json!({"path": file_id, "start_line": 10, "end_line": 10}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        sub["content"].as_str().unwrap_or("").contains("line 0010"),
        "sub-range on @file_* ref should return line 10; got: {}",
        sub
    );

    drop(dir);
}

#[tokio::test]
async fn memory_list_via_dispatch() {
    let (dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    tool.call(
        json!({ "action": "write", "topic": "a", "content": "x" }),
        &ctx,
    )
    .await
    .unwrap();
    let result = tool.call(json!({ "action": "list" }), &ctx).await.unwrap();
    let topics = result["topics"].as_array().expect("expected topics array");
    assert!(topics.iter().any(|t| t.as_str() == Some("a")));
    drop(dir);
}

#[tokio::test]
async fn memory_delete_via_dispatch() {
    let (dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    tool.call(
        json!({ "action": "write", "topic": "to_delete", "content": "x" }),
        &ctx,
    )
    .await
    .unwrap();
    tool.call(json!({ "action": "delete", "topic": "to_delete" }), &ctx)
        .await
        .unwrap();
    let result = tool
        .call(json!({ "action": "read", "topic": "to_delete" }), &ctx)
        .await;
    assert!(result.is_err(), "expected error reading deleted topic");
    drop(dir);
}

#[tokio::test]
async fn memory_unknown_action_returns_recoverable_error() {
    let (dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    let result = tool.call(json!({ "action": "explode" }), &ctx).await;
    assert!(result.is_err());
    drop(dir);
}

#[tokio::test]
async fn memory_remember_requires_content() {
    let (_dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    let result = tool.call(json!({ "action": "remember" }), &ctx).await;
    assert!(result.is_err(), "should error without content");
}

#[tokio::test]
async fn memory_recall_requires_query() {
    let (_dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    let result = tool.call(json!({ "action": "recall" }), &ctx).await;
    assert!(result.is_err(), "should error without query");
}

#[tokio::test]
async fn memory_forget_requires_id() {
    let (_dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    let result = tool.call(json!({ "action": "forget" }), &ctx).await;
    assert!(result.is_err(), "should error without id");
}

#[test]
fn memory_schema_has_new_actions() {
    let schema = Memory.input_schema();
    let actions = schema["properties"]["action"]["enum"].as_array().unwrap();
    assert!(actions.contains(&json!("remember")));
    assert!(actions.contains(&json!("recall")));
    assert!(actions.contains(&json!("forget")));
}

#[test]
fn memory_schema_has_new_properties() {
    let schema = Memory.input_schema();
    assert!(schema["properties"]["query"].is_object());
    assert!(schema["properties"]["bucket"].is_object());
    assert!(schema["properties"]["title"].is_object());
    assert!(schema["properties"]["id"].is_object());
    assert!(schema["properties"]["limit"].is_object());
}

#[test]
fn extract_title_first_sentence() {
    assert_eq!(
        extract_title("Hello world. More text here."),
        "Hello world."
    );
}

#[test]
fn extract_title_truncates_long_content() {
    let long = "a".repeat(200);
    let title = extract_title(&long);
    assert!(title.len() <= 83); // 80 + "..."
}

#[test]
fn extract_title_short_content() {
    assert_eq!(extract_title("Short"), "Short");
}

#[test]
fn extract_title_used_in_cross_embed_context() {
    // Verify extract_title works for typical memory topics
    assert_eq!(
        extract_title("Three layer architecture design."),
        "Three layer architecture design."
    );
}

#[test]
fn extract_title_multibyte_at_boundary() {
    // \u{2500} (box drawing char) is 3 bytes each. 27 chars = 81 bytes.
    // Byte 80 falls inside the 27th char (bytes 78..81), so naive
    // content[..80] would panic. safe_truncate rounds down to byte 78.
    let content: String = "\u{2500}".repeat(27);
    let title = extract_title(&content);
    // Should not panic and should end with "..."
    assert!(
        title.ends_with("..."),
        "expected trailing '...', got: {title}"
    );
    // Title body (minus the "...") should be valid UTF-8 and <= 80 bytes
    let body = &title[..title.len() - 3];
    assert!(body.len() <= 80);
    assert!(body.len() % 3 == 0, "should truncate at char boundary");
}

#[tokio::test]
async fn memory_write_still_works_without_embedder() {
    // Write should succeed even if cross-embedding fails
    let (_dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    let result = tool
        .call(
            json!({ "action": "write", "topic": "test-topic", "content": "hello" }),
            &ctx,
        )
        .await
        .unwrap();
    assert_memory_write_ok(&result);

    // Verify markdown file was written
    let read_result = tool
        .call(json!({ "action": "read", "topic": "test-topic" }), &ctx)
        .await
        .unwrap();
    assert_eq!(read_result["content"], "hello");
}

#[tokio::test]
async fn memory_delete_still_works_without_embedder() {
    let (_dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    tool.call(
        json!({ "action": "write", "topic": "del-me", "content": "x" }),
        &ctx,
    )
    .await
    .unwrap();
    let result = tool
        .call(json!({ "action": "delete", "topic": "del-me" }), &ctx)
        .await
        .unwrap();
    assert_eq!(result, json!("ok"));
}

#[tokio::test]
async fn memory_write_private_not_cross_embedded() {
    // Private memories should not attempt cross-embedding
    let (_dir, ctx) = test_ctx_with_project().await;
    let tool = Memory;
    let result = tool
            .call(
                json!({ "action": "write", "topic": "secret", "content": "private data", "private": true }),
                &ctx,
            )
            .await
            .unwrap();
    assert_eq!(result, json!("ok"));
}

#[tokio::test]
async fn write_creates_anchor_sidecar() {
    let (dir, ctx) = test_ctx_with_project().await;

    // Create a source file in the temp project
    std::fs::create_dir_all(dir.path().join("src/tools")).unwrap();
    std::fs::write(dir.path().join("src/tools/mod.rs"), "pub fn tool() {}").unwrap();

    let input = json!({
        "action": "write",
        "topic": "architecture",
        "content": "## Tools\nThe tool trait lives in `src/tools/mod.rs`."
    });
    let result = Memory.call(input, &ctx).await.unwrap();
    assert_memory_write_ok(&result);

    // Check sidecar was created
    let sidecar = dir
        .path()
        .join(".codescout/memories/architecture.anchors.toml");
    assert!(sidecar.exists(), "anchor sidecar should be created");
    let af = crate::memory::anchors::read_anchor_file(&sidecar).unwrap();
    assert_eq!(af.anchors.len(), 1);
    assert_eq!(af.anchors[0].path, "src/tools/mod.rs");
}

#[tokio::test]
async fn refresh_anchors_clears_staleness() {
    let (dir, ctx) = test_ctx_with_project().await;
    let memories_dir = dir.path().join(".codescout/memories");
    std::fs::create_dir_all(&memories_dir).unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::write(dir.path().join("src/a.rs"), "v1").unwrap();

    // Write memory to create sidecar
    Memory
        .call(
            json!({
                "action": "write",
                "topic": "test-topic",
                "content": "References `src/a.rs`."
            }),
            &ctx,
        )
        .await
        .unwrap();

    // Modify file to make it stale
    std::fs::write(dir.path().join("src/a.rs"), "v2").unwrap();

    // Verify stale
    let af =
        crate::memory::anchors::read_anchor_file(&memories_dir.join("test-topic.anchors.toml"))
            .unwrap();
    let report = crate::memory::anchors::check_path_staleness(dir.path(), &af).unwrap();
    assert!(!report.is_fresh());

    // Refresh anchors
    let result = Memory
        .call(
            json!({
                "action": "refresh_anchors",
                "topic": "test-topic"
            }),
            &ctx,
        )
        .await
        .unwrap();
    assert_eq!(result, json!("ok"));

    // Verify fresh
    let af =
        crate::memory::anchors::read_anchor_file(&memories_dir.join("test-topic.anchors.toml"))
            .unwrap();
    let report = crate::memory::anchors::check_path_staleness(dir.path(), &af).unwrap();
    assert!(report.is_fresh());
}

#[tokio::test]
async fn memory_write_routes_to_project_dir() {
    use crate::agent::Agent;
    use std::sync::Arc;

    let dir = tempdir().unwrap();
    let root = dir.path();

    // Multi-project structure: root gradle project + mcp-server sub-project
    std::fs::write(root.join("build.gradle.kts"), "").unwrap();
    let mcp = root.join("mcp-server");
    std::fs::create_dir_all(&mcp).unwrap();
    std::fs::write(mcp.join("package.json"), r#"{"scripts":{"build":"tsc"}}"#).unwrap();
    // .codescout dir needed for Agent::new
    std::fs::create_dir_all(root.join(".codescout")).unwrap();

    let agent = Agent::new(Some(root.to_path_buf())).await.unwrap();
    let lsp: Arc<dyn crate::lsp::LspProvider> = crate::lsp::LspManager::new_arc();
    let ctx = ToolContext {
        agent,
        lsp,
        output_buffer: Arc::new(crate::tools::output_buffer::OutputBuffer::new(20)),
        progress: None,
        peer: None,
        section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
            crate::tools::section_coverage::SectionCoverage::new(),
        )),
    };

    // Write memory to mcp-server project
    Memory
        .call(
            json!({
                "action": "write",
                "topic": "conventions",
                "content": "Use camelCase",
                "project_id": "mcp-server"
            }),
            &ctx,
        )
        .await
        .unwrap();

    // File should be in per-project dir
    let project_mem_path = root.join(".codescout/projects/mcp-server/memories/conventions.md");
    assert!(
        project_mem_path.exists(),
        "memory should be in per-project dir: {project_mem_path:?}"
    );

    // Write memory with no project param — resolves to workspace root dir
    Memory
        .call(
            json!({
                "action": "write",
                "topic": "root-conventions",
                "content": "Use Kotlin idioms"
            }),
            &ctx,
        )
        .await
        .unwrap();

    // Root memory in workspace-level dir
    let root_mem_path = root.join(".codescout/memories/root-conventions.md");
    assert!(
        root_mem_path.exists(),
        "root memory should be in workspace-level dir: {root_mem_path:?}"
    );

    // list scoped to mcp-server should only show conventions
    let list_result = Memory
        .call(
            json!({ "action": "list", "project_id": "mcp-server" }),
            &ctx,
        )
        .await
        .unwrap();
    let topics: Vec<&str> = list_result["topics"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert_eq!(topics, vec!["conventions"]);

    // read scoped to mcp-server
    let read_result = Memory
        .call(
            json!({ "action": "read", "topic": "conventions", "project_id": "mcp-server" }),
            &ctx,
        )
        .await
        .unwrap();
    assert_eq!(read_result["content"], "Use camelCase");

    // delete scoped to mcp-server
    Memory
        .call(
            json!({ "action": "delete", "topic": "conventions", "project_id": "mcp-server" }),
            &ctx,
        )
        .await
        .unwrap();
    assert!(!project_mem_path.exists(), "memory should be deleted");
}

#[tokio::test]
async fn memory_read_sections_filter_integration() {
    let (_dir, ctx) = test_ctx_with_project().await;

    // Write a multi-section memory
    let content =
        "# Lang Patterns\n\nIntro.\n\n### Rust\n\nRust stuff.\n\n### TypeScript\n\nTS stuff.\n";
    Memory
        .call(
            json!({ "action": "write", "topic": "language-patterns", "content": content }),
            &ctx,
        )
        .await
        .unwrap();

    // Filter to Rust only
    let result = Memory
        .call(
            json!({ "action": "read", "topic": "language-patterns", "sections": ["Rust"] }),
            &ctx,
        )
        .await
        .unwrap();
    let text = result["content"].as_str().unwrap();
    assert!(text.contains("### Rust"), "should contain Rust section");
    assert!(text.contains("Rust stuff."));
    assert!(
        !text.contains("### TypeScript"),
        "should not contain TypeScript"
    );
    assert!(text.contains("# Lang Patterns"), "should contain preamble");

    // Empty sections array → full content (same as omitting the param)
    let result = Memory
        .call(
            json!({ "action": "read", "topic": "language-patterns", "sections": [] }),
            &ctx,
        )
        .await
        .unwrap();
    let text = result["content"].as_str().unwrap();
    assert!(
        text.contains("### Rust") && text.contains("### TypeScript"),
        "empty sections = full content"
    );

    // Unknown section → RecoverableError; hint lists available sections.
    // Tool::call returns Err(RecoverableError) directly — route_tool_error is
    // only invoked by the MCP server, not in unit tests.
    let err = Memory
        .call(
            json!({ "action": "read", "topic": "language-patterns", "sections": ["Go"] }),
            &ctx,
        )
        .await
        .unwrap_err();
    let rec = err
        .downcast_ref::<RecoverableError>()
        .expect("should be RecoverableError");
    let hint = rec.hint().unwrap_or("");
    assert!(
        hint.contains("Rust") && hint.contains("TypeScript"),
        "hint should list available sections: {hint}"
    );

    // Partial match → content + missing list
    let result = Memory
        .call(
            json!({ "action": "read", "topic": "language-patterns", "sections": ["Rust", "Go"] }),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        result["content"].as_str().is_some(),
        "matched sections should be in content"
    );
    let missing = result["missing"]
        .as_array()
        .expect("missing field should be present");
    assert_eq!(missing, &[json!("Go")]);
}

#[tokio::test]
async fn memory_read_sections_string_coerced() {
    let (_dir, ctx) = test_ctx_with_project().await;

    let content =
        "# Lang Patterns\n\nIntro.\n\n### Rust\n\nRust stuff.\n\n### TypeScript\n\nTS stuff.\n";
    Memory
        .call(
            json!({ "action": "write", "topic": "lang-coerce-test", "content": content }),
            &ctx,
        )
        .await
        .unwrap();

    // Simulate MCP client that stringifies array params
    let result = Memory
        .call(
            json!({ "action": "read", "topic": "lang-coerce-test", "sections": "[\"Rust\"]" }),
            &ctx,
        )
        .await
        .unwrap();
    let text = result["content"].as_str().unwrap();
    assert!(text.contains("### Rust"), "should contain Rust section");
    assert!(
        !text.contains("### TypeScript"),
        "should not contain TypeScript"
    );
}

#[tokio::test]
async fn memory_read_sections_filter_private_integration() {
    let (_dir, ctx) = test_ctx_with_project().await;

    // Write a private multi-section memory
    let content = "### Rust\n\nRust stuff.\n\n### Python\n\nPython stuff.\n";
    Memory
        .call(
            json!({ "action": "write", "topic": "lang", "content": content, "private": true }),
            &ctx,
        )
        .await
        .unwrap();

    // Filtering applies in the private branch too
    let result = Memory
        .call(
            json!({ "action": "read", "topic": "lang", "sections": ["Rust"], "private": true }),
            &ctx,
        )
        .await
        .unwrap();
    let text = result["content"].as_str().unwrap();
    assert!(text.contains("### Rust"), "should contain Rust");
    assert!(!text.contains("### Python"), "should not contain Python");
}