repotoire 0.9.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Missing Await Detector
//!
//! Graph-enhanced detection of async calls without await:
//! - Uses graph to identify async functions defined in the codebase
//! - Traces calls to known async functions across file boundaries
//! - Checks for Promise chain patterns (.then, .catch)

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphQueryExt;
use crate::models::{deterministic_finding_id, Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::LazyLock;
use tracing::info;

static ASYNC_CALL: LazyLock<Regex> = LazyLock::new(|| {
    // Only match clearly async I/O patterns — NOT generic method calls
    Regex::new(r"(?i)\b(fetch\(|axios\.\w+\(|\.\bjson\(\)|\.\btext\(\)|async_\w+\(|aio\w+\.|\.\bquery\(|\.\bexecute\(|\.\bconnect\(|\.\bsend\(|fs\.promises\.|fsPromises\.)")
            .expect("valid regex")
});

/// Bare method names that collide with Map/Set/Array/Promise/string built-ins.
/// When the bare `node_name` of a graph-async function matches one of these,
/// we skip the graph-async heuristic entirely to avoid false positives on
/// synchronous calls like `someMap.get(key)`, `arr.set(i, v)`, etc.
static BUILTIN_METHOD_BLOCKLIST: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
    [
        // Map / Set / WeakMap / WeakSet
        "get",
        "set",
        "has",
        "delete",
        "clear",
        "add",
        "size",
        // Iteration
        "keys",
        "values",
        "entries",
        "forEach",
        // Array higher-order
        "map",
        "filter",
        "reduce",
        "reduceRight",
        "find",
        "findIndex",
        "some",
        "every",
        "flat",
        "flatMap",
        // Array mutation / access
        "push",
        "pop",
        "shift",
        "unshift",
        "splice",
        "fill",
        "sort",
        "reverse",
        "at",
        "indexOf",
        "lastIndexOf",
        "includes",
        // String / Array shared
        "slice",
        "concat",
        "join",
        "toString",
        "valueOf",
        // Promise chain
        "then",
        "catch",
        "finally",
        // Async iteration
        "next",
        "done",
        "return",
    ]
    .into()
});

/// Return `true` if `func_name` (a bare name from `node_name()`) must be
/// excluded from the graph-async heuristic because it collides with a common
/// built-in method name.
fn is_builtin_collision(func_name: &str) -> bool {
    // node_name() returns the bare name, but just in case a qualified form
    // slips through (e.g. "Foo::get"), extract the last component.
    let bare = func_name.rsplit(['.', ':']).next().unwrap_or(func_name);
    BUILTIN_METHOD_BLOCKLIST.contains(bare)
}

/// Return `true` if `line` contains a call to `func_name` that is not merely
/// a substring of a longer identifier.
///
/// Rules:
///  - The character immediately *before* the occurrence of `func_name` must
///    not be an identifier character (`[A-Za-z0-9_$]`), so `getData(` is not
///    matched by `func == "get"`.
///  - Immediately *after* `func_name` (skipping spaces) must be `(`.
fn line_calls_func(line: &str, func_name: &str) -> bool {
    let bytes = line.as_bytes();
    let fname = func_name.as_bytes();
    let flen = fname.len();
    if flen == 0 {
        return false;
    }
    let mut start = 0usize;
    while start + flen <= bytes.len() {
        // Find next occurrence of func_name in the remaining slice.
        let Some(rel) = bytes[start..].windows(flen).position(|w| w == fname) else {
            break;
        };
        let pos = start + rel;

        // Check the character before is not an identifier char.
        let pre_ok = if pos == 0 {
            true
        } else {
            let c = bytes[pos - 1] as char;
            !c.is_ascii_alphanumeric() && c != '_' && c != '$'
        };

        // Check that what follows (after optional spaces) is `(`.
        let after_pos = pos + flen;
        let post_ok = bytes[after_pos..]
            .iter()
            .copied()
            .find(|&b| b != b' ' && b != b'\t')
            == Some(b'(');

        if pre_ok && post_ok {
            return true;
        }
        start = pos + 1;
    }
    false
}

pub struct MissingAwaitDetector {
    #[allow(dead_code)] // Part of detector pattern, used for file scanning
    repository_path: PathBuf,
    max_findings: usize,
}

impl MissingAwaitDetector {
    crate::detectors::detector_new!(50);

    /// Identify async functions from the graph — only trust the is_async flag
    fn find_async_functions(graph: &dyn crate::graph::GraphQuery) -> HashSet<String> {
        let i = graph.interner();
        let mut async_funcs = HashSet::new();
        for func in graph.get_functions_shared().iter() {
            if func.is_async() {
                async_funcs.insert(func.node_name(i).to_string());
            }
        }
        async_funcs
    }

    /// Check if a line is an async function/method DECLARATION (not a call).
    /// Matches patterns like `async function foo()`, `const foo = async () =>`,
    /// `export async function`, and Python's `async def`.
    fn is_async_declaration(line: &str) -> bool {
        let trimmed = line.trim();
        trimmed.contains("async function ")
            || trimmed.contains("async def ")
            || trimmed.contains("= async (")
            || trimmed.contains("= async function")
            || (trimmed.starts_with("async ") && trimmed.contains('(') && trimmed.contains('{'))
            || (trimmed.starts_with("export async "))
    }

    /// Check if the function body actually contains await (it's a real async function)
    fn function_body_has_await(lines: &[&str], start: usize, ext: &str) -> bool {
        let mut brace_depth = 0i32;
        let mut found_open = false;
        for line in &lines[start..] {
            if !found_open {
                if line.contains('{') || (ext == "py" && line.contains(':')) {
                    found_open = true;
                    // Count all braces on the opening line (e.g. `async function foo() {`)
                    brace_depth =
                        line.matches('{').count() as i32 - line.matches('}').count() as i32;
                    if line.contains("await ") {
                        return true;
                    }
                    continue;
                }
                continue;
            }
            brace_depth += line.matches('{').count() as i32;
            brace_depth -= line.matches('}').count() as i32;
            if line.contains("await ") {
                return true;
            }
            if ext != "py" && brace_depth <= 0 {
                break;
            }
            // Python: stop at dedent
            if ext == "py" {
                let indent = line.len() - line.trim_start().len();
                let start_indent = lines[start].len() - lines[start].trim_start().len();
                if !line.trim().is_empty()
                    && indent <= start_indent
                    && !line.trim().starts_with('#')
                {
                    break;
                }
            }
        }
        false
    }
}

impl Detector for MissingAwaitDetector {
    fn name(&self) -> &'static str {
        "missing-await"
    }
    fn description(&self) -> &'static str {
        "Detects async calls without await"
    }

    fn requires_graph(&self) -> bool {
        true
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &["py", "js", "ts", "jsx", "tsx"]
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        let gi = graph.interner();
        let _i = graph.interner();
        let mut findings = vec![];
        let known_async_funcs = Self::find_async_functions(graph);

        // Pre-build file→functions map once (avoid calling get_functions() per file)
        let all_functions = graph.get_functions_shared();
        let mut funcs_by_file: std::collections::HashMap<&str, Vec<&crate::graph::CodeNode>> =
            std::collections::HashMap::new();
        for func in all_functions.iter() {
            funcs_by_file.entry(func.path(gi)).or_default().push(func);
        }

        for path in files.files_with_extensions(&["js", "ts", "jsx", "tsx", "py"]) {
            if findings.len() >= self.max_findings {
                break;
            }

            let path_str = path.to_string_lossy().to_string();
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

            if crate::detectors::content_classifier::is_non_production_path(&path_str) {
                continue;
            }

            let Some(content) = files.content(path) else {
                continue;
            };
            let lines: Vec<&str> = content.lines().collect();

            // Find async function boundaries using brace counting
            // We need to know: (a) are we inside an async function? (b) which one?
            let mut async_ranges: Vec<(usize, usize, String)> = Vec::new(); // (start, end, name)
                                                                            // Use pre-built file→functions map instead of calling get_functions() per file
            let file_funcs: Vec<&&crate::graph::CodeNode> = funcs_by_file
                .get(path_str.as_str())
                .map(|v| v.iter().collect())
                .unwrap_or_default();

            for (i, line) in lines.iter().enumerate() {
                let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
                if crate::detectors::is_line_suppressed(line, prev_line) {
                    continue;
                }

                if !Self::is_async_declaration(line) {
                    continue;
                }

                // Find the function name from pre-fetched list
                let func_name = file_funcs
                    .iter()
                    .find(|f| f.line_start <= (i + 1) as u32 && f.line_end >= (i + 1) as u32)
                    .map(|f| f.node_name(gi).to_string())
                    .unwrap_or_default();

                // Only flag if the function body actually uses await
                // (an async function that never awaits is fine — it just returns a Promise)
                if !Self::function_body_has_await(&lines, i, ext) {
                    continue;
                }

                // Find the function end via brace counting
                let mut depth = 0i32;
                let mut end = i;
                for (j, l) in lines[i..].iter().enumerate() {
                    depth += l.matches('{').count() as i32;
                    depth -= l.matches('}').count() as i32;
                    if depth <= 0 && j > 0 {
                        end = i + j;
                        break;
                    }
                }
                if end == i {
                    end = (i + 50).min(lines.len() - 1);
                } // fallback

                async_ranges.push((i, end, func_name));
            }

            // Now scan for un-awaited async calls within async function bodies
            for (start, end, func_name) in &async_ranges {
                for i in (*start + 1)..=*end {
                    let Some(line) = lines.get(i) else { continue };
                    let trimmed = line.trim();

                    // Skip blank lines, comments, declarations
                    if trimmed.is_empty()
                        || trimmed.starts_with("//")
                        || trimmed.starts_with("/*")
                        || trimmed.starts_with('*')
                        || Self::is_async_declaration(line)
                    {
                        continue;
                    }

                    // Skip React event handler assignments
                    {
                        let ll = trimmed.to_lowercase();
                        if ll.contains("onsubmit=")
                            || ll.contains("onclick=")
                            || ll.contains("onchange=")
                            || ll.contains("onpress=")
                            || ll.contains("onblur=")
                            || ll.contains("onfocus=")
                        {
                            continue;
                        }
                    }

                    // Skip React Query / hook options
                    if trimmed.contains("useMutation(")
                        || trimmed.contains("useQuery(")
                        || trimmed.contains("queryFn")
                        || trimmed.contains("mutationFn")
                    {
                        continue;
                    }

                    let has_async_call = ASYNC_CALL.is_match(line);
                    let calls_known_async = known_async_funcs.iter().any(|func| {
                        // Skip built-in method names (get, set, has, map, filter, …) that
                        // collide with Map/Set/Array/Promise APIs — these are synchronous and
                        // flagging them produces false positives (e.g. `someMap.get(key)`).
                        if is_builtin_collision(func) {
                            return false;
                        }
                        // Require a precise call: `func` must not be preceded by an identifier
                        // char and must be followed (ignoring spaces) by `(`.  This prevents
                        // `getData(` from matching `func == "get"`.
                        line_calls_func(line, func)
                            && !line.contains(&format!("async {}", func)) // skip declarations
                            && !line.contains(&format!("function {}", func))
                        // skip declarations
                    });

                    if !has_async_call && !calls_known_async {
                        continue;
                    }

                    // Check if properly awaited
                    let next_line = lines.get(i + 1).copied().unwrap_or("");
                    let prev_line = if i > 0 {
                        lines.get(i - 1).copied().unwrap_or("")
                    } else {
                        ""
                    };

                    let is_awaited = line.contains("await ")
                        || line.contains(".then(")
                        || line.contains("Promise.")
                        || (line.contains("return ") && (has_async_call || calls_known_async))
                        // Multi-line: await on next line
                        || next_line.trim().starts_with("await ")
                        || next_line.trim().starts_with(".then(")
                        // Previous line started a chain: const x = await \n  fetch(...)
                        || prev_line.contains("await");

                    // Fire-and-forget patterns
                    let is_fire_and_forget = trimmed.starts_with("void ")
                        || line.contains(".catch(")
                        || line.contains("// fire-and-forget")
                        || line.contains("// fire and forget")
                        || line.contains("// best-effort")
                        || line.contains("// non-blocking");

                    // Telemetry — inherently fire-and-forget
                    let is_telemetry = {
                        let ll = line.to_lowercase();
                        ll.contains("track(")
                            || ll.contains("telemetry")
                            || ll.contains("analytics")
                            || ll.contains("log_event")
                            || ll.contains("send_event")
                            || ll.contains("metric")
                    };

                    if is_awaited || is_fire_and_forget || is_telemetry {
                        continue;
                    }

                    let severity = if calls_known_async {
                        Severity::High
                    } else {
                        Severity::Medium
                    };

                    let mut notes = Vec::new();
                    if !func_name.is_empty() {
                        notes.push(format!("📦 In async function: `{}`", func_name));
                    }
                    if calls_known_async {
                        notes.push(
                            "🔍 Calls a function defined as async in this codebase".to_string(),
                        );
                    }
                    let context_notes = if notes.is_empty() {
                        String::new()
                    } else {
                        format!("\n\n**Analysis:**\n{}", notes.join("\n"))
                    };

                    findings.push(Finding {
                        id: String::new(),
                        detector: "MissingAwaitDetector".to_string(),
                        severity,
                        title: "Async call without await".to_string(),
                        description: format!(
                            "Async function called without await - returns Promise/coroutine, not the actual value.{}",
                            context_notes
                        ),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some((i + 1) as u32),
                        line_end: Some((i + 1) as u32),
                        suggested_fix: Some("Add `await` before the async call.".to_string()),
                        estimated_effort: Some("2 minutes".to_string()),
                        category: Some("bug-risk".to_string()),
                        cwe_id: None,
                        why_it_matters: Some(
                            "Without await, you get a Promise object instead of the actual result.".to_string()
                        ),
                        ..Default::default()
                    });
                }
            }
        }

        info!("MissingAwaitDetector found {} findings", findings.len());
        Ok(findings)
    }
}

impl crate::detectors::RegisteredDetector for MissingAwaitDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }

    fn max_tier() -> crate::models::Tier {
        crate::models::Tier::Deep
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builder::GraphBuilder;
    use crate::graph::store_models::{CodeNode, FLAG_IS_ASYNC};

    #[test]
    fn test_detects_fetch_without_await() {
        let store = GraphBuilder::new().freeze();
        let detector = MissingAwaitDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("api.js", "async function loadData() {\n  const config = \"default\";\n  fetch(\"/api/data\");\n  const result = await process(config);\n  return result;\n}\n")],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect fetch() without await in async function"
        );
    }

    #[test]
    fn test_no_finding_when_awaited() {
        let store = GraphBuilder::new().freeze();
        let detector = MissingAwaitDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("api_good.js", "async function loadData() {\n  const res = await fetch(\"/api/data\");\n  const data = await res.json();\n  return data;\n}\n")],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag properly awaited calls, got: {:?}",
            findings
        );
    }

    /// Regression: a codebase has `async get(k) {...}` in some cache class.
    /// That adds "get" to `known_async_funcs`.  Lines like `someMap.get(key)`
    /// inside an async function body must NOT be flagged.
    #[test]
    fn test_no_false_positive_map_get() {
        // Build a graph with an async function named "get" (simulating a cache
        // class method `async get(k) {...}`).
        let mut builder = GraphBuilder::new();
        let mut async_get = CodeNode::function("get", "cache.ts");
        async_get.set_flag(FLAG_IS_ASYNC);
        builder.add_node(async_get);
        let store = builder.freeze();

        let detector = MissingAwaitDetector::new("/mock/repo");
        // The TS file has:
        //   - `perStaff.get(lead.assignedToStaffId)` — Map.get, synchronous, must NOT flag
        //   - `await db.query(sql)` — properly awaited, must NOT flag
        //   - `el.getElementById(id)` — unrelated sync call, must NOT flag
        let src = concat!(
            "async function processLeads(perStaff, clerkUserMap) {\n",
            "  const entry = perStaff.get(lead.assignedToStaffId) ?? {};\n",
            "  const cu = clerkUserMap.get(s.clerkUserId);\n",
            "  const rows = await db.query(\"SELECT 1\");\n",
            "  const el = document.getElementById(\"root\");\n",
            "  return entry;\n",
            "}\n"
        );
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("staff.ts", src)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // None of these lines should be flagged as missing-await.
        assert!(
            findings.is_empty(),
            "Map.get / getElementById / awaited db.query should produce no findings, got: {:?}",
            findings
        );
    }

    /// The graph has a distinctively-named async function `loadUserProfile`.
    /// A line `loadUserProfile(id)` inside an async function body (no await)
    /// MUST be flagged.
    ///
    /// Note: the outer async function must itself contain at least one `await`
    /// for `function_body_has_await` to include it in `async_ranges`; the
    /// un-awaited call to `loadUserProfile` on a *separate* line is the finding.
    #[test]
    fn test_flags_distinctive_async_call_without_await() {
        let mut builder = GraphBuilder::new();
        let mut async_fn = CodeNode::function("loadUserProfile", "users.ts");
        async_fn.set_flag(FLAG_IS_ASYNC);
        builder.add_node(async_fn);
        let store = builder.freeze();

        let detector = MissingAwaitDetector::new("/mock/repo");
        // The outer function uses `await` (satisfying function_body_has_await).
        // `loadUserProfile(id)` is separated from the `await` line by a plain
        // assignment so that `prev_line.contains("await")` does NOT fire on it.
        let src = concat!(
            "async function renderUser(id) {\n",
            "  const data = await fetch(\"/api\");\n", // line 2 — awaited, no finding
            "  const name = data.name;\n",             // line 3 — plain, no await
            "  loadUserProfile(id);\n",                // line 4 — missing await, flagged
            "  return name;\n",
            "}\n"
        );
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("render.ts", src)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // loadUserProfile(id) on line 4 must be flagged.
        let has_load_finding = findings.iter().any(|f| f.line_start == Some(4));
        assert!(
            has_load_finding,
            "loadUserProfile(id) without await (line 4) should be flagged, got: {:?}",
            findings
        );
    }

    /// Ensure `getData(` is NOT matched when `func == "get"` is in the async set
    /// (i.e., a longer identifier that merely starts with the blocklisted name
    /// must NOT trigger through the `line_calls_func` path either — but `getData`
    /// is not in the blocklist, so the real guard here is the identifier-boundary
    /// check in `line_calls_func`).
    #[test]
    fn test_no_false_positive_get_data_prefix() {
        let mut builder = GraphBuilder::new();
        // "get" is async (blocklisted) — should be skipped entirely.
        let mut async_get = CodeNode::function("get", "store.ts");
        async_get.set_flag(FLAG_IS_ASYNC);
        builder.add_node(async_get);
        let store = builder.freeze();

        let detector = MissingAwaitDetector::new("/mock/repo");
        let src = concat!(
            "async function process() {\n",
            "  const val = getData(key);\n", // getData is synchronous here
            "  return val;\n",
            "}\n"
        );
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("proc.ts", src)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // "get" is blocklisted → no finding via graph path; ASYNC_CALL regex
        // won't match getData either.
        assert!(
            findings.is_empty(),
            "getData() must not be flagged via graph-async path for func=='get', got: {:?}",
            findings
        );
    }
}