topodb-json 0.1.0

JSON conversion layer for the TopoDB agent-memory engine
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
//! Graph snapshot: the one struct every `topodb graph` output format renders.
//! Deterministic by construction — no wall-clock fields, sorted collections.

use serde::{Deserialize, Serialize};
use topodb::{EdgeRecord, NodeRecord, PropValue, SmolStr};

use crate::{
    scope_label, ENTITY_LABEL, ENTITY_NAME_PROP, MEMORY_CONTENT_PROP, MEMORY_TOMBSTONE_PROPS,
};

pub const GRAPH_SNAPSHOT_VERSION: u32 = 1;
pub const GRAPH_DEFAULT_LIMIT: usize = 500;
pub const GRAPH_TITLE_MAX_CHARS: usize = 120;
pub const GRAPH_MERMAID_INLINE_MAX_NODES: usize = 60;

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GraphSnapshot {
    pub snapshot_version: u32,
    pub db_path: Option<String>,
    pub op_seq: u64,
    pub scopes: Vec<String>,
    pub view: GraphView,
    pub truncated: Option<GraphTruncation>,
    pub nodes: Vec<GraphNode>,
    pub edges: Vec<GraphEdge>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GraphView {
    pub kind: String,
    pub seeds: Vec<String>,
    pub query: Option<String>,
    pub hops: u8,
    pub as_of: Option<i64>,
    pub time_axis: String,
    pub direction: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GraphTruncation {
    pub nodes_dropped: usize,
    pub edges_dropped: usize,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GraphNode {
    pub id: String,
    pub label: String,
    pub title: String,
    pub scope: String,
    pub superseded: bool,
    pub hop: u32,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct GraphEdge {
    pub from: String,
    pub to: String,
    pub ty: String,
    pub scope: String,
    pub valid_from: i64,
    pub valid_to: Option<i64>,
}

/// Entity name, else `content` preview (≤ GRAPH_TITLE_MAX_CHARS chars,
/// char-boundary safe, '…' suffix when cut), else the label itself.
pub fn node_title(n: &NodeRecord) -> String {
    let titled = if n.label == ENTITY_LABEL {
        n.props.get(ENTITY_NAME_PROP)
    } else {
        n.props.get(MEMORY_CONTENT_PROP)
    };
    let s = match titled {
        Some(PropValue::Str(s)) => s.as_str(),
        _ => return n.label.to_string(),
    };
    // Whitespace-normalize so multi-line content stays a one-line title.
    let flat: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
    if flat.chars().count() <= GRAPH_TITLE_MAX_CHARS {
        flat
    } else {
        let mut t: String = flat.chars().take(GRAPH_TITLE_MAX_CHARS).collect();
        t.push('');
        t
    }
}

pub fn node_superseded(n: &NodeRecord) -> bool {
    MEMORY_TOMBSTONE_PROPS
        .iter()
        .any(|p| n.props.contains_key(*p))
}

pub fn graph_node(n: &NodeRecord, hop: u32) -> GraphNode {
    GraphNode {
        id: n.id.to_string(),
        label: n.label.to_string(),
        title: node_title(n),
        scope: scope_label(&n.scope),
        superseded: node_superseded(n),
        hop,
    }
}

pub fn graph_edge(e: &EdgeRecord) -> GraphEdge {
    GraphEdge {
        from: e.from.to_string(),
        to: e.to.to_string(),
        ty: e.ty.to_string(),
        scope: scope_label(&e.scope),
        valid_from: e.valid_from,
        valid_to: e.valid_to,
    }
}

pub fn to_canonical_json(s: &GraphSnapshot) -> Result<String, String> {
    serde_json::to_string(s).map_err(|e| format!("serializing snapshot: {e}"))
}

const GRAPH_HTML_TEMPLATE: &str = include_str!("../assets/graph.html");

/// Self-contained interactive HTML: the canonical JSON is embedded verbatim
/// (with `<` escaped as `\u003c` to make a literal `</script>` breakout
/// impossible) inside `assets/graph.html`, a vanilla-JS force-layout viewer.
pub fn to_html(s: &GraphSnapshot) -> Result<String, String> {
    let json = to_canonical_json(s)?;
    // `<` only ever appears inside JSON strings, so escaping it is always
    // legal JSON and guarantees no literal "</script>" can appear in the
    // embedded payload.
    let json_escaped = json.replace('<', "\\u003c");
    let title = format!("topodb graph — {} view", s.view.kind);
    Ok(GRAPH_HTML_TEMPLATE
        .replace("__PAGE_TITLE__", &title)
        .replace("__SNAPSHOT_JSON__", &json_escaped))
}

pub fn to_dot(s: &GraphSnapshot) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let _ = writeln!(out, "digraph topodb {{");
    let _ = writeln!(out, "rankdir=LR;");
    let _ = writeln!(out, "node [shape=box];");

    if let Some(t) = &s.truncated {
        let _ = writeln!(
            out,
            "label=\"truncated: {} nodes, {} edges dropped\"; labelloc=t;",
            t.nodes_dropped, t.edges_dropped
        );
    }

    // Iterate over nodes (already sorted)
    for node in &s.nodes {
        let title_escaped = escape_dot_label(&node.title);
        let label_escaped = escape_dot_label(&node.label);
        let scope_escaped = escape_dot_label(&node.scope);
        let label = if s.scopes.len() > 1 {
            format!("{}\\n{}\\n{}", label_escaped, title_escaped, scope_escaped)
        } else {
            format!("{}\\n{}", label_escaped, title_escaped)
        };

        let style = if node.superseded {
            ", style=dashed"
        } else {
            ""
        };

        let _ = writeln!(out, "\"{}\" [label=\"{}\"]{}", node.id, label, style);
    }

    // Iterate over edges (already sorted)
    for edge in &s.edges {
        let ty_escaped = escape_dot_label(&edge.ty);
        let _ = writeln!(
            out,
            "\"{}\" -> \"{}\" [label=\"{}\"]",
            edge.from, edge.to, ty_escaped
        );
    }

    let _ = writeln!(out, "}}");
    out
}

pub fn to_mermaid(s: &GraphSnapshot) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let _ = writeln!(out, "graph TD");

    // Create a mapping from node id to index
    let mut id_to_index = std::collections::BTreeMap::new();
    for (idx, node) in s.nodes.iter().enumerate() {
        id_to_index.insert(node.id.clone(), idx);
    }

    if let Some(t) = &s.truncated {
        let _ = writeln!(
            out,
            "  %% truncated: {} nodes, {} edges dropped",
            t.nodes_dropped, t.edges_dropped
        );
    }

    // Iterate over nodes (already sorted)
    let mut has_superseded = false;
    for (idx, node) in s.nodes.iter().enumerate() {
        let label_sanitized = sanitize_mermaid_label(&node.label);
        let title_sanitized = sanitize_mermaid_label(&node.title);
        let superseded_class = if node.superseded {
            has_superseded = true;
            ":::superseded"
        } else {
            ""
        };

        let _ = writeln!(
            out,
            "  n{}[\"{}: {}\"]{}",
            idx, label_sanitized, title_sanitized, superseded_class
        );
    }

    // Emit truncation node if needed
    if let Some(t) = &s.truncated {
        let trunc_text = sanitize_mermaid_label(&format!(
            "⚠ truncated: {} nodes, {} edges dropped",
            t.nodes_dropped, t.edges_dropped
        ));
        let _ = writeln!(out, "  trunc[\"{}\"]", trunc_text);
    }

    // Iterate over edges (already sorted)
    for edge in &s.edges {
        if let (Some(&from_idx), Some(&to_idx)) =
            (id_to_index.get(&edge.from), id_to_index.get(&edge.to))
        {
            let ty = edge.ty.replace(['|', '"'], "");
            let _ = writeln!(out, "  n{} -->|{}| n{}", from_idx, ty, to_idx);
        }
    }

    // Emit classDef superseded only if needed
    if has_superseded {
        let _ = writeln!(out, "classDef superseded opacity:0.45;");
    }

    out
}

fn escape_dot_label(s: &str) -> String {
    let mut result = String::new();
    for c in s.chars() {
        match c {
            '\\' => result.push_str("\\\\"),
            '"' => result.push_str("\\\""),
            '\n' => result.push_str("\\n"),
            _ => result.push(c),
        }
    }
    result
}

fn sanitize_mermaid_label(s: &str) -> String {
    let mut result = String::new();
    for c in s.chars() {
        match c {
            '"' => result.push_str("#quot;"),
            '[' => result.push('('),
            ']' => result.push(')'),
            _ => result.push(c),
        }
    }
    result
}

/// Parameters for ego snapshot building.
#[derive(Clone, Debug)]
pub struct EgoParams {
    pub seeds: Vec<topodb::NodeId>,
    pub query: Option<String>,
    pub query_k: usize,
    pub max_hops: u8,
    pub direction: topodb::Direction,
    pub edge_types: Option<Vec<SmolStr>>,
    pub as_of: Option<i64>,
    pub time_axis: topodb::TimeAxis,
}

/// Compute hop distances from seeds via undirected BFS over edges.
/// Returns a map of node id → hop distance.
fn hops_from(seeds: &[String], edges: &[GraphEdge]) -> std::collections::BTreeMap<String, u32> {
    use std::collections::{BTreeMap, HashSet, VecDeque};

    let mut hops: BTreeMap<String, u32> = BTreeMap::new();
    let mut visited: HashSet<String> = HashSet::new();
    let mut queue: VecDeque<(String, u32)> = VecDeque::new();

    // Initialize seeds with hop 0
    for seed in seeds {
        hops.insert(seed.clone(), 0);
        visited.insert(seed.clone());
        queue.push_back((seed.clone(), 0));
    }

    // Build undirected adjacency map
    let mut adjacency: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for edge in edges {
        adjacency
            .entry(edge.from.clone())
            .or_default()
            .push(edge.to.clone());
        adjacency
            .entry(edge.to.clone())
            .or_default()
            .push(edge.from.clone());
    }

    // BFS
    while let Some((node_id, hop)) = queue.pop_front() {
        if let Some(neighbors) = adjacency.get(&node_id) {
            for neighbor in neighbors {
                if !visited.contains(neighbor) {
                    visited.insert(neighbor.clone());
                    let next_hop = hop + 1;
                    hops.insert(neighbor.clone(), next_hop);
                    queue.push_back((neighbor.clone(), next_hop));
                }
            }
        }
    }

    hops
}

/// Build an ego-view snapshot from seeds and optional query.
pub fn build_ego(
    db: &topodb::Db,
    scopes: &topodb::ScopeSet,
    p: &EgoParams,
) -> Result<GraphSnapshot, String> {
    use std::collections::BTreeSet;

    // 1. Combine seeds and query results
    let mut all_seeds: BTreeSet<topodb::NodeId> = p.seeds.iter().cloned().collect();

    if let Some(query) = &p.query {
        let hits = db
            .search_text(scopes, query, p.query_k)
            .map_err(|e| format!("search_text: {e}"))?;
        for (hit, _score) in hits {
            all_seeds.insert(hit.id);
        }
    }

    if all_seeds.is_empty() {
        return Err("no seeds: pass --seed or a --query with hits".to_string());
    }

    // Convert to Vec and sort for determinism (by string representation)
    let seeds_vec: Vec<topodb::NodeId> = all_seeds.into_iter().collect();
    let seeds_str_vec: Vec<String> = seeds_vec.iter().map(|s| s.to_string()).collect();

    // 2. Build TraversalQuery and traverse
    let query = topodb::TraversalQuery {
        scopes: scopes.clone(),
        seeds: seeds_vec.clone(),
        max_hops: p.max_hops,
        edge_types: p.edge_types.clone(),
        direction: p.direction,
        as_of: p.as_of,
        time_axis: p.time_axis,
    };

    let subgraph = db.traverse(&query).map_err(|e| format!("traverse: {e}"))?;

    // 3. Convert nodes and compute hops
    let mut nodes: Vec<GraphNode> = subgraph
        .nodes
        .iter()
        .map(|n| graph_node(n, 0)) // placeholder hop, will update
        .collect();
    nodes.sort_by_key(|a| a.id.clone()); // Sort by id

    // Compute hops
    let edges_for_bfs: Vec<GraphEdge> = subgraph.edges.iter().map(graph_edge).collect();

    let hops_map = hops_from(&seeds_str_vec, &edges_for_bfs);

    for node in &mut nodes {
        node.hop = *hops_map.get(&node.id).unwrap_or(&(p.max_hops as u32));
    }

    // 4. Sort edges
    let mut edges_raw = subgraph.edges.clone();
    edges_raw.sort_by_key(|a| a.id); // Sort EdgeRecords by id first
    let mut edges: Vec<GraphEdge> = edges_raw.iter().map(graph_edge).collect();
    // Stable sort by (from, to, ty)
    edges.sort_by(|a, b| {
        a.from
            .cmp(&b.from)
            .then_with(|| a.to.cmp(&b.to))
            .then_with(|| a.ty.cmp(&b.ty))
    });

    // 5. Get op_seq and scopes
    let op_seq = db.current_seq().map_err(|e| format!("current_seq: {e}"))?;

    let scope_labels: Vec<String> = scopes.iter_scopes().map(|s| scope_label(&s)).collect();

    // 6. Direction and TimeAxis to lowercase strings
    let direction_str = match p.direction {
        topodb::Direction::Out => "out",
        topodb::Direction::In => "in",
        topodb::Direction::Both => "both",
    };

    let time_axis_str = match p.time_axis {
        topodb::TimeAxis::Valid => "valid",
        topodb::TimeAxis::Recorded => "recorded",
    };

    Ok(GraphSnapshot {
        snapshot_version: GRAPH_SNAPSHOT_VERSION,
        db_path: None,
        op_seq,
        scopes: scope_labels,
        view: GraphView {
            kind: "ego".to_string(),
            seeds: seeds_str_vec,
            query: p.query.clone(),
            hops: p.max_hops,
            as_of: p.as_of,
            time_axis: time_axis_str.to_string(),
            direction: direction_str.to_string(),
        },
        truncated: None,
        nodes,
        edges,
    })
}

/// Build a scope-view snapshot: all entities and memories in the scope,
/// truncated to `limit` (keeping newest-first by ULID, recording honest
/// dropout counts). All nodes have hop: 0. View is marked "scope" with
/// empty seeds and query.
pub fn build_scope(
    db: &topodb::Db,
    scopes: &topodb::ScopeSet,
    limit: usize,
) -> Result<GraphSnapshot, String> {
    use std::collections::{BTreeSet, HashSet};

    // 1. Collect nodes from both ENTITY_LABEL and MEMORY_LABEL (unbumped)
    let mut all_nodes = db
        .nodes_by_label_unbumped(scopes, crate::ENTITY_LABEL)
        .into_iter()
        .chain(db.nodes_by_label_unbumped(scopes, crate::MEMORY_LABEL))
        .collect::<Vec<_>>();

    // 2. Track which nodes are kept/dropped
    let nodes_dropped = if all_nodes.len() > limit {
        all_nodes.len() - limit
    } else {
        0
    };

    let mut kept_ids: BTreeSet<topodb::NodeId> = BTreeSet::new();
    let mut dropped_ids: HashSet<topodb::NodeId> = HashSet::new();

    if all_nodes.len() > limit {
        // Sort descending (newest first, ULIDs are time-ordered)
        all_nodes.sort_by_key(|n| std::cmp::Reverse(n.id));
        // Keep the limit
        let kept = all_nodes.drain(..limit).collect::<Vec<_>>();
        // Remaining are dropped
        for n in all_nodes.iter() {
            dropped_ids.insert(n.id);
        }
        for n in kept.iter() {
            kept_ids.insert(n.id);
        }
        all_nodes = kept;
    } else {
        for n in all_nodes.iter() {
            kept_ids.insert(n.id);
        }
    }

    // Re-sort kept nodes ascending for output (like build_ego does)
    all_nodes.sort_by_key(|n| n.id);

    // 3. Convert nodes and set hop to 0
    let mut nodes: Vec<GraphNode> = all_nodes.iter().map(|n| graph_node(n, 0)).collect();
    nodes.sort_by_key(|a| a.id.clone());

    // 4. Collect edges: outgoing from kept nodes
    let mut edges_dropped = 0;
    let mut all_edges: Vec<topodb::EdgeRecord> = Vec::new();

    for node_id in kept_ids.iter() {
        let edges_out = db
            .edges_from(scopes, *node_id, None, None, true, topodb::TimeAxis::Valid)
            .map_err(|e| format!("edges_from: {e}"))?;
        all_edges.extend(edges_out);
    }

    // Also check for edges pointing TO kept nodes from dropped nodes
    for node_id in kept_ids.iter() {
        let edges_in = db
            .edges_to(scopes, *node_id, None, None, true, topodb::TimeAxis::Valid)
            .map_err(|e| format!("edges_to: {e}"))?;
        for edge in edges_in {
            all_edges.push(edge);
        }
    }

    // Deduplicate edges by id to handle edges that appear in both from and to queries
    let mut seen_edges: HashSet<topodb::EdgeId> = HashSet::new();
    all_edges.retain(|e| seen_edges.insert(e.id));

    // 5. Filter edges: keep only those with both endpoints in kept_ids
    let filtered_edges: Vec<topodb::EdgeRecord> = all_edges
        .into_iter()
        .filter(|e| {
            if kept_ids.contains(&e.from) && kept_ids.contains(&e.to) {
                true // both endpoints kept: render it
            } else if kept_ids.contains(&e.from) && dropped_ids.contains(&e.to) {
                edges_dropped += 1; // kept -> dropped
                false
            } else if kept_ids.contains(&e.to) && dropped_ids.contains(&e.from) {
                edges_dropped += 1; // dropped -> kept
                false
            } else {
                false // dropped <-> dropped: not counted (documented non-exhaustive)
            }
        })
        .collect();

    // 6. Sort edges: by raw edge id first, then stable (from, to, ty)
    let mut edges_raw = filtered_edges;
    edges_raw.sort_by_key(|a| a.id);
    let mut edges: Vec<GraphEdge> = edges_raw.iter().map(graph_edge).collect();
    edges.sort_by(|a, b| {
        a.from
            .cmp(&b.from)
            .then_with(|| a.to.cmp(&b.to))
            .then_with(|| a.ty.cmp(&b.ty))
    });

    // 7. Get op_seq and scopes
    let op_seq = db.current_seq().map_err(|e| format!("current_seq: {e}"))?;
    let scope_labels: Vec<String> = scopes.iter_scopes().map(|s| scope_label(&s)).collect();

    // 8. Build truncation info (only if something was dropped)
    let truncated = if nodes_dropped > 0 || edges_dropped > 0 {
        Some(GraphTruncation {
            nodes_dropped,
            edges_dropped,
        })
    } else {
        None
    };

    Ok(GraphSnapshot {
        snapshot_version: GRAPH_SNAPSHOT_VERSION,
        db_path: None,
        op_seq,
        scopes: scope_labels,
        view: GraphView {
            kind: "scope".to_string(),
            seeds: vec![],
            query: None,
            hops: 0,
            as_of: None,
            time_axis: "valid".to_string(),
            direction: "out".to_string(),
        },
        truncated,
        nodes,
        edges,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use topodb::{EdgeId, NodeId, Op, PropValue, Scope};

    fn node(label: &str, props: Vec<(&str, PropValue)>) -> topodb::NodeRecord {
        topodb::NodeRecord {
            id: NodeId::new(),
            scope: Scope::Shared,
            label: label.into(),
            props: props.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
            embedding: None,
        }
    }

    /// a(Memory) -ABOUT-> b(Entity) -ABOUT-> c(Entity); returns (db, [a,b,c])
    fn seed_chain(dir: &tempfile::TempDir) -> (topodb::Db, [NodeId; 3]) {
        let db = topodb::Db::open_with(dir.path().join("t.redb"), crate::default_spec()).unwrap();
        let (a, b, c) = (NodeId::new(), NodeId::new(), NodeId::new());
        db.submit(vec![
            Op::CreateNode {
                id: a,
                scope: Scope::Shared,
                label: "Memory".into(),
                props: [("content".to_string(), PropValue::Str("alpha fact".into()))]
                    .into_iter()
                    .collect(),
            },
            Op::CreateNode {
                id: b,
                scope: Scope::Shared,
                label: "Entity".into(),
                props: [("name".to_string(), PropValue::Str("Beta".into()))]
                    .into_iter()
                    .collect(),
            },
            Op::CreateNode {
                id: c,
                scope: Scope::Shared,
                label: "Entity".into(),
                props: [("name".to_string(), PropValue::Str("Gamma".into()))]
                    .into_iter()
                    .collect(),
            },
            Op::CreateEdge {
                id: EdgeId::new(),
                scope: Scope::Shared,
                ty: "ABOUT".into(),
                from: a,
                to: b,
                props: Default::default(),
                valid_from: None,
                recorded_at: None,
            },
            Op::CreateEdge {
                id: EdgeId::new(),
                scope: Scope::Shared,
                ty: "ABOUT".into(),
                from: b,
                to: c,
                props: Default::default(),
                valid_from: None,
                recorded_at: None,
            },
        ])
        .unwrap();
        (db, [a, b, c])
    }

    #[test]
    fn ego_walks_hops_and_labels_them() {
        let dir = tempfile::tempdir().unwrap();
        let (db, [a, _b, c]) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let p = EgoParams {
            seeds: vec![a],
            query: None,
            query_k: 3,
            max_hops: 2,
            direction: topodb::Direction::Both,
            edge_types: None,
            as_of: None,
            time_axis: topodb::TimeAxis::Valid,
        };
        let snap = build_ego(&db, &scopes, &p).unwrap();
        assert_eq!(snap.nodes.len(), 3);
        assert_eq!(snap.edges.len(), 2);
        assert_eq!(snap.view.kind, "ego");
        let hop_of = |id: NodeId| {
            snap.nodes
                .iter()
                .find(|n| n.id == id.to_string())
                .unwrap()
                .hop
        };
        assert_eq!(hop_of(a), 0);
        assert_eq!(hop_of(c), 2);
        // determinism: sorted node ids
        let ids: Vec<_> = snap.nodes.iter().map(|n| n.id.clone()).collect();
        let mut sorted = ids.clone();
        sorted.sort();
        assert_eq!(ids, sorted);
    }

    #[test]
    fn ego_query_seeds_from_search_hits() {
        let dir = tempfile::tempdir().unwrap();
        let (db, [a, ..]) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let p = EgoParams {
            seeds: vec![],
            query: Some("alpha".into()),
            query_k: 3,
            max_hops: 1,
            direction: topodb::Direction::Both,
            edge_types: None,
            as_of: None,
            time_axis: topodb::TimeAxis::Valid,
        };
        let snap = build_ego(&db, &scopes, &p).unwrap();
        assert!(snap.nodes.iter().any(|n| n.id == a.to_string()));
        assert_eq!(snap.view.query.as_deref(), Some("alpha"));
    }

    #[test]
    fn ego_no_seeds_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let (db, _) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let p = EgoParams {
            seeds: vec![],
            query: Some("zzzznohit".into()),
            query_k: 3,
            max_hops: 1,
            direction: topodb::Direction::Both,
            edge_types: None,
            as_of: None,
            time_axis: topodb::TimeAxis::Valid,
        };
        assert!(build_ego(&db, &scopes, &p).is_err());
    }

    #[test]
    fn title_prefers_name_for_entities_and_previews_memory_content() {
        let e = node("Entity", vec![("name", PropValue::Str("Alice".into()))]);
        assert_eq!(node_title(&e), "Alice");
        let long = "x".repeat(300);
        let m = node("Memory", vec![("content", PropValue::Str(long))]);
        let t = node_title(&m);
        assert!(t.chars().count() <= GRAPH_TITLE_MAX_CHARS + 1); // +1 for the ellipsis
        assert!(t.ends_with(''));
    }

    #[test]
    fn title_truncates_on_char_boundary_not_bytes() {
        let m = node("Memory", vec![("content", PropValue::Str("é".repeat(200)))]);
        let t = node_title(&m); // must not panic on a multi-byte boundary
        assert!(t.ends_with(''));
    }

    #[test]
    fn title_falls_back_to_label_when_no_titled_prop() {
        let n = node("Widget", vec![("count", PropValue::Int(3))]);
        assert_eq!(node_title(&n), "Widget");
    }

    #[test]
    fn superseded_detects_tombstone_props() {
        let live = node("Memory", vec![("content", PropValue::Str("a".into()))]);
        assert!(!node_superseded(&live));
        let dead = node(
            "Memory",
            vec![
                ("content", PropValue::Str("a".into())),
                ("superseded_at", PropValue::DateTime(42)),
            ],
        );
        assert!(node_superseded(&dead));
        let forgotten = node(
            "Memory",
            vec![
                ("content", PropValue::Str("a".into())),
                ("forgotten_at", PropValue::DateTime(42)),
            ],
        );
        assert!(node_superseded(&forgotten));
    }

    #[test]
    fn canonical_json_is_stable_and_round_trips() {
        let snap = GraphSnapshot {
            snapshot_version: GRAPH_SNAPSHOT_VERSION,
            db_path: None,
            op_seq: 7,
            scopes: vec!["shared".into()],
            view: GraphView {
                kind: "ego".into(),
                seeds: vec!["01X".into()],
                query: None,
                hops: 2,
                as_of: None,
                time_axis: "valid".into(),
                direction: "both".into(),
            },
            truncated: None,
            nodes: vec![],
            edges: vec![],
        };
        let a = to_canonical_json(&snap).unwrap();
        let b = to_canonical_json(&snap).unwrap();
        assert_eq!(a, b);
        let back: GraphSnapshot = serde_json::from_str(&a).unwrap();
        assert_eq!(back, snap);
    }

    #[test]
    fn scope_view_includes_all_nodes_and_internal_edges() {
        let dir = tempfile::tempdir().unwrap();
        let (db, _) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let snap = build_scope(&db, &scopes, GRAPH_DEFAULT_LIMIT).unwrap();
        assert_eq!(snap.nodes.len(), 3);
        assert_eq!(snap.edges.len(), 2);
        assert_eq!(snap.view.kind, "scope");
        assert!(snap.truncated.is_none());
    }

    #[test]
    fn scope_view_truncates_honestly() {
        let dir = tempfile::tempdir().unwrap();
        let (db, [a, b, c]) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let snap = build_scope(&db, &scopes, 2).unwrap();
        assert_eq!(snap.nodes.len(), 2);
        let t = snap.truncated.expect("truncation must be recorded");
        assert_eq!(t.nodes_dropped, 1);
        let kept: std::collections::BTreeSet<String> =
            snap.nodes.iter().map(|n| n.id.clone()).collect();
        let dropped = [a, b, c]
            .iter()
            .find(|id| !kept.contains(&id.to_string()))
            .unwrap()
            .to_string();
        // chain edges: a->b, b->c. Count edges adjacent to the dropped node.
        let expected = [
            (a.to_string(), b.to_string()),
            (b.to_string(), c.to_string()),
        ]
        .iter()
        .filter(|(f, t2)| *f == dropped || *t2 == dropped)
        .count();
        assert_eq!(
            t.edges_dropped, expected,
            "each dropped-adjacent edge counted exactly once"
        );
    }

    #[test]
    fn exports_are_byte_identical_across_calls() {
        let dir = tempfile::tempdir().unwrap();
        let (db, [a, ..]) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let s1 = to_canonical_json(&build_scope(&db, &scopes, 500).unwrap()).unwrap();
        let s2 = to_canonical_json(&build_scope(&db, &scopes, 500).unwrap()).unwrap();
        assert_eq!(s1, s2);
        let p = EgoParams {
            seeds: vec![a],
            query: None,
            query_k: 3,
            max_hops: 2,
            direction: topodb::Direction::Both,
            edge_types: None,
            as_of: None,
            time_axis: topodb::TimeAxis::Valid,
        };
        let e1 = to_canonical_json(&build_ego(&db, &scopes, &p).unwrap()).unwrap();
        let e2 = to_canonical_json(&build_ego(&db, &scopes, &p).unwrap()).unwrap();
        assert_eq!(e1, e2);
    }

    #[test]
    fn scope_view_edges_are_closed_over_rendered_nodes() {
        let dir = tempfile::tempdir().unwrap();
        let (db, _) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);

        // Test with limit 2 (truncated)
        let snap = build_scope(&db, &scopes, 2).unwrap();
        let node_ids: std::collections::HashSet<_> =
            snap.nodes.iter().map(|n| n.id.clone()).collect();
        for edge in &snap.edges {
            assert!(
                node_ids.contains(&edge.from),
                "edge from {} not in rendered nodes",
                edge.from
            );
            assert!(
                node_ids.contains(&edge.to),
                "edge to {} not in rendered nodes",
                edge.to
            );
        }

        // Test with limit 500 (all nodes)
        let snap = build_scope(&db, &scopes, 500).unwrap();
        let node_ids: std::collections::HashSet<_> =
            snap.nodes.iter().map(|n| n.id.clone()).collect();
        for edge in &snap.edges {
            assert!(
                node_ids.contains(&edge.from),
                "edge from {} not in rendered nodes",
                edge.from
            );
            assert!(
                node_ids.contains(&edge.to),
                "edge to {} not in rendered nodes",
                edge.to
            );
        }
    }

    fn tiny_snap(superseded: bool, truncated: bool) -> GraphSnapshot {
        GraphSnapshot {
            snapshot_version: GRAPH_SNAPSHOT_VERSION,
            db_path: None,
            op_seq: 1,
            scopes: vec!["shared".into()],
            view: GraphView {
                kind: "scope".into(),
                seeds: vec![],
                query: None,
                hops: 0,
                as_of: None,
                time_axis: "valid".into(),
                direction: "out".into(),
            },
            truncated: truncated.then_some(GraphTruncation {
                nodes_dropped: 2,
                edges_dropped: 3,
            }),
            nodes: vec![
                GraphNode {
                    id: "01A".into(),
                    label: "Memory".into(),
                    title: "say \"hi\"".into(),
                    scope: "shared".into(),
                    superseded,
                    hop: 0,
                },
                GraphNode {
                    id: "01B".into(),
                    label: "Entity".into(),
                    title: "Bob".into(),
                    scope: "shared".into(),
                    superseded: false,
                    hop: 0,
                },
            ],
            edges: vec![GraphEdge {
                from: "01A".into(),
                to: "01B".into(),
                ty: "ABOUT".into(),
                scope: "shared".into(),
                valid_from: 1,
                valid_to: None,
            }],
        }
    }

    #[test]
    fn dot_escapes_and_marks_superseded_and_truncation() {
        let d = to_dot(&tiny_snap(true, true));
        assert!(d.starts_with("digraph topodb {"));
        assert!(d.contains("say \\\"hi\\\""));
        assert!(d.contains("style=dashed"));
        assert!(d.contains("truncated: 2 nodes, 3 edges dropped"));
        assert!(d.contains("\"01A\" -> \"01B\""));
        assert!(!d.contains("\\nshared")); // single-scope snapshot elides scope lines (DOT uses the two-char \n escape)

        // Multi-scope test: verify two-char escape sequence and single physical line
        let mut snap = tiny_snap(false, false);
        snap.scopes = vec!["shared".into(), "other".into()];
        let d = to_dot(&snap);
        assert!(d.contains("\\nshared")); // two-char escape in Rust source becomes \n in output
                                          // Verify it stays on one line (no raw newline inside label quotes)
        for line in d.lines() {
            if line.contains("01A") && line.contains("[label=") {
                assert!(
                    !line.contains("\n"),
                    "node label must stay on one physical line"
                );
            }
        }
    }

    #[test]
    fn mermaid_sanitizes_ids_and_surfaces_truncation() {
        let m = to_mermaid(&tiny_snap(false, true));
        assert!(m.starts_with("graph TD"));
        assert!(m.contains("n0[")); // sorted: 01A first
        assert!(m.contains("n0 -->|ABOUT| n1"));
        assert!(m.contains("#quot;"));
        assert!(m.contains("truncated: 2 nodes, 3 edges dropped"));
        assert!(!m.contains("01A[")); // raw ULIDs never used as mermaid ids
        assert!(m.contains("n0[\"Memory: ")); // Label: title separator

        // Test node label sanitization: label with `"` and `[` must be sanitized
        let mut snap = tiny_snap(false, false);
        snap.nodes[0].label = "Memory[bad]\"label".into();
        let m = to_mermaid(&snap);
        // Sanitized form should appear: [ → (, ] → ), " → #quot;
        assert!(
            m.contains("Memory(bad)#quot;label"),
            "sanitized label should appear in output"
        );
        // Raw form should NOT appear
        assert!(
            !m.contains("[\"bad\"label"),
            "raw label with quotes and brackets should not appear"
        );
        assert!(
            !m.contains("Memory[bad]\"label"),
            "unsanitized label should not appear"
        );
    }

    #[test]
    fn dot_and_mermaid_escape_edge_types() {
        let mut snap = tiny_snap(false, false);
        snap.edges[0].ty = "he\"llo|x".into();

        // Test dot escaping: `"` should be escaped as `\"`
        let d = to_dot(&snap);
        assert!(
            d.contains("he\\\"llo|x"),
            "dot should escape quotes in edge types"
        );

        // Test mermaid stripping: both `"` and `|` should be removed
        let m = to_mermaid(&snap);
        assert!(
            m.contains("-->|hellox|"),
            "mermaid should strip pipes and quotes from edge types"
        );
        // Verify raw form is not present
        assert!(
            !m.contains("-->|he\"llo|x|"),
            "mermaid should not contain raw quotes or pipes in edge label"
        );
    }

    #[test]
    fn mermaid_superseded_class_only_when_needed() {
        assert!(to_mermaid(&tiny_snap(true, false)).contains("classDef superseded"));
        assert!(!to_mermaid(&tiny_snap(false, false)).contains("classDef"));
    }

    #[test]
    fn html_round_trips_the_snapshot_and_is_self_contained() {
        let snap = tiny_snap(false, true);
        let html = to_html(&snap).unwrap();
        // extract the embedded JSON
        let start = html.find("<script id=\"snapshot\"").unwrap();
        let json_start = html[start..].find('>').unwrap() + start + 1;
        let json_end = html[json_start..].find("</script>").unwrap() + json_start;
        let back: GraphSnapshot = serde_json::from_str(&html[json_start..json_end]).unwrap();
        assert_eq!(back, snap);
        // zero network requests
        assert!(!html.contains("http://"));
        assert!(!html.contains("https://"));
        // markers fully substituted
        assert!(!html.contains("__SNAPSHOT_JSON__"));
        assert!(!html.contains("__PAGE_TITLE__"));
        // truncation banner text present
        assert!(html.contains("truncated"));
    }

    #[test]
    fn html_escapes_script_breakout() {
        let mut snap = tiny_snap(false, false);
        snap.nodes[0].title = "</script><script>alert(1)".into();
        let html = to_html(&snap).unwrap();
        let body_after_snapshot = &html[html.find("id=\"snapshot\"").unwrap()..];
        // the payload's literal </script> must not appear un-escaped
        assert!(!body_after_snapshot.contains("</script><script>alert"));
    }

    #[test]
    #[ignore]
    fn html_smoke_writes_to_target_for_eyeballing() {
        let dir = tempfile::tempdir().unwrap();
        let (db, [a, ..]) = seed_chain(&dir);
        let scopes = crate::scope_to_scope_set(Scope::Shared);
        let p = EgoParams {
            seeds: vec![a],
            query: None,
            query_k: 3,
            max_hops: 2,
            direction: topodb::Direction::Both,
            edge_types: None,
            as_of: None,
            time_axis: topodb::TimeAxis::Valid,
        };
        let snap = build_ego(&db, &scopes, &p).unwrap();
        let html = to_html(&snap).unwrap();
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let target = manifest_dir
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("target");
        let _ = std::fs::create_dir_all(&target);
        std::fs::write(target.join("graph-smoke.html"), html).unwrap();
    }
}