sem-core 0.6.1

Entity-level semantic diff engine. Extracts functions, classes, and methods from 20 languages via tree-sitter and diffs at the entity level.
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
use crate::model::entity::SemanticEntity;
use crate::parser::plugin::SemanticParserPlugin;
use crate::utils::hash::content_hash;

pub struct JsonParserPlugin;

impl SemanticParserPlugin for JsonParserPlugin {
    fn id(&self) -> &str {
        "json"
    }

    fn extensions(&self) -> &[&str] {
        &[".json"]
    }

    fn extract_entities(&self, content: &str, file_path: &str) -> Vec<SemanticEntity> {
        if !content.trim().starts_with('{') {
            return Vec::new();
        }
        extract_entries(content, file_path)
    }
}

struct Frame {
    content: String,
    entries: Vec<JsonEntry>,
    cursor: usize,
    line_offset: usize,
    parent_pointer: Option<String>,
    parent_entity_id: Option<String>,
}

/// Iterative walk of the JSON tree, emitting entities in DFS pre-order.
/// Frames track a cursor through their entries; encountering an
/// object-valued entry pushes both the parent frame (resumed after) and the
/// child frame (visited next), so children appear before later siblings.
fn extract_entries(content: &str, file_path: &str) -> Vec<SemanticEntity> {
    let mut entities = Vec::new();
    let root_entries = find_top_level_entries(content);
    let mut worklist: Vec<Frame> = vec![Frame {
        content: content.to_string(),
        entries: root_entries,
        cursor: 0,
        line_offset: 1,
        parent_pointer: None,
        parent_entity_id: None,
    }];

    while let Some(mut frame) = worklist.pop() {
        let lines: Vec<&str> = frame.content.lines().collect();
        let closing = find_closing_brace_line(&lines);

        while frame.cursor < frame.entries.len() {
            let i = frame.cursor;
            frame.cursor += 1;
            let entry = &frame.entries[i];
            let next_boundary = frame.entries.get(i + 1).map(|e| e.start_line).unwrap_or(closing);
            let end_line = trim_trailing_blanks(&lines, entry.start_line, next_boundary);

            let entity_content = lines[entry.start_line - 1..end_line].join("\n");
            let value_content = extract_value_content(&entity_content);

            let pointer = match &frame.parent_pointer {
                Some(pp) => format!("{pp}{}", entry.pointer),
                None => entry.pointer.clone(),
            };
            let entity_id = format!("{}::{}", file_path, pointer);
            let abs_start = frame.line_offset + entry.start_line - 1;
            let abs_end = frame.line_offset + end_line - 1;

            entities.push(SemanticEntity {
                id: entity_id.clone(),
                file_path: file_path.to_string(),
                entity_type: entry.entity_type.clone(),
                name: entry.key.clone(),
                parent_id: frame.parent_entity_id.clone(),
                content_hash: content_hash(&entity_content),
                structural_hash: Some(content_hash(value_content)),
                content: entity_content.clone(),
                start_line: abs_start,
                end_line: abs_end,
                metadata: None,
            });

            if entry.entity_type == "object" {
                if let Some(obj_str) = extract_object_value(&entity_content) {
                    let obj_line_in_entity = find_value_start_line(&entity_content);
                    let child = Frame {
                        content: obj_str.to_string(),
                        entries: find_top_level_entries(obj_str),
                        cursor: 0,
                        line_offset: abs_start + obj_line_in_entity - 1,
                        parent_pointer: Some(pointer),
                        parent_entity_id: Some(entity_id),
                    };
                    worklist.push(frame);
                    worklist.push(child);
                    break;
                }
            }
        }
    }

    entities
}

/// Given an entity content string like `  "scripts": {\n    "build": "tsc"\n  }`,
/// return a slice that starts at the opening `{` of the value and ends at (and
/// including) the matching closing `}`.
fn extract_object_value(content: &str) -> Option<&str> {
    // Skip past the first `:` (outside strings) to find the value
    let mut in_string = false;
    let mut escape_next = false;
    let mut colon_pos: Option<usize> = None;

    for (i, ch) in content.char_indices() {
        if escape_next {
            escape_next = false;
            continue;
        }
        if ch == '\\' && in_string {
            escape_next = true;
            continue;
        }
        if ch == '"' {
            in_string = !in_string;
        }
        if ch == ':' && !in_string {
            colon_pos = Some(i);
            break;
        }
    }

    let after_colon = &content[colon_pos? + 1..];
    // Find the opening `{`
    let brace_offset = after_colon.find('{')?;
    let obj_start = colon_pos? + 1 + brace_offset;

    // Find the matching `}`. Track brace and bracket depth separately so
    // that a `}` only terminates extraction when no array is still open.
    let mut brace_depth = 0usize;
    let mut bracket_depth = 0usize;
    in_string = false;
    escape_next = false;

    for (i, ch) in content[obj_start..].char_indices() {
        if escape_next {
            escape_next = false;
            continue;
        }
        if ch == '\\' && in_string {
            escape_next = true;
            continue;
        }
        if ch == '"' {
            in_string = !in_string;
            continue;
        }
        if !in_string {
            match ch {
                '{' => brace_depth += 1,
                '[' => bracket_depth += 1,
                '}' => {
                    brace_depth = brace_depth.saturating_sub(1);
                    if brace_depth == 0 && bracket_depth == 0 {
                        return Some(&content[obj_start..obj_start + i + 1]);
                    }
                }
                ']' => bracket_depth = bracket_depth.saturating_sub(1),
                _ => {}
            }
        }
    }
    None
}

/// Return the 1-based line number (relative to the entity content) where the
/// object value's `{` appears.
fn find_value_start_line(content: &str) -> usize {
    let mut in_string = false;
    let mut escape_next = false;
    let mut past_colon = false;
    let mut line = 1usize;

    for ch in content.chars() {
        if ch == '\n' {
            line += 1;
            continue;
        }
        if escape_next {
            escape_next = false;
            continue;
        }
        if ch == '\\' && in_string {
            escape_next = true;
            continue;
        }
        if ch == '"' {
            in_string = !in_string;
            continue;
        }
        if ch == ':' && !in_string {
            past_colon = true;
            continue;
        }
        if past_colon && ch == '{' {
            return line;
        }
    }
    1
}

struct JsonEntry {
    key: String,
    pointer: String,
    entity_type: String,
    start_line: usize, // 1-based, relative to the content passed in
}

/// Scan the source text to find each top-level key in the root JSON object.
/// Returns entries with accurate start_line positions (1-based, relative to `content`).
fn find_top_level_entries(content: &str) -> Vec<JsonEntry> {
    let mut entries = Vec::new();
    let mut depth = 0;
    let mut in_string = false;
    let mut escape_next = false;
    let mut line_num: usize = 1;

    let mut current_key: Option<String> = None;
    let mut key_start = false;
    let mut key_buf = String::new();
    let mut reading_key = false;

    for ch in content.chars() {
        if ch == '\n' {
            line_num += 1;
            continue;
        }

        if escape_next {
            if reading_key {
                key_buf.push(ch);
            }
            escape_next = false;
            continue;
        }

        if ch == '\\' && in_string {
            if reading_key {
                key_buf.push(ch);
            }
            escape_next = true;
            continue;
        }

        if in_string {
            if ch == '"' {
                in_string = false;
                if reading_key {
                    reading_key = false;
                    current_key = Some(key_buf.clone());
                    key_buf.clear();
                }
            } else if reading_key {
                key_buf.push(ch);
            }
            continue;
        }

        match ch {
            '"' => {
                in_string = true;
                if depth == 1 && current_key.is_none() && !key_start {
                    reading_key = true;
                    key_buf.clear();
                }
            }
            ':' => {
                if depth == 1 {
                    if let Some(ref key) = current_key {
                        let escaped_key = key.replace('~', "~0").replace('/', "~1");
                        let pointer = format!("/{escaped_key}");
                        entries.push(JsonEntry {
                            key: key.clone(),
                            pointer,
                            entity_type: String::new(),
                            start_line: line_num,
                        });
                        key_start = true;
                    }
                }
            }
            '{' | '[' => {
                depth += 1;
                if depth == 2 && key_start {
                    if let Some(entry) = entries.last_mut() {
                        entry.entity_type = if ch == '{' { "object" } else { "array" }.to_string();
                    }
                }
            }
            '}' | ']' => {
                depth -= 1;
            }
            ',' => {
                if depth == 1 {
                    if let Some(entry) = entries.last_mut() {
                        if entry.entity_type.is_empty() {
                            entry.entity_type = "property".to_string();
                        }
                    }
                    current_key = None;
                    key_start = false;
                }
            }
            _ => {}
        }
    }

    if let Some(entry) = entries.last_mut() {
        if entry.entity_type.is_empty() {
            entry.entity_type = "property".to_string();
        }
    }

    entries
}

/// Extract just the value portion of a `"key": value` entity content string,
/// stripping the key name so that renamed keys with identical values share the
/// same structural_hash and are detected as renames rather than delete + add.
fn extract_value_content(content: &str) -> &str {
    let mut in_string = false;
    let mut escape_next = false;
    for (i, ch) in content.char_indices() {
        if escape_next {
            escape_next = false;
            continue;
        }
        if ch == '\\' && in_string {
            escape_next = true;
            continue;
        }
        if ch == '"' {
            in_string = !in_string;
        }
        if ch == ':' && !in_string {
            let rest = content[i + 1..].trim();
            return rest.trim_end_matches(',').trim();
        }
    }
    content
}

/// Find the line number (1-based) of the closing `}` of the root object.
fn find_closing_brace_line(lines: &[&str]) -> usize {
    for (i, line) in lines.iter().enumerate().rev() {
        if line.trim() == "}" {
            return i + 1;
        }
    }
    lines.len()
}

/// Walk backwards from next_start to skip trailing blank lines and commas,
/// returning the end_line (1-based, inclusive) for the current entry.
fn trim_trailing_blanks(lines: &[&str], start: usize, next_start: usize) -> usize {
    let mut end = next_start - 1;
    while end > start {
        let trimmed = lines[end - 1].trim();
        if trimmed.is_empty() || trimmed == "," {
            end -= 1;
        } else {
            break;
        }
    }
    end
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::types::{FileChange, FileStatus};
    use crate::model::change::{ChangeType, SemanticChange};
    use crate::parser::differ::compute_semantic_diff;
    use crate::parser::registry::ParserRegistry;

    /// Run the full pipeline and drop orphan changes (which represent line-level
    /// noise outside entity spans like the root `{` `}` brackets).
    fn json_diff(before: &str, after: &str) -> Vec<SemanticChange> {
        let mut registry = ParserRegistry::new();
        registry.register(Box::new(JsonParserPlugin));
        let changes = vec![FileChange {
            file_path: "test.json".to_string(),
            status: FileStatus::Modified,
            old_file_path: None,
            before_content: Some(before.to_string()),
            after_content: Some(after.to_string()),
        }];
        compute_semantic_diff(&changes, &registry, None, None)
            .changes
            .into_iter()
            .filter(|c| c.entity_type != "orphan")
            .collect()
    }

    fn names(changes: &[SemanticChange]) -> Vec<(String, ChangeType)> {
        changes.iter().map(|c| (c.entity_name.clone(), c.change_type)).collect()
    }

    fn find_change<'a>(changes: &'a [SemanticChange], name: &str, kind: ChangeType) -> &'a SemanticChange {
        changes.iter().find(|c| c.entity_name == name && c.change_type == kind)
            .unwrap_or_else(|| panic!("expected {:?} {} in changes; got: {:?}", kind, name, names(changes)))
    }

    #[test]
    fn test_json_line_positions() {
        let content = r#"{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc",
    "test": "jest"
  },
  "description": "a test app"
}
"#;
        let plugin = JsonParserPlugin;
        let entities = plugin.extract_entities(content, "package.json");

        // Top-level entities
        let top: Vec<_> = entities.iter().filter(|e| e.parent_id.is_none()).collect();
        assert_eq!(top.len(), 4);

        assert_eq!(top[0].name, "name");
        assert_eq!(top[0].start_line, 2);
        assert_eq!(top[0].end_line, 2);

        assert_eq!(top[1].name, "version");
        assert_eq!(top[1].start_line, 3);
        assert_eq!(top[1].end_line, 3);

        assert_eq!(top[2].name, "scripts");
        assert_eq!(top[2].entity_type, "object");
        assert_eq!(top[2].start_line, 4);
        assert_eq!(top[2].end_line, 7);

        assert_eq!(top[3].name, "description");
        assert_eq!(top[3].start_line, 8);
        assert_eq!(top[3].end_line, 8);
    }

    #[test]
    fn test_nested_entities_extracted() {
        let content = r#"{
  "scripts": {
    "build": "tsc",
    "test": "jest"
  }
}
"#;
        let plugin = JsonParserPlugin;
        let entities = plugin.extract_entities(content, "package.json");

        // Should have "scripts" (top-level) + "build" and "test" (nested)
        assert_eq!(entities.len(), 3);

        let scripts = entities.iter().find(|e| e.name == "scripts").unwrap();
        assert!(scripts.parent_id.is_none());

        let build = entities.iter().find(|e| e.name == "build").unwrap();
        assert_eq!(build.parent_id, Some(scripts.id.clone()));
        assert_eq!(build.start_line, 3);

        let test = entities.iter().find(|e| e.name == "test").unwrap();
        assert_eq!(test.parent_id, Some(scripts.id.clone()));
        assert_eq!(test.start_line, 4);
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Top-level scalars
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn scalar_value_change_reports_modified() {
        let changes = json_diff(
            "{\n  \"name\": \"foo\"\n}",
            "{\n  \"name\": \"bar\"\n}",
        );
        assert_eq!(names(&changes), vec![("name".into(), ChangeType::Modified)]);
        assert_eq!(changes[0].parent_name, None);
    }

    #[test]
    fn scalar_added_to_empty_object_reports_only_the_scalar() {
        let changes = json_diff("{}", "{\n  \"name\": \"foo\"\n}");
        assert_eq!(names(&changes), vec![("name".into(), ChangeType::Added)]);
    }

    #[test]
    fn scalar_deleted_from_object_reports_only_the_scalar() {
        let changes = json_diff("{\n  \"name\": \"foo\"\n}", "{}");
        assert_eq!(names(&changes), vec![("name".into(), ChangeType::Deleted)]);
    }

    #[test]
    fn scalar_key_renamed_with_unchanged_value_reports_renamed() {
        let changes = json_diff(
            "{\n  \"timeout\": 30\n}",
            "{\n  \"testTimeout\": 30\n}",
        );
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].change_type, ChangeType::Renamed);
        assert_eq!(changes[0].entity_name, "testTimeout");
        assert_eq!(changes[0].old_entity_name.as_deref(), Some("timeout"));
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Parent suppression — object containers don't surface when children change
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn child_modified_inside_object_only_child_reported() {
        let changes = json_diff(
            "{\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}",
            "{\n  \"scripts\": {\n    \"build\": \"webpack\"\n  }\n}",
        );
        assert!(!changes.iter().any(|c| c.entity_name == "scripts"),
            "scripts should be suppressed; got: {:?}", names(&changes));
        let build = find_change(&changes, "build", ChangeType::Modified);
        assert_eq!(build.parent_name.as_deref(), Some("scripts"));
    }

    #[test]
    fn child_added_inside_object_only_child_reported() {
        let changes = json_diff(
            "{\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}",
            "{\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"test\": \"jest\"\n  }\n}",
        );
        assert!(!changes.iter().any(|c| c.entity_name == "scripts" && c.change_type == ChangeType::Modified),
            "scripts should be suppressed; got: {:?}", names(&changes));
        let test = find_change(&changes, "test", ChangeType::Added);
        assert_eq!(test.parent_name.as_deref(), Some("scripts"));
    }

    #[test]
    fn child_deleted_inside_object_only_child_reported() {
        let changes = json_diff(
            "{\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"test\": \"jest\"\n  }\n}",
            "{\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}",
        );
        assert!(!changes.iter().any(|c| c.entity_name == "scripts" && c.change_type == ChangeType::Modified),
            "scripts should be suppressed; got: {:?}", names(&changes));
        let test = find_change(&changes, "test", ChangeType::Deleted);
        assert_eq!(test.parent_name.as_deref(), Some("scripts"));
    }

    #[test]
    fn whole_object_added_only_leaf_children_reported() {
        let changes = json_diff(
            "{}",
            "{\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}",
        );
        assert!(!changes.iter().any(|c| c.entity_name == "scripts"),
            "scripts (container) should be suppressed; got: {:?}", names(&changes));
        let build = find_change(&changes, "build", ChangeType::Added);
        assert_eq!(build.parent_name.as_deref(), Some("scripts"));
    }

    #[test]
    fn whole_object_deleted_only_leaf_children_reported() {
        let changes = json_diff(
            "{\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}",
            "{}",
        );
        assert!(!changes.iter().any(|c| c.entity_name == "scripts"),
            "scripts (container) should be suppressed; got: {:?}", names(&changes));
        find_change(&changes, "build", ChangeType::Deleted);
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Deep nesting — full ancestor chain in parent_name
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn deep_nested_value_change_reports_only_the_leaf_with_full_chain() {
        let before = r#"{
  "jest": {
    "config": {
      "testTimeout": 5000
    }
  }
}"#;
        let after = r#"{
  "jest": {
    "config": {
      "testTimeout": 10000
    }
  }
}"#;
        let changes = json_diff(before, after);
        assert_eq!(names(&changes), vec![("testTimeout".into(), ChangeType::Modified)]);
        assert_eq!(changes[0].parent_name.as_deref(), Some("jest::config"));
    }

    #[test]
    fn empty_string_key_ancestor_is_skipped_in_parent_name() {
        // package-lock.json uses "" as a key for the root project.
        // Walking the parent chain for a deeply-nested change must not emit
        // the empty name (would render as "::::") in the displayed path.
        let before = r#"{
  "packages": {
    "": {
      "dependencies": {
        "jose": "^6.1.3"
      }
    }
  }
}"#;
        let after = r#"{
  "packages": {
    "": {
      "dependencies": {
        "jose": "^6.1.4"
      }
    }
  }
}"#;
        let changes = json_diff(before, after);
        let jose = find_change(&changes, "jose", ChangeType::Modified);
        // The empty-string key ancestor is dropped from the displayed chain.
        assert_eq!(jose.parent_name.as_deref(), Some("packages::dependencies"));
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Renames at the object level
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn nested_scalar_rename_with_unchanged_value() {
        // Same value → structural_hash matches → Renamed.
        let before = r#"{
  "scripts": {
    "run": "node .",
    "test": "jest"
  }
}"#;
        let after = r#"{
  "scripts": {
    "start": "node .",
    "test": "jest"
  }
}"#;
        let changes = json_diff(before, after);
        let renames: Vec<_> = changes.iter().filter(|c| c.change_type == ChangeType::Renamed).collect();
        assert_eq!(renames.len(), 1);
        assert_eq!(renames[0].entity_name, "start");
        assert_eq!(renames[0].old_entity_name.as_deref(), Some("run"));
        assert_eq!(renames[0].parent_name.as_deref(), Some("scripts"));
    }

    #[test]
    fn parent_object_renamed_unchanged_child_move_suppressed() {
        // scripts → tasks, dev unchanged: only the parent rename is reported.
        let before = "{\n  \"scripts\": {\n    \"dev\": \"vite\"\n  }\n}\n";
        let after = "{\n  \"tasks\": {\n    \"dev\": \"vite\"\n  }\n}\n";
        let changes = json_diff(before, after);
        let tasks = find_change(&changes, "tasks", ChangeType::Renamed);
        assert_eq!(tasks.old_entity_name.as_deref(), Some("scripts"));
        assert!(!changes.iter().any(|c| c.entity_name == "dev"),
            "child 'dev' should be suppressed (only moved due to parent rename); got: {:?}", names(&changes));
    }

    #[test]
    fn parent_object_renamed_and_child_renamed_only_child_surfaces() {
        // scripts → tasks AND dev → develop. Parent rename cannot be detected
        // because the renamed child key changes the parent's structural_hash.
        // The child move alone conveys the move + rename via:
        //   parent_name="tasks", old_entity_name="dev", old_parent_id=<scripts>
        let before = "{\n  \"scripts\": {\n    \"dev\": \"vite\"\n  }\n}\n";
        let after = "{\n  \"tasks\": {\n    \"develop\": \"vite\"\n  }\n}\n";
        let changes = json_diff(before, after);
        assert_eq!(names(&changes), vec![("develop".into(), ChangeType::Moved)]);
        let develop = &changes[0];
        assert_eq!(develop.old_entity_name.as_deref(), Some("dev"));
        assert_eq!(develop.parent_name.as_deref(), Some("tasks"));
        assert!(develop.old_parent_id.is_some(), "child Moved should carry old_parent_id");
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Type transitions — scalar ↔ object
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn scalar_to_object_transition_reports_modified_plus_new_children_added() {
        let changes = json_diff(
            "{\n  \"build\": \"tsc\"\n}",
            "{\n  \"build\": {\n    \"command\": \"tsc\"\n  }\n}",
        );
        let build = find_change(&changes, "build", ChangeType::Modified);
        assert_eq!(build.entity_type, "object", "after type should reflect new value");
        let command = find_change(&changes, "command", ChangeType::Added);
        assert_eq!(command.parent_name.as_deref(), Some("build"));
    }

    #[test]
    fn object_to_scalar_transition_reports_modified_plus_old_children_deleted() {
        let changes = json_diff(
            "{\n  \"config\": {\n    \"watch\": true\n  }\n}",
            "{\n  \"config\": \"auto\"\n}",
        );
        let config = find_change(&changes, "config", ChangeType::Modified);
        assert_eq!(config.entity_type, "property", "after type should reflect new value");
        find_change(&changes, "watch", ChangeType::Deleted);
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Arrays — opaque (no recursion into elements)
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn array_modified_reports_only_the_array_key() {
        let changes = json_diff(
            "{\n  \"deps\": [\"react\", \"vue\"]\n}",
            "{\n  \"deps\": [\"react\", \"vue\", \"lodash\"]\n}",
        );
        assert_eq!(names(&changes), vec![("deps".into(), ChangeType::Modified)]);
    }

    #[test]
    fn array_renamed_when_contents_unchanged() {
        let changes = json_diff(
            "{\n  \"deps\": [\"react\", \"vue\"]\n}",
            "{\n  \"dependencies\": [\"react\", \"vue\"]\n}",
        );
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].change_type, ChangeType::Renamed);
        assert_eq!(changes[0].entity_name, "dependencies");
    }

    #[test]
    fn array_element_keys_are_not_tracked_as_entities() {
        let before = r#"{
  "deps": [
    {"name": "react"},
    {"name": "vue"}
  ]
}"#;
        let after = r#"{
  "deps": [
    {"package": "react"},
    {"name": "vue"}
  ]
}"#;
        let changes = json_diff(before, after);
        assert_eq!(names(&changes), vec![("deps".into(), ChangeType::Modified)],
            "array elements have no stable identity; only the array key should change");
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Null and empty values
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn null_to_string_value_reports_modified() {
        let changes = json_diff(
            "{\n  \"key\": null\n}",
            "{\n  \"key\": \"value\"\n}",
        );
        assert_eq!(names(&changes), vec![("key".into(), ChangeType::Modified)]);
    }

    #[test]
    fn empty_object_gains_child_reports_both_parent_and_child() {
        // The precision guard keeps `key` Modified — its declaration shape
        // changed from `{}` to `{...}`.
        let changes = json_diff(
            "{\n  \"key\": {}\n}",
            "{\n  \"key\": {\n    \"build\": \"tsc\"\n  }\n}",
        );
        let key = find_change(&changes, "key", ChangeType::Modified);
        assert_eq!(key.parent_name, None);
        let build = find_change(&changes, "build", ChangeType::Added);
        assert_eq!(build.parent_name.as_deref(), Some("key"));
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Entity ID format — file::pointer (no entity_type)
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn entity_id_for_nested_property_uses_full_pointer_only() {
        let changes = json_diff(
            "{\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}",
            "{\n  \"scripts\": {\n    \"build\": \"webpack\"\n  }\n}",
        );
        let build = find_change(&changes, "build", ChangeType::Modified);
        assert_eq!(build.entity_id, "test.json::/scripts/build");
    }


    // ─────────────────────────────────────────────────────────────────────────
    //  Phase 3 fuzzy matching
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn fuzzy_rename_detected_when_value_mostly_unchanged() {
        // config → settings: key rename (Phase 1 & 2 miss).
        // testTimeout 30 → 60: small value change rules out structural_hash.
        // Many siblings unchanged → Jaccard > 0.8 → Phase 3 catches it.
        let before = r#"{
  "config": {
    "host": "localhost",
    "protocol": "https",
    "retries": 3,
    "testTimeout": 30,
    "keepalive": true,
    "compression": true,
    "logging": "verbose",
    "maxConnections": 100
  }
}"#;
        let after = r#"{
  "settings": {
    "host": "localhost",
    "protocol": "https",
    "retries": 3,
    "testTimeout": 60,
    "keepalive": true,
    "compression": true,
    "logging": "verbose",
    "maxConnections": 100
  }
}"#;
        let changes = json_diff(before, after);
        assert!(changes.iter().any(|c| c.entity_name == "settings" && c.change_type == ChangeType::Renamed),
            "expected fuzzy rename of config → settings; got: {:?}", names(&changes));
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Known limitations (documented in spec)
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn parent_rename_with_sibling_added_surfaces_leaf_moves() {
        // Parent renamed AND a new sibling appears: structural_hash diverges,
        // Phase 2 misses the parent rename. The unchanged child still matches
        // by structural_hash and surfaces as Moved; the parent Deleted/Added
        // entries are container-suppressed.
        let before = r#"{
  "scripts": {
    "build": "tsc"
  }
}"#;
        let after = r#"{
  "tasks": {
    "build": "tsc",
    "test": "jest"
  }
}"#;
        let changes = json_diff(before, after);
        let build = find_change(&changes, "build", ChangeType::Moved);
        assert_eq!(build.parent_name.as_deref(), Some("tasks"));
        assert!(build.old_parent_id.is_some());
        find_change(&changes, "test", ChangeType::Added);
        assert!(!changes.iter().any(|c| c.entity_name == "scripts" || c.entity_name == "tasks"),
            "parent Deleted/Added should be suppressed; got: {:?}", names(&changes));
    }

    #[test]
    fn scalar_array_transitions_report_modified_only() {
        // Arrays are opaque, so the type transition surfaces as a single
        // Modified entry with entity_type reflecting the after value.
        let cases = [
            ("{\n  \"deps\": \"react\"\n}", "{\n  \"deps\": [\"react\", \"vue\"]\n}", "array"),
            ("{\n  \"deps\": [\"react\", \"vue\"]\n}", "{\n  \"deps\": \"react\"\n}", "property"),
        ];
        for (before, after, after_type) in cases {
            let changes = json_diff(before, after);
            assert_eq!(names(&changes), vec![("deps".into(), ChangeType::Modified)]);
            assert_eq!(changes[0].entity_type, after_type);
        }
    }

    #[test]
    fn object_to_array_transition_reports_modified_plus_old_children_deleted() {
        let changes = json_diff(
            "{\n  \"deps\": {\n    \"react\": \"18\"\n  }\n}",
            "{\n  \"deps\": [\"react\"]\n}",
        );
        let deps = find_change(&changes, "deps", ChangeType::Modified);
        assert_eq!(deps.entity_type, "array");
        find_change(&changes, "react", ChangeType::Deleted);
    }

    #[test]
    fn array_to_object_transition_reports_modified_plus_new_children_added() {
        let changes = json_diff(
            "{\n  \"deps\": [\"react\"]\n}",
            "{\n  \"deps\": {\n    \"react\": \"18\"\n  }\n}",
        );
        let deps = find_change(&changes, "deps", ChangeType::Modified);
        assert_eq!(deps.entity_type, "object");
        let react = find_change(&changes, "react", ChangeType::Added);
        assert_eq!(react.parent_name.as_deref(), Some("deps"));
    }

    #[test]
    fn deep_whole_section_deleted_only_leaf_reported() {
        let changes = json_diff(
            "{\n  \"jest\": {\n    \"config\": {\n      \"testTimeout\": 5000\n    }\n  }\n}",
            "{}",
        );
        let timeout = find_change(&changes, "testTimeout", ChangeType::Deleted);
        assert_eq!(timeout.parent_name.as_deref(), Some("jest::config"));
        assert!(!changes.iter().any(|c| c.entity_name == "jest" || c.entity_name == "config"),
            "intermediate containers should be suppressed; got: {:?}", names(&changes));
    }

    #[test]
    fn pointer_escapes_preserve_rfc6901_order() {
        // '~' must be escaped before '/'. Otherwise a literal '/' would become
        // '~1' and the '~' inside that would then become '~01'.
        let cases = [
            ("a/b", "test.json::/a~1b"),
            ("a~b", "test.json::/a~0b"),
            ("a~/b", "test.json::/a~0~1b"),
        ];
        for (key, expected_id) in cases {
            let changes = json_diff(
                &format!("{{\n  \"{key}\": 1\n}}"),
                &format!("{{\n  \"{key}\": 2\n}}"),
            );
            assert_eq!(changes.len(), 1);
            assert_eq!(changes[0].entity_id, expected_id, "key {key}");
        }
    }

    // ─────────────────────────────────────────────────────────────────────────
    //  Document-level edge cases
    // ─────────────────────────────────────────────────────────────────────────

    #[test]
    fn documents_without_extractable_keys_produce_no_entities() {
        let plugin = JsonParserPlugin;
        for input in ["[1, 2, 3]", "\"hello\"", "42", "null", "{}"] {
            assert!(
                plugin.extract_entities(input, "test.json").is_empty(),
                "input: {input}"
            );
        }
    }

    #[test]
    fn malformed_input_does_not_panic() {
        let plugin = JsonParserPlugin;
        let cases = [
            "{",                                 // unclosed root
            "{\"a\":",                           // dangling colon
            "{\"a\": {",                         // unclosed nested object
            "{\"a\": {] }}",                     // stray ']' inside object value
            "{\"a\": {\"b\": [}]}",              // mismatched brackets in array
            "{\"a\": }}}}",                      // multiple stray '}'
            "{\"a\": {\"b\": 1}, \"c\":",        // truncated mid-object
        ];
        for input in cases {
            let _ = plugin.extract_entities(input, "test.json");
        }
    }

    #[test]
    fn parent_rename_with_child_value_change_falls_back_to_leaf_delete_add() {
        let changes = json_diff(
            "{\n  \"scripts\": {\n    \"dev\": \"vite\"\n  }\n}\n",
            "{\n  \"tasks\": {\n    \"dev\": \"rollup\"\n  }\n}\n",
        );
        find_change(&changes, "dev", ChangeType::Deleted);
        find_change(&changes, "dev", ChangeType::Added);
        assert!(!changes.iter().any(|c| c.change_type == ChangeType::Renamed),
            "rename should not be detectable; got: {:?}", names(&changes));
    }
}