remembrall-core 0.4.2

Field-aware code graph plus persistent memory for AI agents - Rust, Postgres + pgvector
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
//! Tree-sitter based Go parser.
//!
//! Extracts symbols and relationships from a single Go source file.
//!
//! # Extracted symbols
//! - `function_declaration`  -> SymbolType::Function  (top-level `func foo()`)
//! - `method_declaration`    -> SymbolType::Method    (`func (s *Server) Handle()`)
//! - `type_declaration` with `struct_type`    -> SymbolType::Class
//! - `type_declaration` with `interface_type` -> SymbolType::Class
//! - The file itself         -> SymbolType::File
//!
//! # Extracted relationships
//! - `import_declaration` -> RelationType::Imports  (single and block imports)
//! - `call_expression`    -> RelationType::Calls
//! - Struct/interface embedding -> RelationType::Inherits
//! - Receiver type defines method -> RelationType::Defines
//! - Function/method parameter and return types -> RelationType::UsesType

use std::collections::{HashMap, HashSet};

use chrono::{DateTime, Utc};
use tree_sitter::{Node, Parser, TreeCursor};
use uuid::Uuid;

use crate::graph::types::{RelationType, Relationship, Symbol, SymbolType};
use crate::parser::python::{FileParseResult, RawImport};

/// Parse a Go file and extract symbols and relationships.
///
/// - `file_path`  - canonical path string stored on each symbol
/// - `source`     - raw UTF-8 source text
/// - `project`    - project name tag
/// - `file_mtime` - filesystem mtime; stored on symbols for incremental indexing
pub fn parse_go_file(
    file_path: &str,
    source: &str,
    project: &str,
    file_mtime: DateTime<Utc>,
) -> FileParseResult {
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_go::LANGUAGE.into())
        .expect("failed to load Go grammar");

    let Some(tree) = parser.parse(source, None) else {
        tracing::warn!("tree-sitter failed to parse {file_path}");
        return FileParseResult::default();
    };

    let source_bytes = source.as_bytes();
    let root = tree.root_node();

    let mut ctx = ParseContext {
        file_path,
        project,
        file_mtime,
        result: FileParseResult::default(),
        name_to_id: HashMap::new(),
        imported_names: HashSet::new(),
        struct_fields: HashMap::new(),
    };

    // File-level symbol - always the first symbol in the result.
    let file_symbol_id = Uuid::new_v4();
    ctx.result.symbols.push(Symbol {
        id: file_symbol_id,
        name: file_path.to_string(),
        symbol_type: SymbolType::File,
        file_path: file_path.to_string(),
        start_line: Some(1),
        end_line: Some(source.lines().count() as i32),
        language: "go".to_string(),
        project: project.to_string(),
        signature: None,
        file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    // Pass 1: collect imports.
    let mut cursor = root.walk();
    collect_imports(&root, source_bytes, &mut ctx, &mut cursor);

    // Pass 2: collect type and function/method declarations.
    let mut cursor2 = root.walk();
    collect_definitions(&root, file_symbol_id, source_bytes, &mut ctx, &mut cursor2);

    // Pass 3: collect call expressions.
    let mut cursor3 = root.walk();
    collect_calls(&root, source_bytes, &mut ctx, &mut cursor3);

    // Pass 4: collect type annotations from function/method signatures.
    let mut cursor4 = root.walk();
    collect_type_annotations(&root, source_bytes, &mut ctx, &mut cursor4);

    ctx.result
}

// ---------------------------------------------------------------------------
// Internal state
// ---------------------------------------------------------------------------

struct ParseContext<'a> {
    file_path: &'a str,
    project: &'a str,
    file_mtime: DateTime<Utc>,
    result: FileParseResult,
    /// name -> symbol UUID for symbols defined in this file.
    name_to_id: HashMap<String, Uuid>,
    /// Import aliases and package names imported into this file.
    imported_names: HashSet<String>,
    /// (struct_id, field_name) -> field symbol UUID for struct fields defined in
    /// this file. Used to resolve receiver field reads (`s.X`) inside methods to
    /// the struct's field.
    struct_fields: HashMap<(Uuid, String), Uuid>,
}

// ---------------------------------------------------------------------------
// Import collection
// ---------------------------------------------------------------------------

/// Collect all `import_declaration` nodes at the source-file level.
///
/// Go supports two forms:
///   - Single: `import "fmt"`
///   - Block:  `import ( "fmt"\n alias "github.com/gorilla/mux" )`
fn collect_imports<'a>(
    node: &Node<'a>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    for child in node.children(cursor) {
        if child.kind() == "import_declaration" {
            process_import_declaration(&child, source, ctx);
        }
    }
}

fn process_import_declaration(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let file_id = ctx.result.symbols[0].id;
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        match child.kind() {
            // Single import: `import "fmt"` or `import alias "pkg"`
            "interpreted_string_literal" | "raw_string_literal" => {
                let path = unquote(node_text(&child, source));
                emit_import(file_id, &path, None, ctx);
            }
            // Block: `import ( spec spec ... )`
            "import_spec_list" => {
                let mut list_cursor = child.walk();
                for spec in child.named_children(&mut list_cursor) {
                    if spec.kind() == "import_spec" {
                        process_import_spec(&spec, source, file_id, ctx);
                    }
                }
            }
            // Single import_spec directly under import_declaration
            "import_spec" => {
                process_import_spec(&child, source, file_id, ctx);
            }
            _ => {}
        }
    }
}

fn process_import_spec(node: &Node<'_>, source: &[u8], file_id: Uuid, ctx: &mut ParseContext<'_>) {
    // tree-sitter-go fields on import_spec: name (optional alias), path
    let path_node = node.child_by_field_name("path");
    let alias_node = node.child_by_field_name("name");

    let path = path_node
        .map(|n| unquote(node_text(&n, source)))
        .unwrap_or_default();

    if path.is_empty() {
        return;
    }

    // Alias: explicit alias, "_" (blank import), or "." (dot import)
    let alias = alias_node.map(|n| node_text(&n, source));

    emit_import(file_id, &path, alias.as_deref(), ctx);
}

/// Emit an import relationship and record the imported package name.
fn emit_import(file_id: Uuid, import_path: &str, alias: Option<&str>, ctx: &mut ParseContext<'_>) {
    if import_path.is_empty() {
        return;
    }

    // Determine the local name used in the file to reference the package.
    // Priority: explicit alias > last path segment (Go convention).
    let local_name = match alias {
        Some("_") | Some(".") | None => {
            // Derive from last path segment: "github.com/gorilla/mux" -> "mux"
            import_path
                .rsplit('/')
                .next()
                .unwrap_or(import_path)
                .to_string()
        }
        Some(a) => a.to_string(),
    };

    if !local_name.is_empty() && local_name != "_" && local_name != "." {
        ctx.imported_names.insert(local_name);
    }

    // Record as raw import; Go imports use path notation (contains '/').
    ctx.result.raw_imports.push(RawImport {
        source_id: file_id,
        module_raw: import_path.to_string(),
        // Go imports with '/' in the path are absolute package paths - treat
        // them as relative only if they start with "./" or "../" (rare but valid).
        is_relative: import_path.starts_with("./") || import_path.starts_with("../"),
        dot_count: 0,
        module_path: import_path.to_string(),
    });

    let target_id = Uuid::new_v5(&Uuid::NAMESPACE_OID, import_path.as_bytes());
    ctx.result.relationships.push(Relationship {
        source_id: file_id,
        target_id,
        rel_type: RelationType::Imports,
        confidence: 0.3,
    });
}

// ---------------------------------------------------------------------------
// Definition collection
// ---------------------------------------------------------------------------

/// Walk top-level declarations collecting functions, methods, and type defs.
fn collect_definitions<'a>(
    node: &Node<'a>,
    file_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    for child in node.children(cursor) {
        match child.kind() {
            "function_declaration" => {
                process_function_declaration(&child, file_id, source, ctx);
            }
            "method_declaration" => {
                process_method_declaration(&child, file_id, source, ctx);
            }
            "type_declaration" => {
                process_type_declaration(&child, file_id, source, ctx);
            }
            _ => {}
        }
    }
}

/// `func foo(args) returnType { ... }`
fn process_function_declaration(
    node: &Node<'_>,
    file_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "<anonymous>".to_string());

    let signature = build_func_signature(node, &name, source, None);
    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();

    ctx.name_to_id.insert(name.clone(), id);
    ctx.result.symbols.push(Symbol {
        id,
        name: name.clone(),
        symbol_type: SymbolType::Function,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "go".to_string(),
        project: ctx.project.to_string(),
        signature: Some(signature),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    ctx.result.relationships.push(Relationship {
        source_id: file_id,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: 1.0,
    });
}

/// `func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { ... }`
fn process_method_declaration(
    node: &Node<'_>,
    file_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "<anonymous>".to_string());

    // Extract receiver type name for the Defines relationship.
    // `func (s *Server) Foo()` -> receiver type is "Server"
    let receiver_type = node
        .child_by_field_name("receiver")
        .and_then(|recv| extract_receiver_type(&recv, source));

    let signature = build_func_signature(node, &name, source, receiver_type.as_deref());
    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();

    // Use "ReceiverType.MethodName" as the unique key to avoid collisions
    // when multiple types have a method with the same name.
    let qualified_name = if let Some(ref rt) = receiver_type {
        format!("{rt}.{name}")
    } else {
        name.clone()
    };
    ctx.name_to_id.insert(qualified_name, id);

    ctx.result.symbols.push(Symbol {
        id,
        name: name.clone(),
        symbol_type: SymbolType::Method,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "go".to_string(),
        project: ctx.project.to_string(),
        signature: Some(signature),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    // DEFINES from the receiver struct (if we know it), otherwise from the file.
    let defines_source = if let Some(ref rt) = receiver_type {
        ctx.name_to_id
            .get(rt)
            .copied()
            .unwrap_or(file_id)
    } else {
        file_id
    };

    ctx.result.relationships.push(Relationship {
        source_id: defines_source,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: if receiver_type.is_some() && defines_source != file_id {
            1.0
        } else {
            0.8
        },
    });
}

/// `type Foo struct { ... }` or `type Foo interface { ... }`
fn process_type_declaration(
    node: &Node<'_>,
    file_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let mut cursor = node.walk();
    for spec in node.named_children(&mut cursor) {
        if spec.kind() == "type_spec" {
            process_type_spec(&spec, file_id, source, ctx);
        }
    }
}

fn process_type_spec(
    node: &Node<'_>,
    file_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let name = node
        .child_by_field_name("name")
        .map(|n| node_text(&n, source))
        .unwrap_or_default();

    if name.is_empty() {
        return;
    }

    let type_node = node.child_by_field_name("type");
    let type_kind = type_node.as_ref().map(|n| n.kind()).unwrap_or("");

    let is_struct_or_iface = matches!(type_kind, "struct_type" | "interface_type");
    if !is_struct_or_iface {
        // Type aliases and other type defs are skipped for now.
        return;
    }

    let signature = format!("type {name} {type_kind}");
    let start_line = node.start_position().row as i32 + 1;
    let end_line = node.end_position().row as i32 + 1;
    let id = Uuid::new_v4();

    ctx.name_to_id.insert(name.clone(), id);
    ctx.result.symbols.push(Symbol {
        id,
        name: name.clone(),
        symbol_type: SymbolType::Class,
        file_path: ctx.file_path.to_string(),
        start_line: Some(start_line),
        end_line: Some(end_line),
        language: "go".to_string(),
        project: ctx.project.to_string(),
        signature: Some(signature),
        file_mtime: ctx.file_mtime,
        layer: None,
        parent_symbol_id: None,
        moniker: None,
    });

    ctx.result.relationships.push(Relationship {
        source_id: file_id,
        target_id: id,
        rel_type: RelationType::Defines,
        confidence: 1.0,
    });

    // Collect embedded types (struct embedding / interface embedding).
    if let Some(type_body) = type_node {
        collect_embeddings(&type_body, id, source, ctx);
        // Capture named struct fields as Field symbols (skips embedded fields,
        // which have no `name` and are already emitted as Inherits above).
        if type_kind == "struct_type" {
            collect_struct_fields(&type_body, id, source, ctx);
        }
    }
}

/// Walk a `struct_type` body and emit a `Field` symbol + `Defines` edge for each
/// named `field_declaration`. Embedded fields (no `name`) are skipped - they are
/// handled as `Inherits` by `collect_embeddings`.
fn collect_struct_fields(
    type_body: &Node<'_>,
    struct_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    // struct_type's named child is `field_declaration_list`; descend into it.
    let mut cursor = type_body.walk();
    let list = type_body
        .named_children(&mut cursor)
        .find(|c| c.kind() == "field_declaration_list");
    let Some(list) = list else {
        return;
    };
    let mut lc = list.walk();
    for child in list.named_children(&mut lc) {
        if child.kind() != "field_declaration" {
            continue;
        }
        let Some(name_node) = child.child_by_field_name("name") else {
            continue; // embedded field, no name
        };
        let name = node_text(&name_node, source);
        if name.is_empty() {
            continue;
        }
        let start_line = child.start_position().row as i32 + 1;
        let end_line = child.end_position().row as i32 + 1;
        let field_id = Uuid::new_v4();
        ctx.struct_fields.insert((struct_id, name.clone()), field_id);

        ctx.result.symbols.push(Symbol {
            id: field_id,
            name,
            symbol_type: SymbolType::Field,
            file_path: ctx.file_path.to_string(),
            start_line: Some(start_line),
            end_line: Some(end_line),
            language: "go".to_string(),
            project: ctx.project.to_string(),
            signature: None,
            file_mtime: ctx.file_mtime,
            layer: None,
            parent_symbol_id: Some(struct_id),
            moniker: None,
        });

        ctx.result.relationships.push(Relationship {
            source_id: struct_id,
            target_id: field_id,
            rel_type: RelationType::Defines,
            confidence: 1.0,
        });
    }
}

/// Collect struct embedding and interface embedding relationships.
///
/// Struct: `type Handler struct { http.Handler; Logger }` - each embedded
/// field without an explicit field name is an embedding.
///
/// Interface: `type ReadWriter interface { Reader; Writer }` - embedded
/// interface types.
fn collect_embeddings(
    type_body: &Node<'_>,
    owner_id: Uuid,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
) {
    let mut cursor = type_body.walk();
    for child in type_body.named_children(&mut cursor) {
        match child.kind() {
            // Struct embedding: a field_declaration where the only named child is
            // a type (no field name). tree-sitter-go represents embedded fields
            // as `field_declaration` nodes with a `type` field but no `name`.
            "field_declaration" => {
                // Embedded field: no `name` child, only a type reference.
                if child.child_by_field_name("name").is_none() {
                    if let Some(type_node) = child.child_by_field_name("type") {
                        let embedded = strip_pointer(node_text(&type_node, source));
                        // Strip package qualifier: "http.Handler" -> "Handler"
                        let base_name = embedded.split('.').last().unwrap_or(&embedded).to_string();
                        if !base_name.is_empty() {
                            emit_inherits(owner_id, &base_name, ctx);
                        }
                    }
                }
            }
            // Interface embedding: just a type_name or qualified_type_identifier
            // inside the interface body.
            "type_name" | "qualified_type_identifier" => {
                let embedded = node_text(&child, source);
                let base_name = embedded.split('.').last().unwrap_or(&embedded).to_string();
                if !base_name.is_empty() {
                    emit_inherits(owner_id, &base_name, ctx);
                }
            }
            _ => {}
        }
    }
}

fn emit_inherits(owner_id: Uuid, base_name: &str, ctx: &mut ParseContext<'_>) {
    let (target_id, confidence) = if let Some(&id) = ctx.name_to_id.get(base_name) {
        (id, 1.0_f32)
    } else if ctx.imported_names.contains(base_name) {
        (Uuid::new_v5(&Uuid::NAMESPACE_OID, base_name.as_bytes()), 0.8)
    } else {
        (Uuid::new_v5(&Uuid::NAMESPACE_OID, base_name.as_bytes()), 0.5)
    };

    ctx.result.relationships.push(Relationship {
        source_id: owner_id,
        target_id,
        rel_type: RelationType::Inherits,
        confidence,
    });
}

// ---------------------------------------------------------------------------
// Call collection
// ---------------------------------------------------------------------------

fn collect_calls<'a>(
    node: &Node<'a>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    for child in node.children(cursor) {
        if child.kind() == "call_expression" {
            process_call(&child, source, ctx);
        }
        // Receiver field reads: `s.X` where `s` is the method receiver - emit a
        // References edge to the struct's field. Method calls (`s.M()`) and
        // qualified package access (`pkg.X`) are filtered inside
        // process_receiver_field_read.
        if child.kind() == "selector_expression" {
            process_receiver_field_read(&child, source, ctx);
        }
        let mut inner = child.walk();
        collect_calls(&child, source, ctx, &mut inner);
    }
}

fn process_call(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    // tree-sitter-go: call_expression has a `function` field.
    let Some(function_node) = node.child_by_field_name("function") else {
        return;
    };

    let (callee_name, is_qualified) = extract_callee(&function_node, source);
    if callee_name.is_empty() {
        return;
    }

    let caller_id = find_enclosing_function(node, ctx);

    let (target_id, confidence) = if let Some(&id) = ctx.name_to_id.get(&callee_name) {
        (id, 1.0_f32)
    } else if ctx.imported_names.contains(callee_name.split('.').next().unwrap_or("")) {
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.8,
        )
    } else if is_qualified {
        // receiver.Method() - can't resolve statically without type info.
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.6,
        )
    } else {
        (
            Uuid::new_v5(&Uuid::NAMESPACE_OID, callee_name.as_bytes()),
            0.5,
        )
    };

    let source_id = caller_id.unwrap_or(ctx.result.symbols[0].id);

    ctx.result.relationships.push(Relationship {
        source_id,
        target_id,
        rel_type: RelationType::Calls,
        confidence,
    });
}

/// Extract the callee name from a call expression's function node.
///
/// - `foo()`         -> ("foo", false)
/// - `pkg.Func()`    -> ("Func", true)
/// - `s.Method()`    -> ("Method", true)
/// - `a.b.c()`       -> ("c", true)
fn extract_callee(node: &Node<'_>, source: &[u8]) -> (String, bool) {
    match node.kind() {
        "identifier" => (node_text(node, source), false),
        "selector_expression" => {
            // `X.Y` - take the field (method/function name).
            let field = node
                .child_by_field_name("field")
                .map(|n| node_text(&n, source))
                .unwrap_or_default();
            (field, true)
        }
        _ => (String::new(), false),
    }
}

/// Find the innermost enclosing function or method that contains `call_node`.
fn find_enclosing_function(call_node: &Node<'_>, ctx: &ParseContext<'_>) -> Option<Uuid> {
    let call_start = call_node.start_position().row as i32 + 1;
    let mut best: Option<(Uuid, i32)> = None; // (id, range_size)

    for sym in &ctx.result.symbols {
        if !matches!(sym.symbol_type, SymbolType::Function | SymbolType::Method) {
            continue;
        }
        let (start, end) = match (sym.start_line, sym.end_line) {
            (Some(s), Some(e)) => (s, e),
            _ => continue,
        };
        if call_start >= start && call_start <= end {
            let range = end - start;
            let current_best = best.map(|(_, r)| r).unwrap_or(i32::MAX);
            if range < current_best {
                best = Some((sym.id, range));
            }
        }
    }

    best.map(|(id, _)| id)
}

/// Walk up the AST from `node` to find the enclosing method's receiver and
/// return `(receiver_var_name, receiver_type_name)`. Returns None outside a
/// method (free functions have no receiver).
fn find_enclosing_receiver(node: &Node<'_>, source: &[u8]) -> Option<(String, String)> {
    let mut current = node.parent()?;
    loop {
        if current.kind() == "method_declaration" {
            if let Some(recv) = current.child_by_field_name("receiver") {
                let type_name = extract_receiver_type(&recv, source).unwrap_or_default();
                let mut cursor = recv.walk();
                for param in recv.named_children(&mut cursor) {
                    if param.kind() == "parameter_declaration" {
                        if let Some(name_node) = param.child_by_field_name("name") {
                            let var_name = node_text(&name_node, source);
                            if !var_name.is_empty() && !type_name.is_empty() {
                                return Some((var_name, type_name));
                            }
                        }
                    }
                }
            }
            return None;
        }
        current = current.parent()?;
    }
}

/// Emit a `References` edge for a receiver field read `s.X` inside a method.
///
/// Only direct `<receiver>.<field>` selector expressions where the object is the
/// receiver variable. Intermediate reads in `s.a.b()` (i.e. `s.a`) are still
/// caught. Method calls (`s.M()`) and writes (`s.X = ...`) are skipped. The
/// field is resolved against the receiver struct via the per-file `struct_fields`
/// map.
fn process_receiver_field_read(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let Some(obj) = node.child_by_field_name("operand") else {
        return;
    };
    if obj.kind() != "identifier" {
        return;
    }
    let obj_name = node_text(&obj, source);

    let Some(field_node) = node.child_by_field_name("field") else {
        return;
    };
    let field_name = node_text(&field_node, source);
    if field_name.is_empty() {
        return;
    }

    let Some((recv_var, type_name)) = find_enclosing_receiver(node, source) else {
        return;
    };
    if obj_name != recv_var {
        return;
    }

    if let Some(parent) = node.parent() {
        // Skip method invocations: `s.Method()`.
        if parent.kind() == "call_expression"
            && parent.child_by_field_name("function").map(|f| f.id()) == Some(node.id())
        {
            return;
        }
    }

    let Some(&struct_id) = ctx.name_to_id.get(&type_name) else {
        return;
    };
    let Some(&field_id) = ctx.struct_fields.get(&(struct_id, field_name.clone())) else {
        return;
    };

    let source_id = find_enclosing_function(node, ctx)
        .unwrap_or_else(|| ctx.result.symbols[0].id);

    ctx.result.relationships.push(Relationship {
        source_id,
        target_id: field_id,
        rel_type: RelationType::References,
        confidence: 1.0,
    });
}

// ---------------------------------------------------------------------------
// Type annotation collection
// ---------------------------------------------------------------------------

/// Walk top-level function and method declarations and emit UsesType
/// relationships for each non-builtin type referenced in parameters and
/// return types.
fn collect_type_annotations<'a>(
    node: &Node<'a>,
    source: &[u8],
    ctx: &mut ParseContext<'_>,
    cursor: &mut TreeCursor<'a>,
) {
    for child in node.children(cursor) {
        match child.kind() {
            "function_declaration" | "method_declaration" => {
                process_func_type_annotations(&child, source, ctx);
            }
            _ => {}
        }
    }
}

/// Emit UsesType relationships for all non-builtin types found in a function
/// or method's parameter list and return type.
fn process_func_type_annotations(node: &Node<'_>, source: &[u8], ctx: &mut ParseContext<'_>) {
    let func_id = {
        let name = node
            .child_by_field_name("name")
            .map(|n| node_text(&n, source))
            .unwrap_or_default();
        if name.is_empty() {
            return;
        }
        // For methods the map key is "ReceiverType.MethodName"; for functions it is just the name.
        let receiver_type = node
            .child_by_field_name("receiver")
            .and_then(|recv| extract_receiver_type(&recv, source));
        let key = if let Some(ref rt) = receiver_type {
            format!("{rt}.{name}")
        } else {
            name
        };
        match ctx.name_to_id.get(&key).copied() {
            Some(id) => id,
            None => return,
        }
    };

    // Collect types from the parameter list.
    if let Some(params_node) = node.child_by_field_name("parameters") {
        for type_name in extract_type_identifiers(&params_node, source) {
            emit_uses_type(func_id, &type_name, ctx);
        }
    }

    // Collect types from the return type (the `result` field).
    if let Some(result_node) = node.child_by_field_name("result") {
        for type_name in extract_type_identifiers(&result_node, source) {
            emit_uses_type(func_id, &type_name, ctx);
        }
    }
}

/// Recursively extract all named type identifiers from a node subtree.
///
/// Handles:
/// - `type_identifier`  - plain named type: `MyType`
/// - `qualified_type`   - package-qualified: `http.ResponseWriter` (last segment only)
/// - `pointer_type`     - `*MyType` (recurse into element)
/// - `slice_type`       - `[]MyType` (recurse into element)
/// - `map_type`         - `map[K]V` (recurse into key and value fields)
/// - `channel_type`     - `chan MyType` (recurse)
fn extract_type_identifiers(node: &Node<'_>, source: &[u8]) -> Vec<String> {
    let mut result = Vec::new();
    collect_type_ids_recursive(node, source, &mut result);
    result
}

fn collect_type_ids_recursive(node: &Node<'_>, source: &[u8], out: &mut Vec<String>) {
    match node.kind() {
        "type_identifier" => {
            let name = node_text(node, source);
            if !name.is_empty() && !is_go_builtin(&name) {
                out.push(name);
            }
        }
        "qualified_type" => {
            // `pkg.TypeName` - use only the last dotted segment.
            let full = node_text(node, source);
            let name = full.split('.').last().unwrap_or(&full).trim().to_string();
            if !name.is_empty() && !is_go_builtin(&name) {
                out.push(name);
            }
        }
        "pointer_type" | "slice_type" | "channel_type" => {
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                collect_type_ids_recursive(&child, source, out);
            }
        }
        "map_type" => {
            if let Some(key) = node.child_by_field_name("key") {
                collect_type_ids_recursive(&key, source, out);
            }
            if let Some(val) = node.child_by_field_name("value") {
                collect_type_ids_recursive(&val, source, out);
            }
        }
        _ => {
            // Descend into parameter_declaration, parameter_list, result, etc.
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                collect_type_ids_recursive(&child, source, out);
            }
        }
    }
}

/// Returns true if `name` is a Go primitive or builtin that should not
/// produce a UsesType relationship.
fn is_go_builtin(name: &str) -> bool {
    matches!(
        name,
        "int"
            | "int8"
            | "int16"
            | "int32"
            | "int64"
            | "uint"
            | "uint8"
            | "uint16"
            | "uint32"
            | "uint64"
            | "float32"
            | "float64"
            | "complex64"
            | "complex128"
            | "byte"
            | "rune"
            | "string"
            | "bool"
            | "error"
            | "any"
            | "comparable"
            | "uintptr"
    )
}

/// Emit a single UsesType relationship from `source_id` to the resolved or
/// synthetic target UUID for `type_name`.
fn emit_uses_type(source_id: Uuid, type_name: &str, ctx: &mut ParseContext<'_>) {
    let (target_id, confidence) = if let Some(&id) = ctx.name_to_id.get(type_name) {
        (id, 1.0_f32)
    } else if ctx.imported_names.contains(type_name) {
        (Uuid::new_v5(&Uuid::NAMESPACE_OID, type_name.as_bytes()), 0.8)
    } else {
        (Uuid::new_v5(&Uuid::NAMESPACE_OID, type_name.as_bytes()), 0.5)
    };

    ctx.result.relationships.push(Relationship {
        source_id,
        target_id,
        rel_type: RelationType::UsesType,
        confidence,
    });
}

// ---------------------------------------------------------------------------
// Signature building
// ---------------------------------------------------------------------------

/// Build a human-readable signature for a function or method.
///
/// - Function: `func foo(a int, b string) error`
/// - Method:   `func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)`
fn build_func_signature(
    node: &Node<'_>,
    name: &str,
    source: &[u8],
    receiver_type: Option<&str>,
) -> String {
    let receiver_text = node
        .child_by_field_name("receiver")
        .map(|n| format!("{} ", node_text(&n, source)));

    let params = node
        .child_by_field_name("parameters")
        .map(|n| node_text(&n, source))
        .unwrap_or_else(|| "()".to_string());

    let result = node
        .child_by_field_name("result")
        .map(|n| format!(" {}", node_text(&n, source)))
        .unwrap_or_default();

    let _ = receiver_type; // used by caller for relationship lookup; not in sig text

    format!(
        "func {}{}{}{}",
        receiver_text.as_deref().unwrap_or(""),
        name,
        params,
        result
    )
}

// ---------------------------------------------------------------------------
// Utility helpers
// ---------------------------------------------------------------------------

/// Extract the concrete receiver type from a parameter list node.
///
/// `(s *Server)` -> Some("Server")
/// `(s Server)`  -> Some("Server")
fn extract_receiver_type(recv_node: &Node<'_>, source: &[u8]) -> Option<String> {
    let mut cursor = recv_node.walk();
    for child in recv_node.named_children(&mut cursor) {
        // Each receiver parameter is a `parameter_declaration`.
        if child.kind() == "parameter_declaration" {
            if let Some(type_node) = child.child_by_field_name("type") {
                let raw = node_text(&type_node, source);
                // Strip pointer: "*Server" -> "Server"
                let clean = strip_pointer(raw);
                // Strip package qualifier (unusual for receivers but handle it).
                let base = clean.split('.').last().unwrap_or(&clean).to_string();
                if !base.is_empty() {
                    return Some(base);
                }
            }
        }
    }
    None
}

/// Remove a leading `*` from a type expression (pointer dereference).
fn strip_pointer(s: String) -> String {
    s.trim_start_matches('*').trim().to_string()
}

/// Remove surrounding quotes from an import path string.
fn unquote(s: String) -> String {
    s.trim_matches('"').trim_matches('`').to_string()
}

fn node_text(node: &Node<'_>, source: &[u8]) -> String {
    node.utf8_text(source)
        .unwrap_or("")
        .trim()
        .to_string()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;

    fn parse(source: &str) -> FileParseResult {
        parse_go_file("test.go", source, "proj", Utc::now())
    }

    fn field_symbols(result: &FileParseResult) -> Vec<&Symbol> {
        result
            .symbols
            .iter()
            .filter(|s| s.symbol_type == SymbolType::Field)
            .collect()
    }

    fn references_rels(result: &FileParseResult) -> Vec<&Relationship> {
        result
            .relationships
            .iter()
            .filter(|r| r.rel_type == RelationType::References)
            .collect()
    }

    #[test]
    fn test_struct_fields_captured() {
        // Named struct fields become Field symbols; embedded fields do not.
        let source = r#"
package main

type Server struct {
    Logger
    addr string
    port int
}
"#;
        let result = parse(source);
        let fields = field_symbols(&result);
        let names: Vec<_> = fields.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["addr", "port"], "fields: {fields:?}");
        let struct_id = result
            .symbols
            .iter()
            .find(|s| s.symbol_type == SymbolType::Class && s.name == "Server")
            .map(|s| s.id)
            .unwrap();
        for f in &fields {
            assert_eq!(f.parent_symbol_id, Some(struct_id));
            assert!(
                result.relationships.iter().any(|r| {
                    r.rel_type == RelationType::Defines
                        && r.source_id == struct_id
                        && r.target_id == f.id
                }),
                "missing Defines(struct -> field {})",
                f.name
            );
        }
    }

    #[test]
    fn test_receiver_field_read_emits_references() {
        // `s.addr` read inside a method emits a References edge to the field.
        let source = r#"
package main

type Server struct {
    addr string
}

func (s *Server) Address() string {
    return s.addr
}
"#;
        let result = parse(source);
        let addr = result
            .symbols
            .iter()
            .find(|s| s.symbol_type == SymbolType::Field && s.name == "addr")
            .map(|s| s.id)
            .expect("addr field should exist");
        let address = result
            .symbols
            .iter()
            .find(|s| s.symbol_type == SymbolType::Method && s.name == "Address")
            .map(|s| s.id)
            .expect("Address method should exist");
        let refs = references_rels(&result);
        assert!(
            refs.iter()
                .any(|r| r.source_id == address && r.target_id == addr),
            "expected References(Server.Address -> addr), refs: {refs:?}"
        );
    }

    #[test]
    fn test_receiver_method_call_not_a_field_reference() {
        // `s.Start()` is a method call, not a field read.
        let source = r#"
package main

type Server struct {
    addr string
}

func (s *Server) Start() string {
    return s.addr
}

func (s *Server) Run() string {
    return s.Start()
}
"#;
        let result = parse(source);
        let refs = references_rels(&result);
        assert_eq!(
            refs.len(),
            1,
            "expected exactly 1 References edge (s.addr), got: {refs:?}"
        );
    }
}