allsource-core 0.29.0

High-performance event store core built in Rust
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
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
//! Prime API endpoints — exposes graph, vector, and recall operations
//! through Core's existing HTTP server.
//!
//! Feature-gated behind `prime`. When enabled, adds `/api/v1/prime/*` routes
//! to the Core server. Prime runs embedded (same process, no HTTP hop).

use std::sync::Arc;

use axum::{
    Json, Router,
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
    routing::{MethodRouter, delete, get, patch, post, put},
};
use serde::Deserialize;
use serde_json::{Value, json};

use crate::prime::{
    AssertionInput, Direction, EnforcementMode, Prime, PrimeError, SchemaEntry, SchemaKind,
};

/// Shared Prime state, initialized once during server startup.
pub struct PrimeState {
    pub prime: Prime,
}

/// One routed Prime endpoint. [`prime_router`] and [`openapi_document`] are
/// both built from [`prime_routes`], so a route cannot be served without
/// being documented.
pub struct PrimeRoute {
    /// Path relative to `/api/v1/prime`, in axum/OpenAPI `{param}` form.
    pub path: &'static str,
    /// Lower-case HTTP method.
    pub method: &'static str,
    pub summary: &'static str,
    /// Status code of a successful response.
    pub success: u16,
    /// JSON Schema of the request body, if the route takes one.
    pub request: Option<Value>,
    handler: MethodRouter<Arc<PrimeState>>,
}

impl PrimeRoute {
    fn new(
        method: &'static str,
        path: &'static str,
        summary: &'static str,
        success: u16,
        handler: MethodRouter<Arc<PrimeState>>,
    ) -> Self {
        Self {
            path,
            method,
            summary,
            success,
            request: None,
            handler,
        }
    }

    fn body(mut self, schema: Value) -> Self {
        self.request = Some(schema);
        self
    }
}

fn assertion_schema_properties() -> Value {
    json!({
        "source": {
            "type": "string",
            "enum": ["user", "agent", "extraction", "import"],
            "description": "extraction requires run_id and a non-empty derived_from"
        },
        "actor": {"type": "string"},
        "model": {"type": "string"},
        "run_id": {"type": "string"},
        "derived_from": {"type": "array", "items": {"type": "string"}},
        "confidence": {"type": "number", "minimum": 0.0, "maximum": 1.0},
        "source_priority": {"type": "integer"}
    })
}

fn with_assertion(mut schema: Value) -> Value {
    if let (Some(props), Value::Object(extra)) = (
        schema.get_mut("properties").and_then(Value::as_object_mut),
        assertion_schema_properties(),
    ) {
        props.extend(extra);
    }
    schema
}

/// Every Prime route, in registration order.
pub fn prime_routes() -> Vec<PrimeRoute> {
    #[cfg_attr(not(feature = "prime-vectors"), allow(unused_mut))]
    let mut routes = vec![
        PrimeRoute::new("post", "/nodes", "Create a node", 201, post(create_node)).body(
            with_assertion(json!({
                "type": "object",
                "required": ["type", "properties"],
                "properties": {"type": {"type": "string"}, "properties": {"type": "object"}}
            })),
        ),
        PrimeRoute::new("get", "/nodes/{id}", "Get a node", 200, get(get_node)),
        PrimeRoute::new(
            "patch",
            "/nodes/{id}",
            "Update a node",
            200,
            patch(update_node),
        )
        .body(with_assertion(json!({
            "type": "object",
            "required": ["properties"],
            "properties": {"properties": {"type": "object"}}
        }))),
        PrimeRoute::new(
            "delete",
            "/nodes/{id}",
            "Delete a node",
            200,
            delete(delete_node),
        ),
        PrimeRoute::new(
            "get",
            "/nodes/{id}/neighbors",
            "Neighbors of a node",
            200,
            get(get_neighbors),
        ),
        PrimeRoute::new(
            "get",
            "/nodes/{id}/history",
            "Event history of a node",
            200,
            get(get_history),
        ),
        PrimeRoute::new("post", "/edges", "Create an edge", 201, post(create_edge)).body(
            with_assertion(json!({
                "type": "object",
                "required": ["source", "target", "relation"],
                "properties": {
                    "source": {"type": "string"},
                    "target": {"type": "string"},
                    "relation": {"type": "string"},
                    "properties": {"type": "object"},
                    "weight": {"type": "number"}
                }
            })),
        ),
        PrimeRoute::new(
            "delete",
            "/edges/{id}",
            "Delete an edge",
            200,
            delete(delete_edge_handler),
        ),
        PrimeRoute::new(
            "post",
            "/projections",
            "Define a declarative projection",
            201,
            post(define_projection),
        )
        .body(json!({
            "type": "object",
            "required": ["entity_type", "field_policies"],
            "properties": {
                "entity_type": {"type": "string"},
                "field_policies": {"type": "object", "additionalProperties": {
                    "type": "string",
                    "enum": ["last_write", "highest_priority", "most_specific", "merge_array"]
                }}
            }
        })),
        PrimeRoute::new(
            "get",
            "/projections",
            "List projections",
            200,
            get(list_projections),
        ),
        PrimeRoute::new(
            "post",
            "/nodes/{id}/project",
            "Fold a node through its projection",
            200,
            post(project_node),
        ),
        PrimeRoute::new(
            "get",
            "/nodes/{id}/fields/{field}/provenance",
            "Provenance of one projected field",
            200,
            get(field_provenance),
        ),
        PrimeRoute::new(
            "post",
            "/types",
            "Register or re-register a node or edge kind",
            201,
            post(define_type),
        )
        .body(json!({
            "type": "object",
            "required": ["type_name", "kind", "schema"],
            "properties": {
                "type_name": {"type": "string"},
                "kind": {"type": "string", "enum": ["node", "edge"]},
                "schema": {"type": "object"}
            }
        })),
        PrimeRoute::new(
            "get",
            "/types",
            "List registered kinds",
            200,
            get(list_types),
        ),
        PrimeRoute::new(
            "put",
            "/enforcement",
            "Set the enforcement mode",
            200,
            put(set_enforcement),
        )
        .body(json!({
            "type": "object",
            "required": ["mode"],
            "properties": {"mode": {"type": "string", "enum": ["open", "warn", "strict"]}}
        })),
        PrimeRoute::new(
            "get",
            "/enforcement",
            "Current enforcement mode",
            200,
            get(get_enforcement),
        ),
        PrimeRoute::new("get", "/stats", "Graph statistics", 200, get(get_stats)),
        PrimeRoute::new(
            "get",
            "/graph",
            "Full materialized graph",
            200,
            get(get_full_graph),
        ),
        PrimeRoute::new(
            "get",
            "/openapi.json",
            "This OpenAPI document",
            200,
            get(openapi_json),
        ),
    ];

    #[cfg(feature = "prime-vectors")]
    routes.extend([
        PrimeRoute::new(
            "post",
            "/vectors",
            "Store a vector",
            201,
            post(store_vector),
        )
        .body(json!({
            "type": "object",
            "required": ["id", "vector"],
            "properties": {
                "id": {"type": "string"},
                "text": {"type": "string"},
                "vector": {"type": "array", "items": {"type": "number"}},
                "metadata": {"type": "object"}
            }
        })),
        PrimeRoute::new(
            "post",
            "/vectors/search",
            "Vector similarity search",
            200,
            post(search_vectors),
        )
        .body(json!({
            "type": "object",
            "required": ["vector"],
            "properties": {
                "vector": {"type": "array", "items": {"type": "number"}},
                "top_k": {"type": "integer"}
            }
        })),
        PrimeRoute::new(
            "delete",
            "/vectors/{id}",
            "Delete a vector",
            200,
            delete(delete_vector),
        ),
        PrimeRoute::new("post", "/recall", "Hybrid recall", 200, post(recall)).body(json!({
            "type": "object",
            "properties": {
                "vector": {"type": "array", "items": {"type": "number"}},
                "node_type": {"type": "string"},
                "depth": {"type": "integer"},
                "top_k": {"type": "integer"},
                "tenant_id": {"type": "string"}
            }
        })),
    ]);

    routes
}

/// Build the Prime API router.
///
/// All routes are nested under `/api/v1/prime` by the caller.
pub fn prime_router() -> Router<Arc<PrimeState>> {
    prime_routes()
        .into_iter()
        .fold(Router::new(), |router, r| router.route(r.path, r.handler))
}

/// OpenAPI 3.1 document for every route in [`prime_routes`], with paths
/// prefixed by `/api/v1/prime`.
pub fn openapi_document() -> Value {
    let mut paths = serde_json::Map::new();
    for r in prime_routes() {
        let parameters: Vec<Value> = r
            .path
            .split('/')
            .filter_map(|seg| seg.strip_prefix('{').and_then(|p| p.strip_suffix('}')))
            .map(|name| {
                json!({"name": name, "in": "path", "required": true, "schema": {"type": "string"}})
            })
            .collect();
        let mut op = json!({
            "summary": r.summary,
            "operationId": format!("{}{}", r.method, r.path.replace(['/', '{', '}', '.'], "_")),
            "responses": {
                r.success.to_string(): {"description": "Success", "content": {"application/json": {"schema": {"type": "object"}}}},
                "400": {"description": "Invalid request or refused write; a typed refusal carries `violation` {type_name, field, expected, received}"}
            }
        });
        if !parameters.is_empty() {
            op["parameters"] = Value::Array(parameters);
        }
        if let Some(schema) = r.request {
            op["requestBody"] =
                json!({"required": true, "content": {"application/json": {"schema": schema}}});
        }
        let entry = paths
            .entry(format!("/api/v1/prime{}", r.path))
            .or_insert_with(|| json!({}));
        entry[r.method] = op;
    }
    json!({
        "openapi": "3.1.0",
        "info": {"title": "AllSource Prime API", "version": env!("CARGO_PKG_VERSION")},
        "paths": paths
    })
}

async fn openapi_json() -> impl IntoResponse {
    Json(openapi_document())
}

/// Client-error body for a refused write, with the structured violation
/// when the refusal came from a typed kind.
fn refusal_body(e: &PrimeError) -> Json<Value> {
    match e {
        PrimeError::SchemaViolation(v) => Json(json!({"error": e.to_string(), "violation": v})),
        _ => Json(json!({"error": e.to_string()})),
    }
}

fn write_error(e: &PrimeError) -> (StatusCode, Json<Value>) {
    let status = match e {
        PrimeError::NodeNotFound(_) | PrimeError::EdgeNotFound(_) => StatusCode::NOT_FOUND,
        PrimeError::ValidationFailed(_) | PrimeError::SchemaViolation(_) => StatusCode::BAD_REQUEST,
        _ => StatusCode::INTERNAL_SERVER_ERROR,
    };
    (status, refusal_body(e))
}

fn assertion_of(
    input: AssertionInput,
) -> Result<Option<crate::prime::Assertion>, (StatusCode, Json<Value>)> {
    input.into_assertion().map_err(|e| write_error(&e))
}

// =============================================================================
// Request types
// =============================================================================

#[derive(Deserialize)]
struct CreateNodeReq {
    #[serde(rename = "type")]
    node_type: String,
    properties: Value,
    #[serde(flatten)]
    assertion: AssertionInput,
}

#[derive(Deserialize)]
struct UpdateNodeReq {
    properties: Value,
    #[serde(flatten)]
    assertion: AssertionInput,
}

#[derive(Deserialize)]
struct CreateEdgeReq {
    source: String,
    target: String,
    relation: String,
    properties: Option<Value>,
    weight: Option<f64>,
    #[serde(flatten)]
    assertion: AssertionInput,
}

#[derive(Deserialize)]
struct DefineTypeReq {
    type_name: String,
    kind: String,
    schema: Value,
}

#[derive(Deserialize)]
struct SetEnforcementReq {
    mode: String,
}

#[cfg(feature = "prime-vectors")]
#[derive(Deserialize)]
struct StoreVectorReq {
    id: String,
    text: Option<String>,
    vector: Vec<f32>,
    metadata: Option<Value>,
}

#[cfg(feature = "prime-vectors")]
#[derive(Deserialize)]
struct VectorSearchReq {
    vector: Vec<f32>,
    top_k: Option<usize>,
}

#[cfg(feature = "prime-vectors")]
#[derive(Deserialize)]
struct RecallReq {
    vector: Option<Vec<f32>>,
    node_type: Option<String>,
    depth: Option<usize>,
    top_k: Option<usize>,
    /// Same filter, and same security role, as `?tenant_id=` on `GET /graph`:
    /// results are restricted to nodes whose `properties.tenant_id` matches.
    /// Omitting it returns the whole store.
    tenant_id: Option<String>,
}

/// Body for `POST /projections`. `field_policies` maps a field name to one
/// of the four declarative merge policies, as a snake_case string
/// (`last_write`, `highest_priority`, `most_specific`, `merge_array`) — the
/// same wire shape the MCP tool accepts.
#[derive(Deserialize)]
struct DefineProjectionReq {
    entity_type: String,
    field_policies: std::collections::BTreeMap<String, String>,
}

// =============================================================================
// Handlers
// =============================================================================

async fn create_node(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<CreateNodeReq>,
) -> impl IntoResponse {
    let assertion = match assertion_of(req.assertion) {
        Ok(a) => a,
        Err(resp) => return resp,
    };
    match state
        .prime
        .add_node_asserted(&req.node_type, req.properties, assertion)
        .await
    {
        Ok(id) => {
            let entity_id = crate::prime::EntityId::node(&req.node_type, id.as_str()).to_wire();
            (
                StatusCode::CREATED,
                Json(json!({"node_id": id.as_str(), "entity_id": entity_id})),
            )
        }
        Err(e) => (StatusCode::BAD_REQUEST, refusal_body(&e)),
    }
}

async fn get_node(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.prime.get_node(&id) {
        Some(node) => (
            StatusCode::OK,
            Json(json!({
                "id": node.id.as_str(),
                "type": node.node_type,
                "properties": node.properties,
                "domain": node.domain,
                "created_at": node.created_at.to_rfc3339(),
                "updated_at": node.updated_at.to_rfc3339(),
            })),
        ),
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": format!("node not found: {id}")})),
        ),
    }
}

async fn update_node(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
    Json(req): Json<UpdateNodeReq>,
) -> impl IntoResponse {
    let assertion = match assertion_of(req.assertion) {
        Ok(a) => a,
        Err(resp) => return resp,
    };
    match state
        .prime
        .update_node_asserted(&id, req.properties, assertion)
        .await
    {
        Ok(()) => (StatusCode::OK, Json(json!({"updated": true}))),
        Err(e) => write_error(&e),
    }
}

async fn delete_node(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.prime.delete_node(&id).await {
        Ok(()) => (StatusCode::OK, Json(json!({"deleted": true}))),
        Err(e) => (StatusCode::NOT_FOUND, Json(json!({"error": e.to_string()}))),
    }
}

async fn get_neighbors(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let nodes = state.prime.neighbors(&id, None, Direction::Both);
    let nodes_json: Vec<Value> = nodes
        .iter()
        .map(|n| json!({"id": n.id.as_str(), "type": n.node_type, "properties": n.properties}))
        .collect();
    Json(json!({"nodes": nodes_json}))
}

async fn get_history(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.prime.history(&id).await {
        Ok(entries) => {
            let events: Vec<Value> = entries
                .iter()
                .map(|e| {
                    json!({
                        "type": e.event_type,
                        "timestamp": e.timestamp.to_rfc3339(),
                        "payload": e.payload
                    })
                })
                .collect();
            (StatusCode::OK, Json(json!({"events": events})))
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({"error": e.to_string()})),
        ),
    }
}

async fn create_edge(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<CreateEdgeReq>,
) -> impl IntoResponse {
    let assertion = match assertion_of(req.assertion) {
        Ok(a) => a,
        Err(resp) => return resp,
    };
    let result = state
        .prime
        .add_edge_asserted(
            &req.source,
            &req.target,
            &req.relation,
            req.weight,
            req.properties,
            assertion,
        )
        .await;
    match result {
        Ok(id) => (StatusCode::CREATED, Json(json!({"edge_id": id.as_str()}))),
        Err(e) => (StatusCode::BAD_REQUEST, refusal_body(&e)),
    }
}

fn kind_json(e: &SchemaEntry) -> Value {
    json!({
        "type_name": e.type_name,
        "kind": e.kind.as_str(),
        "version": e.version,
        "schema": e.schema,
    })
}

async fn define_type(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<DefineTypeReq>,
) -> impl IntoResponse {
    let Some(kind) = SchemaKind::parse(&req.kind) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(
                json!({"error": format!("kind: expected node or edge, received {}", json!(req.kind))}),
            ),
        );
    };
    match state
        .prime
        .register_kind(kind, &req.type_name, req.schema)
        .await
    {
        Ok(entry) => (StatusCode::CREATED, Json(kind_json(&entry))),
        Err(e) if e.to_string().contains("re-registration refused") => {
            (StatusCode::CONFLICT, refusal_body(&e))
        }
        Err(e) => write_error(&e),
    }
}

async fn list_types(State(state): State<Arc<PrimeState>>) -> impl IntoResponse {
    let types: Vec<Value> = state.prime.schemas().iter().map(kind_json).collect();
    Json(json!({"total": types.len(), "types": types}))
}

async fn set_enforcement(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<SetEnforcementReq>,
) -> impl IntoResponse {
    let Some(mode) = EnforcementMode::parse(&req.mode) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(
                json!({"error": format!("mode: expected open, warn or strict, received {}", json!(req.mode))}),
            ),
        );
    };
    match state.prime.set_enforcement(mode).await {
        Ok(()) => (StatusCode::OK, Json(json!({"mode": mode.as_str()}))),
        Err(e) => write_error(&e),
    }
}

async fn get_enforcement(State(state): State<Arc<PrimeState>>) -> impl IntoResponse {
    Json(json!({"mode": state.prime.enforcement().as_str()}))
}

async fn delete_edge_handler(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.prime.delete_edge(&id).await {
        Ok(()) => (StatusCode::OK, Json(json!({"deleted": true}))),
        Err(e) => (StatusCode::NOT_FOUND, Json(json!({"error": e.to_string()}))),
    }
}

#[cfg(feature = "prime-vectors")]
async fn store_vector(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<StoreVectorReq>,
) -> impl IntoResponse {
    match state
        .prime
        .embed_with_metadata(&req.id, req.text.as_deref(), req.vector, req.metadata)
        .await
    {
        Ok(()) => (
            StatusCode::CREATED,
            Json(json!({"stored": true, "id": req.id})),
        ),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": e.to_string()})),
        ),
    }
}

#[cfg(feature = "prime-vectors")]
async fn search_vectors(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<VectorSearchReq>,
) -> impl IntoResponse {
    let results = state
        .prime
        .vector_search(&req.vector, req.top_k.unwrap_or(10));
    let results_json: Vec<Value> = results
        .iter()
        .map(|r| json!({"id": r.id, "score": r.score, "text": r.text}))
        .collect();
    Json(json!({"results": results_json}))
}

#[cfg(feature = "prime-vectors")]
async fn delete_vector(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.prime.delete_vector(&id).await {
        Ok(()) => (StatusCode::OK, Json(json!({"deleted": true}))),
        Err(e) => (StatusCode::NOT_FOUND, Json(json!({"error": e.to_string()}))),
    }
}

#[cfg(feature = "prime-vectors")]
async fn recall(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<RecallReq>,
) -> impl IntoResponse {
    use crate::prime::types::RecallQuery;

    let query = RecallQuery {
        vector: req.vector,
        node_type: req.node_type,
        tenant: req.tenant_id,
        depth: req.depth.unwrap_or(1),
        top_k: req.top_k.unwrap_or(10),
        ..RecallQuery::default()
    };

    match state.prime.recall(query).await {
        Ok(result) => {
            let nodes: Vec<Value> = result
                .nodes
                .iter()
                .map(|sn| {
                    json!({
                        "id": sn.node.id.as_str(),
                        "type": sn.node.node_type,
                        "properties": sn.node.properties,
                        "score": sn.score,
                        "depth": sn.depth,
                    })
                })
                .collect();
            (StatusCode::OK, Json(json!({"nodes": nodes})))
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({"error": e.to_string()})),
        ),
    }
}

// =============================================================================
// Declarative projections + provenance
// =============================================================================

/// Parse a node entity_id of the form `node:{type}:{id}` and return the
/// type segment. Mirrors `entity_type_from_node_id` in the MCP layer.
fn entity_type_from_node_id(node_id: &str) -> Option<&str> {
    let mut parts = node_id.splitn(3, ':');
    if parts.next()? != "node" {
        return None;
    }
    let entity_type = parts.next()?;
    parts.next()?; // id segment must exist
    Some(entity_type)
}

/// Load the latest projection definition for `entity_type` by replaying the
/// `prime.projection.defined` event stream. Core keeps no in-memory registry
/// (unlike the MCP process); the durable event log is the source of truth.
async fn load_def(
    state: &Arc<PrimeState>,
    entity_type: &str,
) -> Result<Option<crate::prime::projections::declarative::ProjectionDef>, String> {
    let defs = state
        .prime
        .load_projection_defs()
        .await
        .map_err(|e| e.to_string())?;
    Ok(defs.into_iter().find(|d| d.entity_type == entity_type))
}

async fn define_projection(
    State(state): State<Arc<PrimeState>>,
    Json(req): Json<DefineProjectionReq>,
) -> impl IntoResponse {
    use crate::prime::projections::declarative::{MergePolicy, ProjectionDef};

    let mut field_policies = std::collections::BTreeMap::new();
    for (field, policy_str) in &req.field_policies {
        match serde_json::from_value::<MergePolicy>(json!(policy_str)) {
            Ok(p) => {
                field_policies.insert(field.clone(), p);
            }
            Err(_) => {
                return (
                    StatusCode::BAD_REQUEST,
                    Json(json!({"error": format!(
                        "field_policies.{field}: unknown policy '{policy_str}' — valid: last_write, highest_priority, most_specific, merge_array"
                    )})),
                );
            }
        }
    }

    let def = ProjectionDef {
        entity_type: req.entity_type.clone(),
        field_policies,
    };

    match state.prime.define_projection(&def).await {
        Ok(()) => (
            StatusCode::CREATED,
            Json(json!({"entity_type": req.entity_type, "persisted": true})),
        ),
        Err(e) => (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": e.to_string()})),
        ),
    }
}

async fn list_projections(State(state): State<Arc<PrimeState>>) -> impl IntoResponse {
    match state.prime.load_projection_defs().await {
        Ok(defs) => {
            let projections: Vec<Value> = defs
                .iter()
                .map(|d| {
                    let policies: serde_json::Map<String, Value> = d
                        .field_policies
                        .iter()
                        .map(|(field, policy)| {
                            (
                                field.clone(),
                                serde_json::to_value(policy).unwrap_or(Value::Null),
                            )
                        })
                        .collect();
                    json!({"entity_type": d.entity_type, "field_policies": policies})
                })
                .collect();
            (
                StatusCode::OK,
                Json(json!({"projections": projections, "total": defs.len()})),
            )
        }
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({"error": e.to_string()})),
        ),
    }
}

async fn project_node(
    State(state): State<Arc<PrimeState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    use crate::prime::projections::declarative::fold;

    let Some(entity_type) = entity_type_from_node_id(&id) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": format!("node_id must be 'node:{{type}}:{{id}}', got: {id}")})),
        );
    };
    let def = match load_def(&state, entity_type).await {
        Ok(Some(d)) => d,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({"error": format!(
                    "no projection defined for entity_type '{entity_type}' — POST /projections first"
                )})),
            );
        }
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e}))),
    };
    let observations = match state.prime.observations(&id).await {
        Ok(o) => o,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": format!("failed to load observations: {e}")})),
            );
        }
    };
    let snapshot = fold(&observations, &def);
    (
        StatusCode::OK,
        Json(json!({
            "entity_type": snapshot.entity_type,
            "fields": snapshot.fields,
            "observation_count": observations.len(),
        })),
    )
}

async fn field_provenance(
    State(state): State<Arc<PrimeState>>,
    Path((id, field)): Path<(String, String)>,
) -> impl IntoResponse {
    use crate::prime::projections::declarative::{
        MergePolicy, ProjectionDef, provenance_for_field,
    };

    let Some(entity_type) = entity_type_from_node_id(&id) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": format!("node_id must be 'node:{{type}}:{{id}}', got: {id}")})),
        );
    };
    // A field outside any registered projection is answered under
    // `last_write`, matching prime-mcp's route of the same path.
    let (def, policy_source) = match load_def(&state, entity_type).await {
        Ok(Some(d)) if d.field_policies.contains_key(&field) => (d, "projection"),
        Ok(_) => (
            ProjectionDef::new(entity_type, [(field.clone(), MergePolicy::LastWrite)]),
            "default",
        ),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e}))),
    };
    let observations = match state.prime.observations(&id).await {
        Ok(o) => o,
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": format!("failed to load observations: {e}")})),
            );
        }
    };
    match provenance_for_field(&observations, &def, &field) {
        Some(p) => (
            StatusCode::OK,
            Json(json!({
                "field": p.field,
                "value": p.value,
                "source_event_id": p.source_event_id,
                "source_event_at": p.source_event_at,
                "merge_policy_applied": p.merge_policy_applied,
                "policy_source": policy_source,
                "source_priority": p.source_priority,
                "assertion": p.assertion,
                "contributors": p.contributors,
            })),
        ),
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": format!(
                "no provenance for field '{field}' on {id}: no observation sets it"
            )})),
        ),
    }
}

/// Query parameters for `GET /graph`.
#[derive(Deserialize)]
struct GraphQuery {
    /// Tenant filter. See the security note on [`get_full_graph`]. When set,
    /// only nodes whose `properties.tenant_id` matches are returned.
    tenant_id: Option<String>,
    /// Filter to a single `node_type`.
    node_type: Option<String>,
    /// Cap the node count (post-filter). Sets `has_more=true` when it truncates.
    limit: Option<usize>,
}

/// `GET /api/v1/prime/graph` — return the COMPLETE materialized knowledge
/// graph from storage: every live node (full properties + vector presence),
/// every live edge (relation + properties), and summary stats. Reads the
/// `node_state` + `adjacency` projections directly — NOT an events-window
/// reconstruction — so "all details from storage" is real and uncapped.
///
/// # JSON contract (stable — visualizers and downstream beads 013/014 depend
/// on this shape verbatim)
///
/// ```json
/// {
///   "nodes": [
///     {
///       "id": "node:organization:<uuid>",
///       "node_type": "organization",
///       "properties": { "...": "full node property bag" },
///       "has_vector": true,
///       "vector_dim": 384,
///       "created_at": "2026-01-01T00:00:00Z",
///       "updated_at": "2026-01-01T00:00:00Z"
///     }
///   ],
///   "edges": [
///     {
///       "source": "node:contact:<uuid>",
///       "target": "node:organization:<uuid>",
///       "relation": "works_at",
///       "properties": { "...": "full edge property bag, may be null" },
///       "weight": null,
///       "created_at": "2026-01-01T00:00:00Z"
///     }
///   ],
///   "stats": {
///     "node_count": 46,
///     "edge_count": 31,
///     "vector_count": 12,
///     "nodes_by_type": { "organization": 22, "contact": 24 }
///   },
///   "has_more": false
/// }
/// ```
///
/// Vectors report PRESENCE + DIMENSION only (`has_vector`, `vector_dim`);
/// raw float arrays are never returned (payload bloat). A future
/// `?include_vectors=true` could opt into raw arrays at a known cost.
///
/// Query params: `?tenant_id=` (tenant filter — security), `?node_type=`
/// (type filter), `?limit=` (node cap; default = whole graph, sets
/// `has_more`).
///
/// # Tenant scoping (SECURITY)
///
/// Prime is a single-store engine — projections are keyed by `entity_id`
/// only, never by tenant. There is one graph per process. When `tenant_id`
/// is supplied, results are filtered to nodes carrying a matching
/// `properties.tenant_id`, and edges are restricted to that node set, so one
/// tenant can never read another's nodes through this endpoint even though
/// they share a store. Omitting `tenant_id` (local prime-mcp / one-Prime-per-
/// tenant deployments) returns the whole graph.
async fn get_full_graph(
    State(state): State<Arc<PrimeState>>,
    Query(q): Query<GraphQuery>,
) -> impl IntoResponse {
    let graph = state
        .prime
        .full_graph(q.tenant_id.as_deref(), q.node_type.as_deref(), q.limit);
    (
        StatusCode::OK,
        Json(serde_json::to_value(&graph).unwrap_or(Value::Null)),
    )
}

async fn get_stats(State(state): State<Arc<PrimeState>>) -> impl IntoResponse {
    let stats = state.prime.stats();
    Json(json!({
        "total_nodes": stats.total_nodes,
        "total_edges": stats.total_edges,
        "deleted_nodes": stats.deleted_nodes,
        "deleted_edges": stats.deleted_edges,
        "event_count": stats.event_count,
        "nodes_by_type": stats.nodes_by_type,
        "edges_by_relation": stats.edges_by_relation,
    }))
}

// =============================================================================
// Tests — exercise the REST routes end-to-end through the real router, proving
// SDK/REST callers reach the same projection + provenance primitives the MCP
// tools expose (bead t-2ac8 acceptance: REST returns what the MCP path does).
// =============================================================================
#[cfg(test)]
#[path = "prime_api_contract_tests.rs"]
mod contract_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prime::{EntityId, Prime};
    use axum::{
        body::{Body, to_bytes},
        http::Request,
    };
    use tower::ServiceExt; // for `oneshot`

    async fn test_app() -> (Router, Arc<PrimeState>) {
        let prime = Prime::open_in_memory().await.unwrap();
        let state = Arc::new(PrimeState { prime });
        (prime_router().with_state(state.clone()), state)
    }

    async fn send(
        app: &Router,
        method: &str,
        uri: &str,
        body: Option<Value>,
    ) -> (StatusCode, Value) {
        let builder = Request::builder().method(method).uri(uri);
        let req = match body {
            Some(b) => builder
                .header("content-type", "application/json")
                .body(Body::from(b.to_string()))
                .unwrap(),
            None => builder.body(Body::empty()).unwrap(),
        };
        let resp = app.clone().oneshot(req).await.unwrap();
        let status = resp.status();
        let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
        let json: Value = if bytes.is_empty() {
            Value::Null
        } else {
            serde_json::from_slice(&bytes).unwrap()
        };
        (status, json)
    }

    #[tokio::test]
    async fn define_list_project_and_provenance_roundtrip() {
        let (app, state) = test_app().await;

        // Define a projection for entity_type "contact".
        let (status, _) = send(
            &app,
            "POST",
            "/projections",
            Some(json!({
                "entity_type": "contact",
                "field_policies": { "status": "last_write", "tags": "merge_array" }
            })),
        )
        .await;
        assert_eq!(status, StatusCode::CREATED);

        // It shows up in the list (replayed from the durable event log).
        let (status, body) = send(&app, "GET", "/projections", None).await;
        assert_eq!(status, StatusCode::OK);
        let listed = body["projections"].as_array().unwrap();
        assert!(listed.iter().any(|p| p["entity_type"] == "contact"));
        assert_eq!(
            body["projections"][0]["field_policies"]["status"],
            "last_write"
        );

        // Seed a node (one observation) so project/provenance have something.
        let node_id = state
            .prime
            .add_node("contact", json!({ "status": "active", "tags": ["a"] }))
            .await
            .unwrap();
        let entity_id = EntityId::node("contact", node_id.as_str()).to_wire();

        // Project the node through the REST route.
        let (status, body) = send(&app, "POST", &format!("/nodes/{entity_id}/project"), None).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["entity_type"], "contact");
        assert_eq!(body["fields"]["status"], "active");
        assert_eq!(body["observation_count"], 1);

        // Per-field provenance for a single-source field.
        let (status, body) = send(
            &app,
            "GET",
            &format!("/nodes/{entity_id}/fields/status/provenance"),
            None,
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["value"], "active");
        assert_eq!(body["merge_policy_applied"], "last_write");
        assert!(
            body["source_event_id"]
                .as_str()
                .is_some_and(|s| !s.is_empty())
        );

        let (status, body) = send(
            &app,
            "GET",
            &format!("/nodes/{entity_id}/fields/tags/provenance"),
            None,
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["contributors"].as_array().map(Vec::len), Some(1));
    }

    #[tokio::test]
    async fn project_unknown_entity_type_is_404() {
        let (app, _state) = test_app().await;
        let (status, _) = send(&app, "POST", "/nodes/node:ghost:1/project", None).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn define_rejects_unknown_policy() {
        let (app, _state) = test_app().await;
        let (status, body) = send(
            &app,
            "POST",
            "/projections",
            Some(json!({ "entity_type": "x", "field_policies": { "f": "nonsense" } })),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(body["error"].as_str().unwrap().contains("unknown policy"));
    }

    #[tokio::test]
    async fn malformed_node_id_is_400() {
        let (app, _state) = test_app().await;
        let (status, _) = send(&app, "POST", "/nodes/not-a-node-id/project", None).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    // -- Full-graph endpoint -------------------------------------------------

    /// Seed a node tagged with a tenant and return its wire entity_id.
    async fn seed_tenant_node(
        state: &Arc<PrimeState>,
        tenant: &str,
        node_type: &str,
        name: &str,
    ) -> String {
        let id = state
            .prime
            .add_node(node_type, json!({ "name": name, "tenant_id": tenant }))
            .await
            .unwrap();
        EntityId::node(node_type, id.as_str()).to_wire()
    }

    #[tokio::test]
    async fn full_graph_returns_nodes_edges_and_stats() {
        let (app, state) = test_app().await;

        let org = seed_tenant_node(&state, "t1", "organization", "Acme").await;
        let contact = seed_tenant_node(&state, "t1", "contact", "Alice").await;
        state
            .prime
            .add_edge(&contact, &org, "works_at", Some(json!({ "since": "2026" })))
            .await
            .unwrap();

        let (status, body) = send(&app, "GET", "/graph", None).await;
        assert_eq!(status, StatusCode::OK);

        let nodes = body["nodes"].as_array().unwrap();
        assert_eq!(nodes.len(), 2);
        // Full properties present, vector presence reported.
        let org_node = nodes.iter().find(|n| n["id"] == org).unwrap();
        assert_eq!(org_node["node_type"], "organization");
        assert_eq!(org_node["properties"]["name"], "Acme");
        assert_eq!(org_node["has_vector"], false);
        assert!(org_node["created_at"].is_string());

        let edges = body["edges"].as_array().unwrap();
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0]["source"], contact);
        assert_eq!(edges[0]["target"], org);
        assert_eq!(edges[0]["relation"], "works_at");

        assert_eq!(body["stats"]["node_count"], 2);
        assert_eq!(body["stats"]["edge_count"], 1);
        assert_eq!(body["stats"]["nodes_by_type"]["organization"], 1);
        assert_eq!(body["stats"]["nodes_by_type"]["contact"], 1);
        assert_eq!(body["has_more"], false);
    }

    /// The same isolation guarantee `full_graph_is_tenant_isolated` pins, on
    /// the other read that can return nodes. `/graph` grew its `tenant_id`
    /// filter first and `/recall` did not have one, which on a shared store
    /// meant a caller scoped out of another tenant's graph could still recall
    /// its nodes.
    #[cfg(feature = "prime-vectors")]
    #[tokio::test]
    async fn recall_is_tenant_isolated() {
        let (app, state) = test_app().await;

        let a = seed_tenant_node(&state, "tenant-a", "contact", "Ann").await;
        let b = seed_tenant_node(&state, "tenant-b", "contact", "Bob").await;
        state
            .prime
            .embed(&a, Some("Ann"), vec![1.0, 0.0, 0.0, 0.0])
            .await
            .unwrap();
        state
            .prime
            .embed(&b, Some("Bob"), vec![1.0, 0.0, 0.0, 0.0])
            .await
            .unwrap();

        let scoped = json!({"vector": [1.0, 0.0, 0.0, 0.0], "top_k": 10, "tenant_id": "tenant-a"});
        let (status, body) = send(&app, "POST", "/recall", Some(scoped)).await;
        assert_eq!(status, StatusCode::OK);
        let nodes = body["nodes"].as_array().expect("nodes array");
        assert!(!nodes.is_empty(), "tenant A must still recall its own node");
        for n in nodes {
            assert_eq!(n["properties"]["tenant_id"], "tenant-a");
        }

        let unscoped = json!({"vector": [1.0, 0.0, 0.0, 0.0], "top_k": 10});
        let (_, body) = send(&app, "POST", "/recall", Some(unscoped)).await;
        assert!(
            body["nodes"].as_array().expect("nodes array").len() > nodes.len(),
            "the unscoped query must see more, or the scoped one proved nothing"
        );
    }

    /// MANDATORY tenant-isolation test: two tenants share the single Prime
    /// store; tenant A's `?tenant_id=` request must return ONLY tenant A's
    /// graph — tenant B's nodes and the cross-set edge must be absent.
    #[tokio::test]
    async fn full_graph_is_tenant_isolated() {
        let (app, state) = test_app().await;

        // Tenant A: org + contact + edge.
        let a_org = seed_tenant_node(&state, "tenant-a", "organization", "AlphaCorp").await;
        let a_contact = seed_tenant_node(&state, "tenant-a", "contact", "Ann").await;
        state
            .prime
            .add_edge(&a_contact, &a_org, "works_at", None)
            .await
            .unwrap();

        // Tenant B: org + contact + edge.
        let b_org = seed_tenant_node(&state, "tenant-b", "organization", "BetaCorp").await;
        let b_contact = seed_tenant_node(&state, "tenant-b", "contact", "Bob").await;
        state
            .prime
            .add_edge(&b_contact, &b_org, "works_at", None)
            .await
            .unwrap();

        // Tenant A's view: only A's two nodes and A's one edge.
        let (status, body) = send(&app, "GET", "/graph?tenant_id=tenant-a", None).await;
        assert_eq!(status, StatusCode::OK);

        let ids: Vec<&str> = body["nodes"]
            .as_array()
            .unwrap()
            .iter()
            .map(|n| n["id"].as_str().unwrap())
            .collect();
        assert_eq!(ids.len(), 2, "tenant A must see exactly its 2 nodes");
        assert!(ids.contains(&a_org.as_str()));
        assert!(ids.contains(&a_contact.as_str()));
        // Cross-tenant leak guard: B's nodes MUST be absent.
        assert!(
            !ids.contains(&b_org.as_str()),
            "tenant B org leaked to tenant A"
        );
        assert!(
            !ids.contains(&b_contact.as_str()),
            "tenant B contact leaked to tenant A"
        );

        let edges = body["edges"].as_array().unwrap();
        assert_eq!(edges.len(), 1, "tenant A must see only its own edge");
        assert_eq!(edges[0]["source"], a_contact);
        assert_eq!(edges[0]["target"], a_org);

        assert_eq!(body["stats"]["node_count"], 2);
        assert_eq!(body["stats"]["edge_count"], 1);

        // Sanity: the unscoped view sees all four nodes (single store).
        let (_, all) = send(&app, "GET", "/graph", None).await;
        assert_eq!(all["nodes"].as_array().unwrap().len(), 4);
    }

    #[tokio::test]
    async fn full_graph_limit_sets_has_more_and_filters_edges() {
        let (app, state) = test_app().await;
        let a = seed_tenant_node(&state, "t", "thing", "a").await;
        let b = seed_tenant_node(&state, "t", "thing", "b").await;
        let c = seed_tenant_node(&state, "t", "thing", "c").await;
        // Edge a->b and a->c; with limit=1 at most one node survives so edges drop.
        state.prime.add_edge(&a, &b, "rel", None).await.unwrap();
        state.prime.add_edge(&a, &c, "rel", None).await.unwrap();

        let (status, body) = send(&app, "GET", "/graph?limit=1", None).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["nodes"].as_array().unwrap().len(), 1);
        assert_eq!(body["has_more"], true);
        // edge_count counts only edges among returned nodes.
        assert_eq!(body["stats"]["edge_count"], 0);
    }

    #[tokio::test]
    async fn full_graph_node_type_filter() {
        let (app, state) = test_app().await;
        seed_tenant_node(&state, "t", "organization", "Org").await;
        seed_tenant_node(&state, "t", "contact", "C").await;

        let (status, body) = send(&app, "GET", "/graph?node_type=organization", None).await;
        assert_eq!(status, StatusCode::OK);
        let nodes = body["nodes"].as_array().unwrap();
        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0]["node_type"], "organization");
    }
}