embedmind-mcp 0.1.0

MCP memory server for AI agents: remember / recall / forget over a single local file
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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
//! MCP protocol integration tests: drive [`McpServer::serve`] with in-memory
//! pipes (the same loop the stdio binary runs) and assert on the JSON-RPC
//! responses. No subprocess, no real filesystem — the store sits on `SimVfs`.
//!
//! One test (`recall_returns_scored_hits`) uses the real embedded ONNX model
//! to prove the full remember→recall path through the protocol; the rest run
//! embedder-free for speed.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::path::Path;
use std::sync::Arc;

use embedmind_core::embed::OnnxEmbedder;
use embedmind_core::storage::sim::SimVfs;
use embedmind_core::storage::vfs::Vfs;
use embedmind_core::{Store, StoreOptions};
use embedmind_mcp::McpServer;
use serde_json::{Value, json};

/// A KV-only store (no embedder): fast, enough for everything but recall.
fn kv_store() -> Store {
    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    Store::create_with(vfs, Path::new("m.mind"), StoreOptions::default()).unwrap()
}

/// A store with the real embedded model, for the end-to-end recall test.
fn embedding_store() -> Store {
    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    let opts = StoreOptions {
        embedder: Some(Arc::new(OnnxEmbedder::load().expect("model must load"))),
        ..StoreOptions::default()
    };
    Store::create_with(vfs, Path::new("m.mind"), opts).unwrap()
}

/// A store on a `.mind` rewound to the pre-M2 shape (no full-text index):
/// content is remembered normally, then the header's fts root pointer is
/// dropped through the pager — exactly what an old file presents on open.
/// For the S9 graceful-degradation edge.
fn legacy_embedding_store(content: &str) -> Store {
    use embedmind_core::MemoryDraft;
    use embedmind_core::storage::{Pager, PagerOptions};

    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    let opts = StoreOptions {
        embedder: Some(Arc::new(OnnxEmbedder::load().expect("model must load"))),
        ..StoreOptions::default()
    };
    let mut store =
        Store::create_with(Arc::clone(&vfs), Path::new("m.mind"), opts.clone()).unwrap();
    store.remember(MemoryDraft::new(content)).unwrap();
    store.close().unwrap();

    let mut pager = Pager::open(
        Arc::clone(&vfs),
        Path::new("m.mind"),
        PagerOptions::default(),
    )
    .unwrap();
    let mut txn = pager.begin().unwrap();
    txn.set_fts_root_page(0);
    txn.commit().unwrap();
    pager.close().unwrap();

    Store::open_with(vfs, Path::new("m.mind"), opts).unwrap()
}

/// Feeds `requests` (one JSON value per line) through the server loop and
/// returns the responses in order. No project context.
fn roundtrip(store: Store, requests: &[Value]) -> Vec<Value> {
    roundtrip_in_project(store, None, requests)
}

/// [`roundtrip`] with a detected project context (M1 item 1.5).
fn roundtrip_in_project(store: Store, project: Option<&str>, requests: &[Value]) -> Vec<Value> {
    let input: String = requests.iter().map(|r| format!("{r}\n")).collect();
    let mut output = Vec::new();
    McpServer::new(store, project.map(str::to_string))
        .serve(input.as_bytes(), &mut output)
        .unwrap();
    String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect()
}

fn initialize_request(id: u64) -> Value {
    json!({
        "jsonrpc": "2.0", "id": id, "method": "initialize",
        "params": {
            "protocolVersion": "2025-06-18",
            "capabilities": {},
            "clientInfo": { "name": "test-agent", "version": "0.0.0" },
        },
    })
}

fn call(id: u64, tool: &str, arguments: Value) -> Value {
    json!({
        "jsonrpc": "2.0", "id": id, "method": "tools/call",
        "params": { "name": tool, "arguments": arguments },
    })
}

#[test]
fn initialize_handshake_and_ping() {
    let responses = roundtrip(
        kv_store(),
        &[
            initialize_request(1),
            json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }),
            json!({ "jsonrpc": "2.0", "id": 2, "method": "ping" }),
        ],
    );
    // The notification produces no response: exactly two lines out.
    assert_eq!(responses.len(), 2);
    let init = &responses[0];
    assert_eq!(init["id"], 1);
    assert_eq!(init["result"]["protocolVersion"], "2025-06-18");
    assert_eq!(init["result"]["serverInfo"]["name"], "embedmind");
    assert!(init["result"]["capabilities"]["tools"].is_object());
    assert_eq!(responses[1]["id"], 2);
    assert!(responses[1]["result"].is_object());
}

#[test]
fn unsupported_protocol_version_gets_the_latest() {
    let responses = roundtrip(
        kv_store(),
        &[json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize",
            "params": { "protocolVersion": "1999-01-01" },
        })],
    );
    assert_eq!(responses[0]["result"]["protocolVersion"], "2025-06-18");
}

#[test]
fn tools_list_exposes_the_stable_tools() {
    let responses = roundtrip(
        kv_store(),
        &[json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })],
    );
    let tools = responses[0]["result"]["tools"].as_array().unwrap();
    let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
    assert_eq!(names, ["remember", "recall", "related", "stats", "forget"]);
    for tool in tools {
        assert!(tool["inputSchema"]["type"] == "object");
        assert!(tool["description"].as_str().unwrap().len() > 10);
    }
}

#[test]
fn remember_then_forget_roundtrip_with_provenance() {
    let responses = roundtrip(
        kv_store(),
        &[
            initialize_request(1),
            call(
                2,
                "remember",
                json!({
                    "content": "the deploy script lives in scripts/deploy.ps1",
                    "project": "embedmind",
                    "metadata": { "topic": "ops", "priority": 2, "reviewed": false },
                }),
            ),
            call(3, "forget", json!({ "id": "not-a-ulid" })),
        ],
    );
    let structured = &responses[1]["result"]["structuredContent"];
    let id = structured["id"].as_str().unwrap();
    assert_eq!(id.len(), 26, "remember must return a ULID");
    assert_ne!(
        responses[1]["result"]
            .get("isError")
            .and_then(Value::as_bool),
        Some(true)
    );
    // Malformed id is a protocol error (invalid params), not a tool error.
    assert_eq!(responses[2]["error"]["code"], -32602);
}

#[test]
fn engine_failure_is_a_tool_error_not_a_crash() {
    // recall on a KV-only store is a typed engine error → isError: true,
    // and the server keeps serving afterwards.
    let responses = roundtrip(
        kv_store(),
        &[
            call(1, "recall", json!({ "query": "anything" })),
            json!({ "jsonrpc": "2.0", "id": 2, "method": "ping" }),
        ],
    );
    assert_eq!(responses[0]["result"]["isError"], true);
    let text = responses[0]["result"]["content"][0]["text"]
        .as_str()
        .unwrap();
    assert!(
        text.contains("embedder"),
        "error text should explain: {text}"
    );
    assert!(
        responses[1]["result"].is_object(),
        "server must keep serving"
    );
}

#[test]
fn protocol_errors_are_typed_json_rpc_errors() {
    let mut output = Vec::new();
    let input = "this is not json\n\
                 {\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"no/such/method\"}\n\
                 {\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"nope\"}}\n\
                 {\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{\"name\":\"remember\",\"arguments\":{}}}\n";
    McpServer::new(kv_store(), None)
        .serve(input.as_bytes(), &mut output)
        .unwrap();
    let responses: Vec<Value> = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();
    assert_eq!(responses[0]["error"]["code"], -32700, "malformed JSON");
    assert_eq!(responses[1]["error"]["code"], -32601, "unknown method");
    assert_eq!(responses[2]["error"]["code"], -32602, "unknown tool");
    assert_eq!(responses[3]["error"]["code"], -32602, "missing content");
}

#[test]
fn recall_returns_scored_hits_with_provenance() {
    let responses = roundtrip(
        embedding_store(),
        &[
            initialize_request(1),
            call(
                2,
                "remember",
                json!({ "content": "the cat sat on the warm mat" }),
            ),
            call(
                3,
                "remember",
                json!({ "content": "quarterly tax filing deadline" }),
            ),
            call(
                4,
                "recall",
                json!({ "query": "a feline resting", "limit": 2 }),
            ),
        ],
    );
    let cat_id = responses[1]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    let hits = responses[3]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert!(!hits.is_empty());
    assert_eq!(
        hits[0]["id"].as_str().unwrap(),
        cat_id,
        "cat memory must rank first for a feline query"
    );
    let first = hits[0]["score"].as_f64().unwrap();
    let last = hits[hits.len() - 1]["score"].as_f64().unwrap();
    assert!(first >= last, "hits must come best-first");
    assert_eq!(
        hits[0]["provenance"]["agent"], "test-agent",
        "clientInfo.name from initialize must be recorded as provenance"
    );
    assert!(
        responses[3]["result"]["structuredContent"]
            .get("warning")
            .is_none(),
        "a healthy file must not carry a degradation warning"
    );
}

/// S9 edge over the protocol: `recall` against a `.mind` with no full-text
/// index (a pre-M2 file) returns vector-only hits plus a `warning` field —
/// never a tool error, and the response shape is otherwise unchanged.
#[test]
fn recall_on_legacy_file_without_fts_index_returns_hits_with_warning() {
    let responses = roundtrip(
        legacy_embedding_store("the kitten sleeps on the rug"),
        &[
            initialize_request(1),
            call(2, "recall", json!({ "query": "a small feline resting" })),
        ],
    );
    let result = &responses[1]["result"];
    assert!(
        result.get("isError").is_none(),
        "degradation must never be a tool error: {result}"
    );
    let content = &result["structuredContent"];
    let hits = content["hits"].as_array().unwrap();
    assert!(
        !hits.is_empty(),
        "vector similarity must still return the memory: {content}"
    );
    assert!(hits[0]["content"].as_str().unwrap().contains("kitten"));
    let warning = content["warning"].as_str().unwrap();
    assert!(
        warning.contains("no full-text index"),
        "the warning must say what degraded: {warning}"
    );
}

/// M1 item 1.5 (DESIGN §7): with a detected project context, `remember`
/// stamps the project automatically and `recall` scopes to it by default,
/// with `scope: "all"` as the explicit global fallback and `project: null`
/// forcing a global memory.
#[test]
fn project_context_scopes_remember_and_recall_automatically() {
    let responses = roundtrip_in_project(
        embedding_store(),
        Some("alpha"),
        &[
            // Auto-scoped to alpha (no project argument).
            call(
                1,
                "remember",
                json!({ "content": "uses tokio for async runtime work" }),
            ),
            // Explicitly global (project: null).
            call(
                2,
                "remember",
                json!({ "content": "the async runtime notes apply everywhere", "project": null }),
            ),
            // Explicitly another project.
            call(
                3,
                "remember",
                json!({ "content": "async runtime decisions for the beta service", "project": "beta" }),
            ),
            // Default recall: only alpha's memory.
            call(
                4,
                "recall",
                json!({ "query": "async runtime", "limit": 10 }),
            ),
            // Explicit global fallback: all three.
            call(
                5,
                "recall",
                json!({ "query": "async runtime", "limit": 10, "scope": "all" }),
            ),
            // Targeting another project explicitly.
            call(
                6,
                "recall",
                json!({ "query": "async runtime", "limit": 10, "project": "beta" }),
            ),
        ],
    );

    assert_eq!(
        responses[0]["result"]["structuredContent"]["project"], "alpha",
        "remember must stamp the detected project"
    );
    assert_eq!(
        responses[1]["result"]["structuredContent"]["project"],
        Value::Null,
        "project: null must force a global memory"
    );

    let scoped = &responses[3]["result"]["structuredContent"];
    assert_eq!(scoped["scope"], "alpha");
    let hits = scoped["hits"].as_array().unwrap();
    assert_eq!(
        hits.len(),
        1,
        "default recall must see only the project's memories"
    );
    assert_eq!(hits[0]["project"], "alpha");

    let global = &responses[4]["result"]["structuredContent"];
    assert_eq!(global["scope"], "all");
    assert_eq!(global["hits"].as_array().unwrap().len(), 3);

    let beta = &responses[5]["result"]["structuredContent"];
    assert_eq!(beta["scope"], "beta");
    let hits = beta["hits"].as_array().unwrap();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0]["project"], "beta");
}

#[test]
fn without_project_context_recall_defaults_to_everything() {
    let responses = roundtrip(
        embedding_store(),
        &[
            call(
                1,
                "remember",
                json!({ "content": "note scoped to alpha", "project": "alpha" }),
            ),
            call(2, "remember", json!({ "content": "a global note" })),
            call(3, "recall", json!({ "query": "note", "limit": 10 })),
        ],
    );
    assert_eq!(
        responses[1]["result"]["structuredContent"]["project"],
        Value::Null,
        "no context and no argument = global memory"
    );
    let result = &responses[2]["result"]["structuredContent"];
    assert_eq!(result["scope"], "all");
    assert_eq!(result["hits"].as_array().unwrap().len(), 2);
}

/// S10: the `recall` tool accepts an optional `filters` object — exact-value
/// and numeric-range filters, ANDed — and returns only matching memories. The
/// schema addition is backward compatible: the earlier tests that never send
/// `filters` still pass, and `tools/list` still advertises the same three
/// tools.
#[test]
fn recall_filters_by_metadata_through_the_protocol() {
    let responses = roundtrip(
        embedding_store(),
        &[
            initialize_request(1),
            call(
                2,
                "remember",
                json!({
                    "content": "deploy runbook for the release",
                    "metadata": { "topic": "ops", "priority": 9 },
                }),
            ),
            call(
                3,
                "remember",
                json!({
                    "content": "design notes for the release",
                    "metadata": { "topic": "design", "priority": 2 },
                }),
            ),
            // Exact-value filter: only the ops memory.
            call(
                4,
                "recall",
                json!({ "query": "release", "scope": "all", "filters": { "topic": "ops" } }),
            ),
            // Numeric range: priority >= 5, still only the ops memory.
            call(
                5,
                "recall",
                json!({
                    "query": "release", "scope": "all",
                    "filters": { "priority": { "min": 5 } },
                }),
            ),
            // Two filters ANDed, one of which excludes everything ⇒ no hits.
            call(
                6,
                "recall",
                json!({
                    "query": "release", "scope": "all",
                    "filters": { "topic": "ops", "priority": { "max": 1 } },
                }),
            ),
        ],
    );
    let ops_id = responses[1]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let by_value = responses[3]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert_eq!(by_value.len(), 1, "topic=ops must keep exactly one memory");
    assert_eq!(by_value[0]["id"], ops_id);

    let by_range = responses[4]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert_eq!(
        by_range.len(),
        1,
        "priority>=5 must keep exactly one memory"
    );
    assert_eq!(by_range[0]["id"], ops_id);

    let anded = responses[5]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert!(anded.is_empty(), "AND of disjoint filters yields no hits");
}

/// S10 edges through the protocol: a filter on a key no memory has returns
/// zero hits (not an error), while a type-incompatible filter is surfaced as
/// a tool error (`isError: true`), not a crash.
#[test]
fn recall_filter_edges_absent_key_and_type_mismatch() {
    let responses = roundtrip(
        embedding_store(),
        &[
            call(
                1,
                "remember",
                json!({ "content": "a note", "metadata": { "topic": "ops" } }),
            ),
            // Absent key ⇒ 0 hits, still a normal (non-error) result.
            call(
                2,
                "recall",
                json!({ "query": "note", "scope": "all", "filters": { "missing": "x" } }),
            ),
            // Type mismatch: integer filter over a stored string ⇒ tool error.
            call(
                3,
                "recall",
                json!({ "query": "note", "scope": "all", "filters": { "topic": 3 } }),
            ),
        ],
    );
    let absent = &responses[1]["result"];
    assert_ne!(absent.get("isError").and_then(Value::as_bool), Some(true));
    assert!(
        absent["structuredContent"]["hits"]
            .as_array()
            .unwrap()
            .is_empty(),
        "absent-key filter must yield 0 hits, not an error"
    );
    assert_eq!(
        responses[2]["result"]["isError"], true,
        "type-incompatible filter must be a tool error"
    );
}

/// A malformed `filters` argument (not an object, or a filter that is neither
/// a scalar nor a valid range) is a protocol error (`-32602`), caught before
/// the engine runs.
#[test]
fn malformed_filters_argument_is_a_protocol_error() {
    let responses = roundtrip(
        kv_store(),
        &[
            call(1, "recall", json!({ "query": "x", "filters": [1, 2, 3] })),
            call(
                2,
                "recall",
                json!({ "query": "x", "filters": { "k": { "bogus": 1 } } }),
            ),
        ],
    );
    assert_eq!(
        responses[0]["error"]["code"], -32602,
        "filters must be an object"
    );
    assert_eq!(
        responses[1]["error"]["code"], -32602,
        "a range object needs min/max, not arbitrary keys"
    );
}

/// S14: `recall` accepts an optional `agent` filter and returns only memories
/// written by that agent. The writing agent is the `clientInfo.name` from
/// `initialize`, so this test drives two servers with different client names
/// against the same store, then recalls filtered by one of them.
#[test]
fn recall_filters_by_agent_through_the_protocol() {
    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    let opts = StoreOptions {
        embedder: Some(Arc::new(OnnxEmbedder::load().expect("model must load"))),
        ..StoreOptions::default()
    };
    let store = Store::create_with(vfs, Path::new("m.mind"), opts).unwrap();
    let mut server = McpServer::new(store, None);

    // Agent "cli" remembers one; agent "claude-code" remembers another.
    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };

    let r1 = feed(
        &mut server,
        &[
            json!({
                "jsonrpc": "2.0", "id": 1, "method": "initialize",
                "params": { "clientInfo": { "name": "cli", "version": "0" } },
            }),
            call(
                2,
                "remember",
                json!({ "content": "the cat sat on the mat" }),
            ),
        ],
    );
    let cli_id = r1[1]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let r2 = feed(
        &mut server,
        &[
            json!({
                "jsonrpc": "2.0", "id": 1, "method": "initialize",
                "params": { "clientInfo": { "name": "claude-code", "version": "0" } },
            }),
            call(
                2,
                "remember",
                json!({ "content": "a feline naps on the rug" }),
            ),
        ],
    );
    let claude_id = r2[1]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();

    // Recall filtered to agent "cli": only that agent's memory.
    let r3 = feed(
        &mut server,
        &[call(
            1,
            "recall",
            json!({ "query": "a resting cat", "scope": "all", "agent": "cli" }),
        )],
    );
    let hits = r3[0]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert_eq!(hits.len(), 1, "agent filter keeps exactly one memory");
    assert_eq!(hits[0]["id"], cli_id);
    assert_eq!(hits[0]["provenance"]["agent"], "cli");
    assert_ne!(hits[0]["id"], Value::String(claude_id));
}

/// S14: the `stats` tool reports live/forgotten counts and a per-agent
/// breakdown of live memories, all through the protocol.
#[test]
fn stats_tool_reports_provenance_breakdown() {
    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    let store = Store::create_with(vfs, Path::new("m.mind"), StoreOptions::default()).unwrap();
    let mut server = McpServer::new(store, None);

    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };

    // "cli" writes two memories.
    feed(
        &mut server,
        &[
            json!({
                "jsonrpc": "2.0", "id": 1, "method": "initialize",
                "params": { "clientInfo": { "name": "cli", "version": "0" } },
            }),
            call(2, "remember", json!({ "content": "one" })),
            call(3, "remember", json!({ "content": "two" })),
        ],
    );
    // "claude-code" writes one, then forgets it.
    let r = feed(
        &mut server,
        &[
            json!({
                "jsonrpc": "2.0", "id": 1, "method": "initialize",
                "params": { "clientInfo": { "name": "claude-code", "version": "0" } },
            }),
            call(2, "remember", json!({ "content": "three" })),
        ],
    );
    let doomed = r[1]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    feed(&mut server, &[call(3, "forget", json!({ "id": doomed }))]);

    let stats = feed(&mut server, &[call(1, "stats", json!({}))]);
    let content = &stats[0]["result"]["structuredContent"];
    assert_eq!(content["live_memories"], 2);
    assert_eq!(content["forgotten_memories"], 1);
    let by_agent = content["by_agent"].as_array().unwrap();
    // Only "cli" has live memories; the forgotten claude-code memory drops out.
    assert_eq!(by_agent.len(), 1);
    assert_eq!(by_agent[0]["agent"], "cli");
    assert_eq!(by_agent[0]["live_memories"], 2);
}

/// S13 through the protocol: `remember` accepts explicit `entities` and
/// `relations`, and the `related` tool navigates them — by id (both
/// directions, with kind) and by entity. Forgetting a neighbor makes its
/// relation disappear with the tombstone, per the story's edge case.
#[test]
fn graph_remember_related_and_tombstone_through_the_protocol() {
    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    let store = Store::create_with(vfs, Path::new("m.mind"), StoreOptions::default()).unwrap();
    let mut server = McpServer::new(store, None);

    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };

    // Memory A, then B refining A and tagged with an entity.
    let r = feed(
        &mut server,
        &[call(
            1,
            "remember",
            json!({ "content": "we chose postgres for storage" }),
        )],
    );
    let a_id = r[0]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    let r = feed(
        &mut server,
        &[call(
            2,
            "remember",
            json!({
                "content": "specifically postgres 16 with pgvector",
                "entities": ["postgres"],
                "relations": [{ "kind": "refines", "target": a_id }],
            }),
        )],
    );
    let structured = &r[0]["result"]["structuredContent"];
    let b_id = structured["id"].as_str().unwrap().to_string();
    assert_eq!(structured["entities"], json!(["postgres"]));
    assert_eq!(structured["relations"][0]["kind"], "refines");
    assert_eq!(structured["relations"][0]["target"], a_id);

    // related(B): outgoing "refines" edge to A, plus B's entity tags.
    let r = feed(&mut server, &[call(3, "related", json!({ "id": b_id }))]);
    let by_id = &r[0]["result"]["structuredContent"];
    assert_eq!(by_id["entities"], json!(["postgres"]));
    let neighbors = by_id["related"].as_array().unwrap();
    assert_eq!(neighbors.len(), 1);
    assert_eq!(neighbors[0]["id"], a_id);
    assert_eq!(neighbors[0]["kind"], "refines");
    assert_eq!(neighbors[0]["outgoing"], true);

    // related(A): the same edge, incoming.
    let r = feed(&mut server, &[call(4, "related", json!({ "id": a_id }))]);
    let neighbors = r[0]["result"]["structuredContent"]["related"]
        .as_array()
        .unwrap();
    assert_eq!(neighbors.len(), 1);
    assert_eq!(neighbors[0]["id"], b_id);
    assert_eq!(neighbors[0]["outgoing"], false);

    // related(entity): B is the only member of "postgres".
    let r = feed(
        &mut server,
        &[call(5, "related", json!({ "entity": "postgres" }))],
    );
    let by_entity = &r[0]["result"]["structuredContent"];
    assert_eq!(by_entity["entity"], "postgres");
    let members = by_entity["members"].as_array().unwrap();
    assert_eq!(members.len(), 1);
    assert_eq!(members[0]["id"], b_id);

    // Forget A: the relation disappears with the tombstone, and related(A)
    // itself becomes a tool error (no live memory).
    feed(&mut server, &[call(6, "forget", json!({ "id": a_id }))]);
    let r = feed(&mut server, &[call(7, "related", json!({ "id": b_id }))]);
    assert!(
        r[0]["result"]["structuredContent"]["related"]
            .as_array()
            .unwrap()
            .is_empty(),
        "relation to a forgotten memory must disappear with the tombstone"
    );
    let r = feed(&mut server, &[call(8, "related", json!({ "id": a_id }))]);
    assert_eq!(r[0]["result"]["isError"], true);
}

/// S13 argument edges: a relation to a nonexistent target is an engine
/// failure (tool error, nothing stored); malformed graph arguments and a
/// `related` call with neither/both selectors are protocol errors.
#[test]
fn graph_argument_edges_through_the_protocol() {
    let ghost = "01ARZ3NDEKTSV4RRFFQ69G5FAV"; // valid ULID, never stored
    let responses = roundtrip(
        kv_store(),
        &[
            call(
                1,
                "remember",
                json!({
                    "content": "points at a ghost",
                    "relations": [{ "kind": "refines", "target": ghost }],
                }),
            ),
            call(
                2,
                "remember",
                json!({ "content": "bad relations", "relations": "not-an-array" }),
            ),
            call(
                3,
                "remember",
                json!({ "content": "bad target", "relations": [{ "kind": "refines", "target": "not-a-ulid" }] }),
            ),
            call(
                4,
                "remember",
                json!({ "content": "bad entities", "entities": [1, 2] }),
            ),
            call(5, "related", json!({})),
            call(6, "related", json!({ "id": ghost, "entity": "postgres" })),
            call(7, "related", json!({ "id": "not-a-ulid" })),
            call(8, "related", json!({ "id": ghost })),
            call(9, "related", json!({ "entity": "nobody-tagged-this" })),
        ],
    );
    assert_eq!(
        responses[0]["result"]["isError"], true,
        "relation to a nonexistent target is a tool error"
    );
    assert_eq!(responses[1]["error"]["code"], -32602);
    assert_eq!(responses[2]["error"]["code"], -32602);
    assert_eq!(responses[3]["error"]["code"], -32602);
    assert_eq!(
        responses[4]["error"]["code"], -32602,
        "neither id nor entity"
    );
    assert_eq!(responses[5]["error"]["code"], -32602, "both id and entity");
    assert_eq!(responses[6]["error"]["code"], -32602, "malformed id");
    assert_eq!(
        responses[7]["result"]["isError"], true,
        "unknown id is a tool error, not a crash"
    );
    // An entity nobody used is an empty member list, not an error.
    let members = responses[8]["result"]["structuredContent"]["members"]
        .as_array()
        .unwrap();
    assert!(members.is_empty());
}

/// S13: `recall` with `expand_related: true` appends each hit's related
/// memories as connected context with score 0, after the ranked hits.
#[test]
fn recall_expand_related_pulls_connected_context() {
    // Relating B to A needs A's id from an earlier response, so this test
    // feeds the server in stages instead of one `roundtrip` batch.
    let mut server = McpServer::new(embedding_store(), None);
    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };
    let r = feed(
        &mut server,
        &[call(
            1,
            "remember",
            json!({ "content": "the cat sat on the warm mat" }),
        )],
    );
    let cat = r[0]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    feed(
        &mut server,
        &[call(
            2,
            "remember",
            json!({
                "content": "quarterly tax filing deadline is in april",
                "relations": [{ "kind": "mentioned-with", "target": cat }],
            }),
        )],
    );
    let r = feed(
        &mut server,
        &[
            call(
                3,
                "recall",
                json!({ "query": "a feline resting", "limit": 1 }),
            ),
            call(
                4,
                "recall",
                json!({ "query": "a feline resting", "limit": 1, "expand_related": true }),
            ),
        ],
    );
    let plain = r[0]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert_eq!(plain.len(), 1, "without expansion: only the ranked hit");
    assert_eq!(plain[0]["id"], cat);

    let expanded = r[1]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert_eq!(
        expanded.len(),
        2,
        "expansion appends the related memory beyond the limit"
    );
    assert_eq!(expanded[0]["id"], cat, "ranked hit stays first");
    assert!(
        expanded[1]["content"]
            .as_str()
            .unwrap()
            .contains("tax filing"),
        "the graph neighbor comes along as context"
    );
    assert_eq!(
        expanded[1]["score"].as_f64().unwrap(),
        0.0,
        "expanded hits carry score 0 — context, not a ranked match"
    );
}

/// S20: `recall` accepts `recency: bool` and plumbs it through to the engine
/// — the tie-break math itself is covered exhaustively in
/// `embedmind-core`'s `recall.rs` unit/property tests and `tests/recall.rs`
/// end-to-end tests; this just proves the protocol shell doesn't swallow the
/// parameter and rejects a non-boolean value.
#[test]
fn recall_recency_flag_is_accepted_and_type_checked() {
    let responses = roundtrip(
        embedding_store(),
        &[
            call(
                1,
                "remember",
                json!({ "content": "the cat sat on the mat" }),
            ),
            call(
                2,
                "recall",
                json!({ "query": "a feline resting", "recency": true }),
            ),
            call(
                3,
                "recall",
                json!({ "query": "a feline resting", "recency": "yes" }),
            ),
        ],
    );
    let hits = responses[1]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert!(
        !hits.is_empty(),
        "recall with recency: true must still return hits"
    );
    assert!(
        responses[2].get("error").is_some(),
        "a non-boolean recency value must be a protocol error"
    );
}

#[test]
fn invalid_scope_is_a_protocol_error() {
    let responses = roundtrip(
        kv_store(),
        &[call(
            1,
            "recall",
            json!({ "query": "x", "scope": "everything" }),
        )],
    );
    assert_eq!(responses[0]["error"]["code"], -32602);
}

#[test]
fn forget_through_protocol_hides_memory_from_recall() {
    // remember → forget(id) → recall finds nothing of it.
    let store = embedding_store();
    let input_1 = format!(
        "{}\n",
        call(
            1,
            "remember",
            json!({ "content": "temporary secret note about the launch date" })
        )
    );
    let mut out_1 = Vec::new();
    let mut server = McpServer::new(store, None);
    server.serve(input_1.as_bytes(), &mut out_1).unwrap();
    let first: Value =
        serde_json::from_str(String::from_utf8(out_1).unwrap().lines().next().unwrap()).unwrap();
    let id = first["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let input_2 = format!(
        "{}\n{}\n",
        call(2, "forget", json!({ "id": id })),
        call(
            3,
            "recall",
            json!({ "query": "launch date note", "limit": 5 })
        ),
    );
    let mut out_2 = Vec::new();
    server.serve(input_2.as_bytes(), &mut out_2).unwrap();
    let responses: Vec<Value> = String::from_utf8(out_2)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();
    assert_eq!(responses[0]["result"]["structuredContent"]["count"], 1);
    let hits = responses[1]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert!(
        hits.iter().all(|h| h["id"].as_str().unwrap() != id),
        "forgotten memory must not be recalled"
    );
}

/// S19 through the protocol: `remember` accepts `supersedes: [ids]`, echoes
/// them back, the version chain is navigable via `related` in both
/// directions, and argument/engine edges fail the right way (protocol error
/// vs. tool error, nothing stored).
#[test]
fn supersedes_remember_related_and_edges_through_the_protocol() {
    let vfs: Arc<dyn Vfs> = Arc::new(SimVfs::new());
    let store = Store::create_with(vfs, Path::new("m.mind"), StoreOptions::default()).unwrap();
    let mut server = McpServer::new(store, Some("alpha".to_string()));

    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };

    // A (in project "alpha"), then B superseding A.
    let r = feed(
        &mut server,
        &[call(
            1,
            "remember",
            json!({ "content": "fact, first version" }),
        )],
    );
    let a_id = r[0]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    let r = feed(
        &mut server,
        &[call(
            2,
            "remember",
            json!({ "content": "fact, corrected", "supersedes": [a_id] }),
        )],
    );
    let structured = &r[0]["result"]["structuredContent"];
    let b_id = structured["id"].as_str().unwrap().to_string();
    assert_eq!(structured["supersedes"], json!([a_id]));

    // The chain is navigable both ways with the "supersedes" kind.
    let r = feed(&mut server, &[call(3, "related", json!({ "id": b_id }))]);
    let neighbors = r[0]["result"]["structuredContent"]["related"]
        .as_array()
        .unwrap();
    assert_eq!(neighbors.len(), 1);
    assert_eq!(neighbors[0]["id"], a_id);
    assert_eq!(neighbors[0]["kind"], "supersedes");
    assert_eq!(neighbors[0]["outgoing"], true);
    assert_eq!(
        neighbors[0]["superseded"], true,
        "the old version is marked as history"
    );
    let r = feed(&mut server, &[call(4, "related", json!({ "id": a_id }))]);
    let neighbors = r[0]["result"]["structuredContent"]["related"]
        .as_array()
        .unwrap();
    assert_eq!(neighbors.len(), 1);
    assert_eq!(neighbors[0]["id"], b_id);
    assert_eq!(neighbors[0]["outgoing"], false);
    assert_eq!(
        neighbors[0]["superseded"], false,
        "the current version is not history"
    );

    // Edges. Malformed arguments are protocol errors; a ghost target or a
    // cross-project target is an engine failure (tool error, nothing stored).
    let ghost = "01ARZ3NDEKTSV4RRFFQ69G5FAV"; // valid ULID, never stored
    let r = feed(
        &mut server,
        &[
            call(
                5,
                "remember",
                json!({ "content": "bad shape", "supersedes": "not-an-array" }),
            ),
            call(
                6,
                "remember",
                json!({ "content": "bad id", "supersedes": ["not-a-ulid"] }),
            ),
            call(
                7,
                "remember",
                json!({ "content": "ghost target", "supersedes": [ghost] }),
            ),
            call(
                8,
                "remember",
                json!({ "content": "global cannot supersede scoped",
                        "project": null, "supersedes": [a_id] }),
            ),
        ],
    );
    assert_eq!(r[0]["error"]["code"], -32602);
    assert_eq!(r[1]["error"]["code"], -32602);
    assert_eq!(r[2]["result"]["isError"], true, "ghost target: tool error");
    assert_eq!(
        r[3]["result"]["isError"], true,
        "cross-project (global vs. alpha) target: tool error"
    );
}

/// S19 end to end with the real model: after `remember(supersedes: [A])`,
/// recall through the protocol returns only the new version — and forgetting
/// the new version does not resurrect the old one.
#[test]
fn supersedes_hides_old_version_from_recall_through_protocol() {
    let mut server = McpServer::new(embedding_store(), None);
    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };

    let r = feed(
        &mut server,
        &[call(
            1,
            "remember",
            json!({ "content": "the launch date is august 4th" }),
        )],
    );
    let old_id = r[0]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    let r = feed(
        &mut server,
        &[call(
            2,
            "remember",
            json!({ "content": "the launch date moved to august 11th",
                    "supersedes": [old_id] }),
        )],
    );
    let new_id = r[0]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();

    let r = feed(
        &mut server,
        &[call(
            3,
            "recall",
            json!({ "query": "when is the launch date" }),
        )],
    );
    let hits = r[0]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert!(
        hits.iter().any(|h| h["id"] == new_id.as_str()),
        "the new version must be recalled: {hits:?}"
    );
    assert!(
        hits.iter().all(|h| h["id"] != old_id.as_str()),
        "the superseded version must not be recalled: {hits:?}"
    );

    // Forgetting the superseder does not resurrect the superseded (its
    // exclusion is state on its own record, docs/adr/0013).
    let r = feed(
        &mut server,
        &[
            call(4, "forget", json!({ "id": new_id })),
            call(5, "recall", json!({ "query": "when is the launch date" })),
        ],
    );
    assert_eq!(r[0]["result"]["structuredContent"]["count"], 1);
    let hits = r[1]["result"]["structuredContent"]["hits"]
        .as_array()
        .unwrap();
    assert!(
        hits.iter().all(|h| h["id"] != old_id.as_str()),
        "forget of the new version must not resurrect the old: {hits:?}"
    );
}

/// S21 end to end with the real model: `remember` reports near-duplicates in
/// `similar` (id, truncated content, score, created_at_micros), scoped to the
/// applied project, without ever blocking the store. The field is additive —
/// pre-S21 clients simply ignore it.
#[test]
fn remember_reports_similar_through_the_protocol() {
    let mut server = McpServer::new(embedding_store(), Some("alpha".to_string()));
    let feed = |server: &mut McpServer, reqs: &[Value]| -> Vec<Value> {
        let input: String = reqs.iter().map(|r| format!("{r}\n")).collect();
        let mut out = Vec::new();
        server.serve(input.as_bytes(), &mut out).unwrap();
        String::from_utf8(out)
            .unwrap()
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect()
    };

    // First memory of the file: nothing to duplicate.
    let content = "the cache eviction policy is LRU with a 4 GiB cap";
    let r = feed(
        &mut server,
        &[call(1, "remember", json!({ "content": content }))],
    );
    let first = &r[0]["result"]["structuredContent"];
    let first_id = first["id"].as_str().unwrap().to_string();
    assert_eq!(first["similar"].as_array().unwrap().len(), 0, "{first}");

    // Same content again, same scope: the first memory comes back as a
    // near-duplicate with all four fields — and the store still happened.
    let r = feed(
        &mut server,
        &[call(2, "remember", json!({ "content": content }))],
    );
    let second = &r[0]["result"]["structuredContent"];
    assert!(second["id"].as_str().is_some(), "the store always happens");
    let similar = second["similar"].as_array().unwrap();
    assert_eq!(similar.len(), 1, "{second}");
    assert_eq!(similar[0]["id"], first_id.as_str());
    assert_eq!(similar[0]["content"], content);
    assert!(
        similar[0]["score"].as_f64().unwrap() > 0.99,
        "identical content: {}",
        similar[0]["score"]
    );
    assert!(similar[0]["created_at_micros"].as_i64().unwrap() > 0);

    // Different applied scope (global via project: null): the near-duplicate
    // lives in "alpha", so nothing is reported.
    let r = feed(
        &mut server,
        &[call(
            3,
            "remember",
            json!({ "content": content, "project": null }),
        )],
    );
    let global = &r[0]["result"]["structuredContent"];
    assert_eq!(global["similar"].as_array().unwrap().len(), 0, "{global}");
}

/// A KV-only store (no embedder) still answers `remember` with the S21 shape:
/// `similar` present and empty — never an error.
#[test]
fn remember_similar_is_empty_on_a_kv_only_store() {
    let responses = roundtrip(
        kv_store(),
        &[
            call(1, "remember", json!({ "content": "kv fact" })),
            call(2, "remember", json!({ "content": "kv fact" })),
        ],
    );
    for r in &responses {
        let similar = r["result"]["structuredContent"]["similar"]
            .as_array()
            .unwrap();
        assert!(similar.is_empty(), "{r}");
    }
}

// ---------------------------------------------------------------------------
// S22: structured op-log — one JSONL line per tool call.

/// A `Write` handle over a shared buffer: the test hands one clone to the
/// server as the op-log sink and reads the logged lines from the other.
#[derive(Clone)]
struct SharedBuf(Arc<std::sync::Mutex<Vec<u8>>>);

impl SharedBuf {
    fn new() -> SharedBuf {
        SharedBuf(Arc::new(std::sync::Mutex::new(Vec::new())))
    }
    fn contents(&self) -> String {
        String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
    }
}

impl std::io::Write for SharedBuf {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(buf);
        Ok(buf.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// A sink whose every write fails — the disk-full stand-in for the "a log
/// failure never fails the tool call" contract.
struct FailingSink;

impl std::io::Write for FailingSink {
    fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
        Err(std::io::Error::other("disk full"))
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Err(std::io::Error::other("disk full"))
    }
}

/// The S22 story end to end, in-memory: a session with an op-log attached
/// appends exactly one line per tool call; every line parses as its own JSON
/// value and carries `{ts, tool, args, ids, scores, latency_ms, project,
/// isError}`; free-text arguments are truncated; both an engine error and a
/// protocol error on a dispatched call are logged with `isError: true`.
#[test]
fn op_log_appends_one_parseable_json_line_per_tool_call() {
    use embedmind_mcp::OpLog;

    let long_content = "the launch decision considered many alternatives ".repeat(20);
    assert!(
        long_content.chars().count() > 300,
        "content must exceed the cap"
    );
    let requests = [
        initialize_request(1),
        call(2, "remember", json!({ "content": long_content })),
        call(
            3,
            "recall",
            json!({ "query": "launch decision", "scope": "all" }),
        ),
        call(4, "stats", json!({})),
        // Engine error: a well-formed but unknown id — tool result isError.
        call(5, "related", json!({ "id": "01ARZ3NDEKTSV4RRFFQ69G5FAV" })),
        // Protocol error on a dispatched call: unknown tool.
        call(6, "explode", json!({})),
    ];
    let input: String = requests.iter().map(|r| format!("{r}\n")).collect();
    let mut output = Vec::new();
    let sink = SharedBuf::new();
    McpServer::new(embedding_store(), Some("demo".to_string()))
        .with_op_log(OpLog::from_writer(sink.clone(), "test-buffer"))
        .serve(input.as_bytes(), &mut output)
        .unwrap();

    // stdout stays pure protocol: every line is a JSON-RPC response.
    let responses: Vec<Value> = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();
    assert_eq!(responses.len(), 6);
    let remembered_id = responses[1]["result"]["structuredContent"]["id"]
        .as_str()
        .unwrap()
        .to_string();
    assert_eq!(responses[4]["result"]["isError"], true, "{}", responses[4]);
    assert_eq!(responses[5]["error"]["code"], -32602, "{}", responses[5]);

    // One line per tool call plus the "session" marker from `initialize`
    // (S23 — what `embedmind report` counts sessions from), each line its
    // own independently parseable JSON value — the tail-from-anywhere
    // contract.
    let logged = sink.contents();
    let entries: Vec<Value> = logged
        .lines()
        .map(|l| serde_json::from_str(l).expect("every op-log line parses alone"))
        .collect();
    assert_eq!(
        entries.len(),
        6,
        "session marker + one line per tool call:\n{logged}"
    );
    let tools: Vec<&str> = entries
        .iter()
        .map(|e| e["tool"].as_str().unwrap())
        .collect();
    assert_eq!(
        tools,
        [
            "session", "remember", "recall", "stats", "related", "explode"
        ]
    );

    // The session marker carries the client name and the uniform line shape.
    let session = &entries[0];
    assert_eq!(session["args"]["client"], "test-agent", "{session}");
    assert_eq!(session["isError"], false, "{session}");
    assert_eq!(session["latency_ms"], 0.0, "{session}");

    for entry in &entries {
        assert!(entry["ts"].as_u64().unwrap() > 0, "{entry}");
        assert!(entry["latency_ms"].as_f64().unwrap() >= 0.0, "{entry}");
        assert_eq!(entry["project"], "demo", "{entry}");
        assert!(entry["args"].is_object(), "{entry}");
        assert!(entry["ids"].is_array(), "{entry}");
        assert!(entry["scores"].is_array(), "{entry}");
        assert!(entry["isError"].is_boolean(), "{entry}");
    }

    // remember: the stored id is logged; the content is truncated to ~200
    // chars (199 + the `…` cut marker at most 201).
    let remember = &entries[1];
    assert_eq!(remember["isError"], false);
    assert_eq!(remember["ids"][0], remembered_id.as_str(), "{remember}");
    let logged_content = remember["args"]["content"].as_str().unwrap();
    assert!(
        logged_content.chars().count() <= 201,
        "content must be truncated, got {} chars",
        logged_content.chars().count()
    );
    assert!(logged_content.ends_with(''), "{logged_content}");

    // recall: hit ids and their scores are logged, query short = untouched.
    let recall = &entries[2];
    assert_eq!(recall["isError"], false);
    assert_eq!(recall["args"]["query"], "launch decision");
    let ids = recall["ids"].as_array().unwrap();
    let scores = recall["scores"].as_array().unwrap();
    assert!(
        ids.iter().any(|id| id == remembered_id.as_str()),
        "{recall}"
    );
    assert_eq!(ids.len(), scores.len(), "{recall}");
    assert!(scores.iter().all(|s| s.as_f64().unwrap() > 0.0), "{recall}");

    // stats: no ids, no scores, still one line.
    assert_eq!(entries[3]["isError"], false);
    assert_eq!(entries[3]["ids"].as_array().unwrap().len(), 0);

    // Engine error: logged, isError true, message carried.
    let engine_error = &entries[4];
    assert_eq!(engine_error["isError"], true, "{engine_error}");
    assert!(
        engine_error["error"]
            .as_str()
            .unwrap()
            .contains("no live memory"),
        "{engine_error}"
    );

    // Protocol error on a dispatched call: also logged, isError true.
    let protocol_error = &entries[5];
    assert_eq!(protocol_error["isError"], true, "{protocol_error}");
    assert!(
        protocol_error["error"]
            .as_str()
            .unwrap()
            .contains("unknown tool"),
        "{protocol_error}"
    );
}

/// The inviolable rule: an op-log write failure NEVER fails the tool call —
/// the client gets its normal response and the loop keeps serving.
#[test]
fn op_log_write_failure_never_fails_the_tool_call() {
    use embedmind_mcp::OpLog;

    let requests = [
        initialize_request(1),
        call(
            2,
            "remember",
            json!({ "content": "fact under a broken log" }),
        ),
        call(3, "stats", json!({})),
    ];
    let input: String = requests.iter().map(|r| format!("{r}\n")).collect();
    let mut output = Vec::new();
    McpServer::new(kv_store(), None)
        .with_op_log(OpLog::from_writer(FailingSink, "broken-disk"))
        .serve(input.as_bytes(), &mut output)
        .unwrap();

    let responses: Vec<Value> = String::from_utf8(output)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();
    assert_eq!(responses.len(), 3);
    // Both tool calls succeeded normally despite every log write failing.
    assert!(
        responses[1]["result"]["structuredContent"]["id"].is_string(),
        "{}",
        responses[1]
    );
    assert!(
        responses[1]["result"].get("isError").is_none(),
        "{}",
        responses[1]
    );
    assert!(
        responses[2]["result"]["structuredContent"]["live_memories"].is_number(),
        "{}",
        responses[2]
    );
}