agentstatedeveloper-ruby 1.4.9

Ruby language adapter for AgentStateDeveloper (tree-sitter-ruby)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
//! Ruby language adapter for AgentStateDeveloper.
//!
//! Implements [`LanguageAdapter`](agentstatedeveloper_core::LanguageAdapter)
//! on top of `tree-sitter-ruby`. Parses modules, classes, instance methods,
//! singleton methods (def self.x), then runs substring-based effect inference.

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

use agentstatedeveloper_core::adapter::{
    CallEdge, LanguageAdapter, ParsedSymbol, WorkspaceSymbols,
};
use agentstatedeveloper_core::cross_service::{
    DetectedEndpoint, Direction, Transport, http_contract,
};
use agentstatedeveloper_core::error::{AsdError, Result};
use agentstatedeveloper_core::schema::{Effect, EffectCategory, SymbolKind};
use serde_json::json;
use tree_sitter::{Node, Parser};

/// Ruby language adapter.
#[derive(Debug, Default, Clone, Copy)]
pub struct RubyAdapter;

impl RubyAdapter {
    pub fn new() -> Self {
        Self
    }
}

impl LanguageAdapter for RubyAdapter {
    fn language(&self) -> &str {
        "ruby"
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &["rb"]
    }

    fn parse_symbols(&self, file: &str, source: &str) -> Result<Vec<ParsedSymbol>> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_ruby::LANGUAGE.into())
            .map_err(|e| AsdError::Parse(format!("failed to set ruby language: {e}")))?;

        let src_bytes = source.as_bytes();
        let tree = parser
            .parse(src_bytes, None)
            .ok_or_else(|| AsdError::Parse(format!("failed to parse {file}")))?;

        let file_prefix = file_qname_prefix(file);
        let root = tree.root_node();
        let mut out = Vec::new();
        walk(root, src_bytes, &file_prefix, &mut out);
        Ok(out)
    }

    fn infer_effects(&self, _source: &str, symbol: &ParsedSymbol) -> Vec<Effect> {
        infer_effects_from_body(&symbol.body)
    }

    fn infer_service_endpoints(
        &self,
        file: &str,
        source: &str,
        symbols: &[ParsedSymbol],
    ) -> Vec<DetectedEndpoint> {
        infer_service_endpoints_in_ruby(file, source, symbols)
    }

    fn extract_call_edges(
        &self,
        file: &str,
        source: &str,
        symbols: &[ParsedSymbol],
        workspace: &WorkspaceSymbols,
    ) -> Vec<CallEdge> {
        extract_call_edges_impl(file, source, symbols, workspace)
    }
}

// -----------------------------------------------------------------------------
// qname helpers
// -----------------------------------------------------------------------------

/// Walk path components and return the tail after the first `lib` segment.
/// Falls back to the full path for non-gem layouts (e.g. Rails `app/`).
///
/// Examples:
/// - `lib/myapp/parser.rb`      → `myapp/parser.rb`
/// - `gems/foo/lib/foo/bar.rb`  → `foo/bar.rb`
/// - `app/models/user.rb`       → `app/models/user.rb`  (no `lib`, unchanged)
fn strip_lib_prefix(path: &str) -> &str {
    let mut offset = 0usize;
    for part in path.split('/') {
        if part == "lib" {
            let after = offset + part.len() + 1;
            if after < path.len() {
                return &path[after..];
            }
        }
        offset += part.len() + 1;
    }
    path
}

/// `lib/myapp/parser.rb`   → `myapp.parser`  (gem convention, anchored at lib/)
/// `app/models/payment.rb` → `app.models.payment`  (Rails — no lib/, fallback)
fn file_qname_prefix(file: &str) -> String {
    let s = file.strip_prefix("./").unwrap_or(file);
    let s = s.strip_suffix(".rb").unwrap_or(s);
    let s = strip_lib_prefix(s);
    s.replace('/', ".")
}

fn node_text<'a>(node: Node<'_>, src: &'a [u8]) -> &'a str {
    node.utf8_text(src).unwrap_or("")
}

fn child_by_field<'a>(node: Node<'a>, field: &str) -> Option<Node<'a>> {
    node.child_by_field_name(field)
}

fn join_qname(prefix: &str, name: &str) -> String {
    if prefix.is_empty() {
        name.to_string()
    } else {
        format!("{}.{}", prefix, name)
    }
}

fn make_symbol(node: Node<'_>, src: &[u8], qname: String, kind: SymbolKind) -> ParsedSymbol {
    make_symbol_sig(node, src, qname, kind, None)
}

fn make_symbol_sig(
    node: Node<'_>,
    src: &[u8],
    qname: String,
    kind: SymbolKind,
    signature: Option<String>,
) -> ParsedSymbol {
    ParsedSymbol {
        qname,
        kind,
        start_line: node.start_position().row as u32 + 1,
        start_col: node.start_position().column as u32,
        end_line: node.end_position().row as u32 + 1,
        end_col: node.end_position().column as u32,
        body: node_text(node, src).to_string(),
        signature,
        doc: None,
    }
}

/// Extract the Ruby method signature: the first line of the `def` declaration.
/// Ruby uses `end` as the body terminator (not `{`), so we take everything
/// up to the first newline.
fn extract_ruby_sig(node: Node<'_>, src: &[u8]) -> Option<String> {
    let text = std::str::from_utf8(&src[node.start_byte()..node.end_byte()]).ok()?;
    let first_line = text.lines().next()?.trim().to_string();
    if first_line.is_empty() {
        None
    } else {
        Some(first_line)
    }
}

// -----------------------------------------------------------------------------
// Symbol walking
// -----------------------------------------------------------------------------

fn walk(node: Node<'_>, src: &[u8], scope: &str, out: &mut Vec<ParsedSymbol>) {
    match node.kind() {
        "program" => {
            for i in 0..node.child_count() {
                walk(node.child(i).unwrap(), src, scope, out);
            }
        }
        "module" => {
            let name = child_by_field(node, "name")
                .map(|n| node_text(n, src))
                .unwrap_or("");
            if name.is_empty() {
                return;
            }
            let qname = join_qname(scope, name);
            out.push(make_symbol(node, src, qname.clone(), SymbolKind::Module));
            // Walk body
            if let Some(body) = child_by_field(node, "body") {
                for i in 0..body.child_count() {
                    walk(body.child(i).unwrap(), src, &qname, out);
                }
            }
        }
        "class" => {
            let name = child_by_field(node, "name")
                .map(|n| node_text(n, src))
                .unwrap_or("");
            if name.is_empty() {
                return;
            }
            let qname = join_qname(scope, name);
            out.push(make_symbol(node, src, qname.clone(), SymbolKind::Class));
            if let Some(body) = child_by_field(node, "body") {
                for i in 0..body.child_count() {
                    walk(body.child(i).unwrap(), src, &qname, out);
                }
            }
        }
        "method" => {
            let name = child_by_field(node, "name")
                .map(|n| node_text(n, src))
                .unwrap_or("");
            if name.is_empty() {
                return;
            }
            let qname = join_qname(scope, name);
            let sig = extract_ruby_sig(node, src);
            out.push(make_symbol_sig(node, src, qname, SymbolKind::Method, sig));
        }
        "singleton_method" => {
            // def self.method_name — treat as a class-level Function
            let name = child_by_field(node, "name")
                .map(|n| node_text(n, src))
                .unwrap_or("");
            if name.is_empty() {
                return;
            }
            let qname = join_qname(scope, name);
            let sig = extract_ruby_sig(node, src);
            out.push(make_symbol_sig(node, src, qname, SymbolKind::Function, sig));
        }
        _ => {
            for i in 0..node.child_count() {
                walk(node.child(i).unwrap(), src, scope, out);
            }
        }
    }
}

// -----------------------------------------------------------------------------
// Effect inference
// -----------------------------------------------------------------------------

fn find_occurrences(body: &str, needle: &str) -> Vec<usize> {
    let mut out = Vec::new();
    let mut from = 0;
    while let Some(idx) = body[from..].find(needle) {
        out.push(from + idx);
        from += idx + needle.len();
    }
    out
}

fn extract_url_host(s: &str) -> Option<String> {
    for scheme in ["https://", "http://"] {
        if let Some(idx) = s.find(scheme) {
            let tail = &s[idx + scheme.len()..];
            let end = tail
                .find(|c: char| c == '/' || c == '"' || c == '\'' || c == ')' || c.is_whitespace())
                .unwrap_or(tail.len());
            let host = &tail[..end];
            if !host.is_empty() {
                return Some(host.to_string());
            }
        }
    }
    None
}

fn first_matching_line(body: &str, needles: &[&str]) -> Option<String> {
    for line in body.lines() {
        for n in needles {
            if line.contains(n) {
                return Some(line.trim().to_string());
            }
        }
    }
    None
}

fn first_match_note(body: &str, needles: &[&str]) -> Option<String> {
    for n in needles {
        if body.contains(n) {
            return first_matching_line(body, needles);
        }
    }
    None
}

fn extract_first_string_arg(s: &str) -> Option<String> {
    let trimmed = s.trim_start();
    let bytes = trimmed.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let q = bytes[0];
    if q != b'"' && q != b'\'' {
        return None;
    }
    let mut j = 1;
    let mut out = String::new();
    while j < bytes.len() {
        let c = bytes[j];
        if c == b'\\' && j + 1 < bytes.len() {
            out.push(bytes[j + 1] as char);
            j += 2;
            continue;
        }
        if c == q {
            return Some(out);
        }
        out.push(c as char);
        j += 1;
    }
    None
}

// -----------------------------------------------------------------------------
// Cross-service endpoint detection (t-014) — Sinatra / Rails routes + clients
//
// Inbound: a route DSL line `verb '/path' …` (Sinatra `get '/x' do`, Rails
// `get '/x', to: ...`). Requiring the line to START with the verb keyword keeps
// method calls like `obj.get('/x')` out. Outbound: RestClient/HTTParty
// `.<verb>('url')`. Interpolated ("#{…}") strings are skipped.
//
// Limitation: Rails routes.rb routes live in a top-level `routes.draw` block
// with no enclosing class/def, so there's no symbol to attribute them to and
// they're dropped. Sinatra routes (inside the app class) attribute fine.
// -----------------------------------------------------------------------------

const VERBS: &[&str] = &["get", "post", "put", "patch", "delete"];

fn infer_service_endpoints_in_ruby(
    file: &str,
    source: &str,
    symbols: &[ParsedSymbol],
) -> Vec<DetectedEndpoint> {
    let mut out = Vec::new();
    for (idx, raw) in source.lines().enumerate() {
        let line_no = (idx + 1) as u32;
        let line = raw.trim();

        if let Some((method, path)) = ruby_route(line) {
            if let Some(owner) = owner_for_body_line(symbols, line_no) {
                out.push(DetectedEndpoint {
                    transport: Transport::Http,
                    direction: Direction::Inbound,
                    contract: http_contract(&method, &path),
                    owner_qname: owner.qname.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: 0.85,
                    note: None,
                });
            }
        }
        for (method, url) in ruby_clients(line) {
            if let Some(owner) = owner_for_body_line(symbols, line_no) {
                out.push(DetectedEndpoint {
                    transport: Transport::Http,
                    direction: Direction::Outbound,
                    contract: http_contract(&method, &url),
                    owner_qname: owner.qname.clone(),
                    file: file.to_string(),
                    line: line_no,
                    confidence: 0.85,
                    note: None,
                });
            }
        }
    }
    out
}

fn owner_for_body_line(symbols: &[ParsedSymbol], line: u32) -> Option<&ParsedSymbol> {
    symbols
        .iter()
        .filter(|s| s.start_line <= line && line <= s.end_line)
        .max_by_key(|s| s.start_line)
}

/// Sinatra/Rails route: line starts with `verb '/path'`.
fn ruby_route(line: &str) -> Option<(String, String)> {
    for verb in VERBS {
        if let Some(rest) = line.strip_prefix(&format!("{verb} ")) {
            if let Some(path) = first_ruby_string(rest.trim_start()) {
                if path.starts_with('/') {
                    return Some((verb.to_uppercase(), path));
                }
            }
        }
    }
    None
}

/// RestClient/HTTParty client calls: `RestClient.get('url')` etc.
fn ruby_clients(line: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    for lib in ["RestClient", "HTTParty"] {
        for verb in VERBS {
            let needle = format!("{lib}.{verb}(");
            if let Some(pos) = line.find(&needle) {
                if let Some(url) = first_ruby_string(line[pos + needle.len()..].trim_start()) {
                    out.push((verb.to_uppercase(), url));
                }
            }
        }
    }
    out
}

/// First `'…'` or `"…"` string literal; interpolated (`"#{…}"`) strings are
/// rejected as dynamic.
fn first_ruby_string(s: &str) -> Option<String> {
    let s = s.trim_start();
    let q = s.as_bytes().first().copied()?;
    if q != b'\'' && q != b'"' {
        return None;
    }
    let inner = &s[1..];
    let end = inner.find(q as char)?;
    let val = &inner[..end];
    if q == b'"' && val.contains("#{") {
        return None;
    }
    Some(val.to_string())
}

fn infer_effects_from_body(body: &str) -> Vec<Effect> {
    let mut effects: Vec<Effect> = Vec::new();

    // FS Read
    let fs_read_needles = [
        "File.read(",
        "File.readlines(",
        "File.open(",
        "IO.read(",
        "IO.readlines(",
        "CSV.read(",
        "CSV.foreach(",
        "File.foreach(",
    ];
    if let Some(note) = first_match_note(body, &fs_read_needles) {
        effects.push(Effect {
            effect: EffectCategory::IoFsRead,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // FS Write
    let fs_write_needles = [
        "File.write(",
        "File.open(", // also write mode — covered by read; separate write markers:
        "IO.write(",
        "FileUtils.cp(",
        "FileUtils.mv(",
        "FileUtils.mkdir",
        "FileUtils.rm",
        "File.delete(",
        "File.rename(",
    ];
    // Only fire write if we see a write-mode marker not already covered by read
    let write_markers = [
        "IO.write(",
        "FileUtils.cp(",
        "FileUtils.mv(",
        "FileUtils.mkdir",
        "FileUtils.rm",
        "File.delete(",
        "File.rename(",
        "\"w\"",
        "\"w+\"",
        "\"a\"",
        "\"a+\"",
        ":write",
        ", 'w'",
        ", 'a'",
    ];
    let has_write_marker = write_markers.iter().any(|m| body.contains(m));
    let _ = fs_write_needles; // suppress unused warning; logic uses write_markers directly
    if has_write_marker {
        if let Some(note) = first_match_note(body, &write_markers) {
            effects.push(Effect {
                effect: EffectCategory::IoFsWrite,
                qualifiers: serde_json::Value::Null,
                note: Some(note),
                ..Default::default()
            });
        }
    }

    // Network
    let net_needles = [
        "Net::HTTP",
        "Net::HTTP.get(",
        "Net::HTTP.post(",
        "Faraday.new(",
        "Faraday.get(",
        "Faraday.post(",
        "HTTParty.get(",
        "HTTParty.post(",
        "RestClient.get(",
        "RestClient.post(",
        "Typhoeus.get(",
        "open-uri",
        "open(\"http",
        "open('http",
        "URI.open(",
    ];
    let mut net_hosts: Vec<String> = Vec::new();
    let mut net_note: Option<String> = None;
    for needle in net_needles {
        if body.contains(needle) && net_note.is_none() {
            net_note = first_matching_line(body, &[needle]);
            for off in find_occurrences(body, needle) {
                let end = (off + 200).min(body.len());
                let snippet = &body[off..end];
                if let Some(host) = extract_url_host(snippet) {
                    if !net_hosts.contains(&host) {
                        net_hosts.push(host);
                    }
                }
            }
        }
    }
    if net_note.is_some() {
        let qualifiers = if net_hosts.is_empty() {
            serde_json::Value::Null
        } else {
            json!({ "hosts": net_hosts })
        };
        effects.push(Effect {
            effect: EffectCategory::IoNetOut,
            qualifiers,
            note: net_note,
            ..Default::default()
        });
    }

    // Database
    let db_needles = [
        ".where(",
        ".find(",
        ".find_by(",
        ".first",
        ".all",
        ".create(",
        ".save(",
        ".update(",
        ".destroy(",
        ".delete(",
        "ActiveRecord::",
        "Sequel::",
        ".execute(",
        ".query(",
        "DB[",
        "connection.exec(",
        "PG.connect(",
        "Mysql2::Client.new(",
        "SQLite3::Database.new(",
    ];
    if let Some(note) = first_match_note(body, &db_needles) {
        let write_markers = [
            ".create(",
            ".save(",
            ".update(",
            ".destroy(",
            ".delete(",
            ".execute(",
            ".insert(",
        ];
        let read_markers = [
            ".where(",
            ".find(",
            ".find_by(",
            ".first",
            ".all",
            ".query(",
            ".exec(",
            "SELECT",
        ];
        let has_write = write_markers.iter().any(|m| body.contains(m));
        let has_read = read_markers.iter().any(|m| body.contains(m));
        if has_read || (!has_read && !has_write) {
            effects.push(Effect {
                effect: EffectCategory::IoDbRead,
                qualifiers: serde_json::Value::Null,
                note: Some(note.clone()),
                ..Default::default()
            });
        }
        if has_write || (!has_read && !has_write) {
            effects.push(Effect {
                effect: EffectCategory::IoDbWrite,
                qualifiers: serde_json::Value::Null,
                note: Some(note),
                ..Default::default()
            });
        }
    }

    // Process spawn
    let proc_needles = [
        "system(",
        "exec(",
        "spawn(",
        "IO.popen(",
        "Open3.",
        "%x{",
        "Kernel.system(",
        "Kernel.exec(",
    ];
    // Avoid false-positive on common method calls like "exec" in ActiveRecord
    let has_proc = proc_needles.iter().any(|n| body.contains(n));
    if has_proc {
        if let Some(note) = first_match_note(body, &proc_needles) {
            effects.push(Effect {
                effect: EffectCategory::ProcSpawn,
                qualifiers: serde_json::Value::Null,
                note: Some(note),
                ..Default::default()
            });
        }
    }

    // Env read
    let env_needles = ["ENV[", "ENV.fetch(", "ENV.key?(", "ENV.values"];
    if let Some(note) = first_match_note(body, &env_needles) {
        let mut vars: Vec<String> = Vec::new();
        for off in find_occurrences(body, "ENV[") {
            let args = &body[off + "ENV[".len()..];
            if let Some(v) = extract_first_string_arg(args) {
                if !vars.contains(&v) {
                    vars.push(v);
                }
            }
        }
        for off in find_occurrences(body, "ENV.fetch(") {
            let args = &body[off + "ENV.fetch(".len()..];
            if let Some(v) = extract_first_string_arg(args) {
                if !vars.contains(&v) {
                    vars.push(v);
                }
            }
        }
        let qualifiers = if vars.is_empty() {
            serde_json::Value::Null
        } else {
            json!({ "vars": vars })
        };
        effects.push(Effect {
            effect: EffectCategory::EnvRead,
            qualifiers,
            note: Some(note),
            ..Default::default()
        });
    }

    // Logging
    let log_needles = [
        "puts ",
        "print ",
        "p ",
        "pp ",
        "Rails.logger.",
        "logger.",
        "Logger.new(",
        "Sentry.",
        "Bugsnag.",
    ];
    if let Some(note) = first_match_note(body, &log_needles) {
        effects.push(Effect {
            effect: EffectCategory::Log,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // Time sleep
    let sleep_needles = ["sleep(", "sleep ", "Kernel.sleep("];
    if let Some(note) = first_match_note(body, &sleep_needles) {
        effects.push(Effect {
            effect: EffectCategory::TimeSleep,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // Time read
    let time_needles = [
        "Time.now",
        "Time.current",
        "Time.at(",
        "DateTime.now",
        "DateTime.current",
        "Date.today",
        "Time.zone.now",
        "Process.clock_gettime(",
    ];
    if let Some(note) = first_match_note(body, &time_needles) {
        effects.push(Effect {
            effect: EffectCategory::TimeRead,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // Random
    let rand_needles = [
        "rand(",
        "rand ",
        "Random.rand(",
        "Random.new(",
        "SecureRandom.",
        "SecureRandom.uuid",
        "SecureRandom.hex",
        ".sample",
        ".shuffle",
    ];
    if let Some(note) = first_match_note(body, &rand_needles) {
        effects.push(Effect {
            effect: EffectCategory::Random,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    // Throw
    let throw_needles = ["raise ", "raise(", "fail ", "fail("];
    if let Some(note) = first_match_note(body, &throw_needles) {
        effects.push(Effect {
            effect: EffectCategory::Throw,
            qualifiers: serde_json::Value::Null,
            note: Some(note),
            ..Default::default()
        });
    }

    effects
}

// -----------------------------------------------------------------------------
// Call-edge extraction
// -----------------------------------------------------------------------------

/// Require binding: local constant name → dotted qname prefix.
#[derive(Debug, Clone)]
struct RequireBinding {
    /// Constant name as used in code, e.g. `PaymentsClient`.
    constant: String,
    /// Dotted qname prefix for the required file, e.g. `payments.client`.
    qname_prefix: String,
}

fn parse_requires(source: &str) -> Vec<RequireBinding> {
    let mut out = Vec::new();
    for line in source.lines() {
        let t = line.trim();
        // require 'payments/client' or require_relative '../payments/client'
        for kw in ["require ", "require_relative "] {
            if let Some(rest) = t.strip_prefix(kw) {
                let path = rest
                    .trim()
                    .trim_matches(|c| c == '"' || c == '\'')
                    .trim_start_matches("../");
                // Convert path to dotted prefix and derive a constant name
                let prefix = path.replace('/', ".");
                // Guess the constant: last segment, CamelCase
                let constant = path
                    .rsplit('/')
                    .next()
                    .unwrap_or(path)
                    .split('_')
                    .map(|w| {
                        let mut chars = w.chars();
                        match chars.next() {
                            None => String::new(),
                            Some(c) => c.to_uppercase().to_string() + chars.as_str(),
                        }
                    })
                    .collect::<String>();
                if !constant.is_empty() {
                    out.push(RequireBinding {
                        constant,
                        qname_prefix: prefix,
                    });
                }
            }
        }
    }
    out
}

fn enclosing_type_qname(qname: &str, known: &HashSet<&str>) -> Option<String> {
    let idx = qname.rfind('.')?;
    let parent = &qname[..idx];
    if known.contains(parent) {
        Some(parent.to_string())
    } else {
        None
    }
}

fn collect_calls(
    node: Node<'_>,
    src: &[u8],
    sym: &ParsedSymbol,
    by_simple: &HashMap<String, String>,
    known: &HashSet<&str>,
    requires: &[RequireBinding],
    workspace: &WorkspaceSymbols,
    enclosing_type: Option<&str>,
    edges: &mut HashSet<CallEdge>,
) {
    if node.kind() == "call" {
        // receiver.method or bare method
        let receiver_node = child_by_field(node, "receiver");
        let method_node = child_by_field(node, "method");

        let method_text = method_node.map(|n| node_text(n, src)).unwrap_or("");
        let receiver_text = receiver_node.map(|n| node_text(n, src)).unwrap_or("");

        if !method_text.is_empty() {
            let callee = if receiver_text.is_empty() {
                // Bare call
                if let Some(et) = enclosing_type {
                    let q = format!("{}.{}", et, method_text);
                    if known.contains(q.as_str()) {
                        Some(q)
                    } else {
                        by_simple.get(method_text).cloned()
                    }
                } else {
                    by_simple.get(method_text).cloned()
                }
            } else {
                // Qualified: check requires for the receiver constant
                let req = requires.iter().find(|r| r.constant == receiver_text);
                if let Some(binding) = req {
                    let q = format!("{}.{}", binding.qname_prefix, method_text);
                    if known.contains(q.as_str()) || workspace.contains(&q) {
                        Some(q)
                    } else {
                        None
                    }
                } else {
                    // Try known workspace symbols
                    let q = format!("{}.{}", receiver_text, method_text);
                    if known.contains(q.as_str()) || workspace.contains(&q) {
                        Some(q)
                    } else {
                        None
                    }
                }
            };

            if let Some(callee_qname) = callee {
                if callee_qname != sym.qname {
                    edges.insert(CallEdge {
                        caller_qname: sym.qname.clone(),
                        callee_qname,
                    });
                }
            }
        }
    }

    for i in 0..node.child_count() {
        collect_calls(
            node.child(i).unwrap(),
            src,
            sym,
            by_simple,
            known,
            requires,
            workspace,
            enclosing_type,
            edges,
        );
    }
}

fn extract_call_edges_impl(
    file: &str,
    source: &str,
    symbols: &[ParsedSymbol],
    workspace: &WorkspaceSymbols,
) -> Vec<CallEdge> {
    let _ = file;
    let known: HashSet<&str> = symbols.iter().map(|s| s.qname.as_str()).collect();

    let mut by_simple: HashMap<String, String> = HashMap::new();
    for s in symbols {
        let simple = s.qname.rsplit('.').next().unwrap_or(&s.qname).to_string();
        by_simple.entry(simple).or_insert_with(|| s.qname.clone());
    }

    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_ruby::LANGUAGE.into())
        .is_err()
    {
        return Vec::new();
    }

    let requires = parse_requires(source);
    let mut edges: HashSet<CallEdge> = HashSet::new();

    for sym in symbols {
        if !matches!(sym.kind, SymbolKind::Function | SymbolKind::Method) {
            continue;
        }
        let src_bytes = sym.body.as_bytes();
        let tree = match parser.parse(src_bytes, None) {
            Some(t) => t,
            None => continue,
        };
        let enclosing_type = enclosing_type_qname(&sym.qname, &known);
        collect_calls(
            tree.root_node(),
            src_bytes,
            sym,
            &by_simple,
            &known,
            &requires,
            workspace,
            enclosing_type.as_deref(),
            &mut edges,
        );
    }

    let mut out: Vec<CallEdge> = edges.into_iter().collect();
    out.sort_by(|a, b| {
        a.caller_qname
            .cmp(&b.caller_qname)
            .then_with(|| a.callee_qname.cmp(&b.callee_qname))
    });
    out
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use agentstatedeveloper_core::adapter::{LanguageAdapter, WorkspaceSymbols};

    fn adapter() -> RubyAdapter {
        RubyAdapter::new()
    }

    #[test]
    fn parses_module_class_method_singleton() {
        let src = r#"
module Payments
  class PaymentService
    def charge(customer_id, amount)
      puts "charging #{amount}"
    end

    def self.create_client
      new
    end
  end
end
"#;
        let syms = adapter()
            .parse_symbols("payments/payment_service.rb", src)
            .unwrap();
        let qnames: Vec<&str> = syms.iter().map(|s| s.qname.as_str()).collect();
        assert!(
            qnames.contains(&"payments.payment_service.Payments"),
            "{qnames:?}"
        );
        assert!(
            qnames.contains(&"payments.payment_service.Payments.PaymentService"),
            "{qnames:?}"
        );
        assert!(
            qnames.contains(&"payments.payment_service.Payments.PaymentService.charge"),
            "{qnames:?}"
        );
        assert!(
            qnames.contains(&"payments.payment_service.Payments.PaymentService.create_client"),
            "{qnames:?}"
        );
    }

    #[test]
    fn file_prefix_strips_rb_extension() {
        // lib/ anchor — stable for gem convention
        assert_eq!(file_qname_prefix("lib/myapp/parser.rb"), "myapp.parser");
        assert_eq!(file_qname_prefix("gems/foo/lib/foo/bar.rb"), "foo.bar");
        assert_eq!(file_qname_prefix("./lib/helpers.rb"), "helpers");
        // no lib segment — full relative path (Rails app/ or bare files)
        assert_eq!(file_qname_prefix("app/models/user.rb"), "app.models.user");
        assert_eq!(file_qname_prefix("charge.rb"), "charge");
    }

    #[test]
    fn strip_lib_prefix_variants() {
        assert_eq!(strip_lib_prefix("lib/foo/bar.rb"), "foo/bar.rb");
        assert_eq!(strip_lib_prefix("gems/foo/lib/foo.rb"), "foo.rb");
        assert_eq!(strip_lib_prefix("app/models/user.rb"), "app/models/user.rb");
    }

    #[test]
    fn infers_fs_read_and_net_out() {
        let src = r#"
class Fetcher
  def fetch
    data = File.read("/tmp/config.yml")
    response = HTTParty.get("https://api.example.com/v1/data")
    data
  end
end
"#;
        let syms = adapter().parse_symbols("fetcher.rb", src).unwrap();
        let fetch = syms.iter().find(|s| s.qname.ends_with(".fetch")).unwrap();
        let effs = adapter().infer_effects("", fetch);
        let cats: Vec<_> = effs.iter().map(|e| &e.effect).collect();
        assert!(cats.contains(&&EffectCategory::IoFsRead), "{cats:?}");
        assert!(cats.contains(&&EffectCategory::IoNetOut), "{cats:?}");
    }

    #[test]
    fn infers_db_and_env() {
        let src = r#"
class UserService
  def find_user(id)
    db_url = ENV["DATABASE_URL"]
    User.find(id)
  end

  def create_user(attrs)
    User.create(attrs)
  end
end
"#;
        let syms = adapter().parse_symbols("user_service.rb", src).unwrap();
        let find = syms
            .iter()
            .find(|s| s.qname.ends_with(".find_user"))
            .unwrap();
        let create = syms
            .iter()
            .find(|s| s.qname.ends_with(".create_user"))
            .unwrap();
        let find_effs = adapter().infer_effects("", find);
        let create_effs = adapter().infer_effects("", create);
        assert!(
            find_effs
                .iter()
                .any(|e| e.effect == EffectCategory::IoDbRead)
        );
        assert!(
            find_effs
                .iter()
                .any(|e| e.effect == EffectCategory::EnvRead)
        );
        assert!(
            create_effs
                .iter()
                .any(|e| e.effect == EffectCategory::IoDbWrite)
        );

        // Check env var extraction
        let env_eff = find_effs
            .iter()
            .find(|e| e.effect == EffectCategory::EnvRead)
            .unwrap();
        if let Some(vars) = env_eff.qualifiers.get("vars") {
            let vars: Vec<&str> = vars
                .as_array()
                .unwrap()
                .iter()
                .map(|v| v.as_str().unwrap())
                .collect();
            assert!(vars.contains(&"DATABASE_URL"), "{vars:?}");
        }
    }

    #[test]
    fn empty_when_no_patterns() {
        let src = r#"
class MathHelper
  def add(a, b)
    a + b
  end
end
"#;
        let syms = adapter().parse_symbols("math.rb", src).unwrap();
        let add = syms.iter().find(|s| s.qname.ends_with(".add")).unwrap();
        let effs = adapter().infer_effects("", add);
        assert!(effs.is_empty(), "{effs:?}");
    }

    #[test]
    fn extracts_intra_class_call_edges() {
        let src = r#"
class OrderService
  def place_order(order)
    charge(order.customer_id, order.total)
  end

  def charge(customer_id, amount)
    # process
  end
end
"#;
        let ws = WorkspaceSymbols {
            qnames: HashSet::new(),
            kinds: HashMap::new(),
            ..Default::default()
        };
        let syms = adapter().parse_symbols("order_service.rb", src).unwrap();
        let edges = adapter().extract_call_edges("order_service.rb", src, &syms, &ws);
        let found = edges.iter().any(|e| {
            e.caller_qname.ends_with(".place_order") && e.callee_qname.ends_with(".charge")
        });
        assert!(found, "expected intra-class edge; got: {edges:?}");
    }
}

#[cfg(test)]
mod service_endpoint_tests {
    use super::*;
    use agentstatedeveloper_core::adapter::LanguageAdapter;

    fn detect(src: &str) -> Vec<DetectedEndpoint> {
        let a = RubyAdapter;
        let symbols = a.parse_symbols("app.rb", src).unwrap();
        a.infer_service_endpoints("app.rb", src, &symbols)
    }
    fn inbound(eps: &[DetectedEndpoint]) -> Vec<&DetectedEndpoint> {
        eps.iter()
            .filter(|e| e.direction == Direction::Inbound)
            .collect()
    }
    fn outbound(eps: &[DetectedEndpoint]) -> Vec<&DetectedEndpoint> {
        eps.iter()
            .filter(|e| e.direction == Direction::Outbound)
            .collect()
    }

    #[test]
    fn sinatra_route_inbound() {
        // Sinatra routes live inside the app class, so they attribute to it.
        let sinatra = "class App < Sinatra::Base\n  get '/users/:id' do\n    body\n  end\nend\n";
        let eps = detect(sinatra);
        assert_eq!(inbound(&eps)[0].contract, "http:GET /users/{}", "{eps:?}");
    }

    #[test]
    fn top_level_route_without_enclosing_symbol_is_dropped() {
        // Rails routes.rb routes sit at top level (no class/def), so there's no
        // symbol to attribute them to — a known limitation.
        let rails = "Rails.application.routes.draw do\n  post '/charge', to: 'x#y'\nend\n";
        assert!(inbound(&detect(rails)).is_empty(), "{:?}", detect(rails));
    }

    #[test]
    fn method_call_get_is_not_a_route() {
        // `obj.get('/x')` is a method call, not a route DSL line.
        let src = "def f\n  cache.get('/x')\n  h.delete('key')\nend\n";
        assert!(inbound(&detect(src)).is_empty(), "{:?}", detect(src));
    }

    #[test]
    fn restclient_and_httparty_clients() {
        let src = "def call\n  RestClient.get('https://users.svc/users/:id')\n  HTTParty.post('/charge', body)\nend\n";
        let eps = detect(src);
        let mut got: Vec<String> = outbound(&eps).iter().map(|e| e.contract.clone()).collect();
        got.sort();
        assert_eq!(
            got,
            vec![
                "http:GET /users/{}".to_string(),
                "http:POST /charge".to_string()
            ]
        );
    }

    #[test]
    fn interpolated_url_is_skipped() {
        let src = "def call\n  RestClient.get(\"#{base}/users\")\nend\n";
        assert!(outbound(&detect(src)).is_empty(), "{:?}", detect(src));
    }
}