mati 0.1.1

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
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
//! Ruby tree-sitter parser — entry points, requires, TODOs.
//!
//! Entry points: `method` and `singleton_method` — filtered by `_` prefix
//! (Python-style convention for internal methods; Ruby's `private`/`protected`
//! are runtime method-call modifiers not visible in the AST as named nodes).
//! Imports: `require` and `require_relative` are method calls, not AST nodes.
//! Detected via `(call method: (identifier) @call_name)` with dispatch filtering.
//! Single `comment` node type.

use std::cell::RefCell;
use std::sync::LazyLock;

use anyhow::Result;

use super::{extract_todo, normalize_doc, ImportKind, ImportStatement, StaticFileAnalysis};
use crate::analysis::walker::{Language, WalkedFile};

// ── Static handles ────────────────────────────────────────────────────────────

static RUBY_LANGUAGE: LazyLock<tree_sitter::Language> =
    LazyLock::new(|| tree_sitter_ruby::LANGUAGE.into());

const RUBY_QUERY_SRC: &str = r#"
  (method name: (_) @method_name)
  (singleton_method name: (_) @method_name)

  (class name: (_) @type_name)
  (module name: (_) @type_name)

  (call method: (identifier) @call_name arguments: (argument_list (string (string_content) @call_arg)))

  ;; Class inheritance: class Foo < Bar
  (class superclass: (superclass (constant) @superclass))
  (class superclass: (superclass (scope_resolution) @superclass))

  ;; include/extend/prepend with constant arguments
  (call method: (identifier) @mixin_call arguments: (argument_list (constant) @mixin_arg))
  (call method: (identifier) @mixin_call arguments: (argument_list (scope_resolution) @mixin_arg))

  (if) @branch
  (unless) @branch
  (while) @branch
  (until) @branch
  (for) @branch
  (case) @branch
  (begin) @branch
  (if_modifier) @branch
  (unless_modifier) @branch
  (while_modifier) @branch
  (until_modifier) @branch
  (rescue) @branch
  (rescue_modifier) @branch

  (comment) @comment
"#;

static RUBY_QUERY: LazyLock<tree_sitter::Query> = LazyLock::new(|| {
    tree_sitter::Query::new(&RUBY_LANGUAGE, RUBY_QUERY_SRC).expect("parser/ruby: invalid query")
});

static RUBY_CAPTURES: LazyLock<RubyCaptures> = LazyLock::new(|| RubyCaptures::new(&RUBY_QUERY));

thread_local! {
    static RUBY_PARSER: RefCell<tree_sitter::Parser> = RefCell::new({
        let mut p = tree_sitter::Parser::new();
        p.set_language(&RUBY_LANGUAGE).expect("parser/ruby: grammar load failed");
        p
    });
}

// ── Capture indices ───────────────────────────────────────────────────────────

struct RubyCaptures {
    method_name: u32,
    type_name: u32,
    call_name: u32,
    call_arg: u32,
    superclass: u32,
    mixin_call: u32,
    mixin_arg: u32,
    branch: u32,
    comment: u32,
}

impl RubyCaptures {
    fn new(query: &tree_sitter::Query) -> Self {
        let idx = |name: &str| {
            query
                .capture_index_for_name(name)
                .unwrap_or_else(|| panic!("parser/ruby: query missing @{name}"))
        };
        Self {
            method_name: idx("method_name"),
            type_name: idx("type_name"),
            call_name: idx("call_name"),
            call_arg: idx("call_arg"),
            superclass: idx("superclass"),
            mixin_call: idx("mixin_call"),
            mixin_arg: idx("mixin_arg"),
            branch: idx("branch"),
            comment: idx("comment"),
        }
    }
}

// ── Built-in constants (never project-defined) ──────────────────────────────

/// Ruby built-in classes/modules that should never produce Inherits or Includes
/// imports — they are part of the language runtime, not project files.
const RUBY_BUILTINS: &[&str] = &[
    "Object",
    "BasicObject",
    "Kernel",
    "Class",
    "Module",
    "Comparable",
    "Enumerable",
    "Struct",
];

/// Extract the top-level (leftmost) constant from a possibly namespaced name.
/// `"Foo::Bar::Baz"` → `"Foo"`, `"Foo"` → `"Foo"`.
fn top_level_name(name: &str) -> &str {
    name.split("::").next().unwrap_or(name)
}

// ── Parser ────────────────────────────────────────────────────────────────────

pub(super) fn parse_ruby(file: &WalkedFile, source: &str) -> Result<StaticFileAnalysis> {
    let tree = RUBY_PARSER.with(|cell| cell.borrow_mut().parse(source.as_bytes(), None));

    let tree = match tree {
        Some(t) => t,
        None => {
            tracing::warn!("parser/ruby: tree-sitter failed on {}", file.rel_path);
            return Ok(StaticFileAnalysis::empty(file));
        }
    };

    let query = &*RUBY_QUERY;
    let ci = &*RUBY_CAPTURES;
    let src = source.as_bytes();

    let mut out = StaticFileAnalysis {
        path: file.rel_path.clone(),
        language: Language::Ruby,
        entry_points: Vec::with_capacity(16),
        exported_types: Vec::with_capacity(8),
        imports: Vec::with_capacity(16),
        todos: Vec::new(),
        unsafe_count: 0,
        unwrap_count: 0,
        panic_count: 0,
        branch_count: 0,
        module_doc: None,
        content_hash: None,
        line_count: 0,
    };

    let mut doc_lines: Vec<(usize, String)> = Vec::new();
    let mut cursor = tree_sitter::QueryCursor::new();
    for m in cursor.matches(query, tree.root_node(), src) {
        // For call-based require detection, we need both call_name and call_arg
        // from the same match.
        let mut match_call_name: Option<&str> = None;
        let mut match_call_arg: Option<&str> = None;

        // For include/extend/prepend detection.
        let mut match_mixin_call: Option<&str> = None;
        let mut match_mixin_args: Vec<(&str, u32)> = Vec::new();

        for capture in m.captures {
            let idx = capture.index;
            let node = capture.node;

            if idx == ci.branch {
                out.branch_count += 1;
            } else if idx == ci.method_name {
                if let Ok(name) = node.utf8_text(src) {
                    if !name.starts_with('_') {
                        out.entry_points.push(name.to_owned());
                    }
                }
            } else if idx == ci.type_name {
                if let Ok(name) = node.utf8_text(src) {
                    out.exported_types.push(name.to_owned());
                }
            } else if idx == ci.call_name {
                match_call_name = node.utf8_text(src).ok();
            } else if idx == ci.call_arg {
                match_call_arg = node.utf8_text(src).ok();
            } else if idx == ci.superclass {
                // Class inheritance: class Foo < Bar
                if let Ok(name) = node.utf8_text(src) {
                    let line = node.start_position().row as u32 + 1;
                    let base = top_level_name(name);
                    if !RUBY_BUILTINS.contains(&base) {
                        out.imports.push(ImportStatement::new(
                            name.to_owned(),
                            ImportKind::Inherits,
                            line,
                        ));
                    }
                }
            } else if idx == ci.mixin_call {
                match_mixin_call = node.utf8_text(src).ok();
            } else if idx == ci.mixin_arg {
                if let Ok(name) = node.utf8_text(src) {
                    let line = node.start_position().row as u32 + 1;
                    match_mixin_args.push((name, line));
                }
            } else if idx == ci.comment {
                if let Ok(text) = node.utf8_text(src) {
                    let row = node.start_position().row;
                    let line = row as u32 + 1;
                    if let Some(todo) = extract_todo(text, line) {
                        out.todos.push(todo);
                    }
                    // Capture file-top # comments as module doc.
                    if row < 10 {
                        let stripped = text.trim_start_matches('#').trim().to_string();
                        if !stripped.is_empty()
                            && !stripped.starts_with('!')
                            && !stripped.starts_with("frozen_string_literal")
                            && !stripped.starts_with("encoding:")
                        {
                            doc_lines.push((row, stripped));
                        }
                    }
                }
            }
        }

        // Process require/require_relative/require_dependency calls.
        if let (Some(name), Some(arg)) = (match_call_name, match_call_arg) {
            if name == "require" || name == "require_relative" || name == "require_dependency" {
                let line = m
                    .captures
                    .iter()
                    .find(|c| c.index == ci.call_name)
                    .map(|c| c.node.start_position().row as u32 + 1)
                    .unwrap_or(1);
                let kind = if name == "require_relative" {
                    ImportKind::Relative
                } else {
                    // Both require and require_dependency resolve against lib/ and autoload roots.
                    ImportKind::Normal
                };
                out.imports
                    .push(ImportStatement::new(arg.to_owned(), kind, line));
            }
        }

        // Process include/extend/prepend calls with constant arguments.
        if let Some(method) = match_mixin_call {
            if method == "include" || method == "extend" || method == "prepend" {
                for (arg, line) in match_mixin_args {
                    let base = top_level_name(arg);
                    if !RUBY_BUILTINS.contains(&base) {
                        out.imports.push(ImportStatement::new(
                            arg.to_owned(),
                            ImportKind::Includes,
                            line,
                        ));
                    }
                }
            }
        }
    }

    if !doc_lines.is_empty() {
        doc_lines.sort_by_key(|(r, _)| *r);
        let start_row = doc_lines[0].0;
        let contiguous: Vec<&str> = doc_lines
            .iter()
            .enumerate()
            .take_while(|(i, (r, _))| *r == start_row + i)
            .map(|(_, (_, text))| text.as_str())
            .collect();
        if !contiguous.is_empty() {
            out.module_doc = Some(normalize_doc(&contiguous.join(" ")));
        }
    }

    Ok(out)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::record::TodoKind;
    use tempfile::TempDir;

    fn make_file(dir: &TempDir, rel: &str, content: &str) -> WalkedFile {
        let abs = dir.path().join(rel);
        if let Some(parent) = abs.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(&abs, content).unwrap();
        WalkedFile {
            abs_path: abs,
            rel_path: rel.to_owned(),
            language: Language::Ruby,
            size_bytes: content.len() as u64,
            mtime_secs: 0,
        }
    }

    fn parse(dir: &TempDir, source: &str) -> StaticFileAnalysis {
        let f = make_file(dir, "test.rb", source);
        parse_ruby(&f, source).unwrap()
    }

    #[test]
    fn public_method_in_entry_points() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def hello\n  puts 'hi'\nend\n");
        assert!(a.entry_points.contains(&"hello".to_owned()));
    }

    #[test]
    fn underscore_prefixed_method_excluded() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def _internal\n  nil\nend\n");
        assert!(!a.entry_points.contains(&"_internal".to_owned()));
    }

    #[test]
    fn class_in_exported_types() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class MyService\nend\n");
        assert!(a.exported_types.contains(&"MyService".to_owned()));
    }

    #[test]
    fn module_in_exported_types() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "module Utils\nend\n");
        assert!(a.exported_types.contains(&"Utils".to_owned()));
    }

    #[test]
    fn require_captured() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "require 'json'\n");
        assert!(a.imports.iter().any(|i| i.path == "json"));
    }

    #[test]
    fn require_relative_captured() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "require_relative 'helpers/utils'\n");
        assert!(a.imports.iter().any(|i| i.path == "helpers/utils"));
    }

    #[test]
    fn todo_in_comment() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "# TODO: fix this\ndef f\nend\n");
        assert_eq!(a.todos.len(), 1);
        assert_eq!(a.todos[0].kind, TodoKind::Todo);
    }

    #[test]
    fn branch_if() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def f(x)\n  if x\n    1\n  end\nend\n");
        assert_eq!(a.branch_count, 1);
    }

    #[test]
    fn branch_unless() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def f(x)\n  unless x\n    1\n  end\nend\n");
        assert_eq!(a.branch_count, 1);
    }

    #[test]
    fn branch_case() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def f(x)\n  case x\n  when 1\n    'a'\n  end\nend\n");
        assert_eq!(a.branch_count, 1);
    }

    #[test]
    fn branch_rescue() {
        let dir = TempDir::new().unwrap();
        let a = parse(
            &dir,
            "def f\n  begin\n    1\n  rescue => e\n    0\n  end\nend\n",
        );
        // begin + rescue = 2 branches
        assert!(a.branch_count >= 2);
    }

    #[test]
    fn branch_if_modifier() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def f(x)\n  puts 'hi' if x\nend\n");
        assert_eq!(a.branch_count, 1);
    }

    #[test]
    fn empty_file() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "");
        assert!(a.entry_points.is_empty());
        assert!(a.imports.is_empty());
        assert_eq!(a.branch_count, 0);
    }

    #[test]
    fn no_rust_specific_fields_set() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "def f\nend\n");
        assert_eq!(a.unsafe_count, 0);
        assert_eq!(a.unwrap_count, 0);
        assert_eq!(a.panic_count, 0);
    }

    // ── Inheritance (Inherits) ────────────────────────────────────────────

    #[test]
    fn class_with_superclass_emits_inherits() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo < Bar\nend\n");
        let inherits: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Inherits)
            .collect();
        assert_eq!(inherits.len(), 1);
        assert_eq!(inherits[0].path, "Bar");
    }

    #[test]
    fn class_without_superclass_no_inherits() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo\nend\n");
        let inherits: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Inherits)
            .collect();
        assert!(inherits.is_empty());
    }

    #[test]
    fn class_with_namespaced_superclass() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo < MyApp::Bar\nend\n");
        let inherits: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Inherits)
            .collect();
        assert_eq!(inherits.len(), 1);
        assert_eq!(inherits[0].path, "MyApp::Bar");
    }

    #[test]
    fn builtin_superclass_skipped() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo < Object\nend\nclass Bar < Struct\nend\n");
        let inherits: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Inherits)
            .collect();
        assert!(inherits.is_empty());
    }

    // ── Module inclusion (Includes) ───────────────────────────────────────

    #[test]
    fn single_include_emits_includes() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo\n  include Bar\nend\n");
        let includes: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Includes)
            .collect();
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "Bar");
    }

    #[test]
    fn multiple_includes_emit_separately() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo\n  include Bar, Baz, Qux\nend\n");
        let includes: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Includes)
            .collect();
        assert_eq!(includes.len(), 3, "expected 3 includes, got {:?}", includes);
        let paths: Vec<&str> = includes.iter().map(|i| i.path.as_str()).collect();
        assert!(paths.contains(&"Bar"));
        assert!(paths.contains(&"Baz"));
        assert!(paths.contains(&"Qux"));
    }

    #[test]
    fn extend_and_prepend_also_emit_includes() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "class Foo\n  extend Bar\n  prepend Baz\nend\n");
        let includes: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Includes)
            .collect();
        assert_eq!(includes.len(), 2);
        let paths: Vec<&str> = includes.iter().map(|i| i.path.as_str()).collect();
        assert!(paths.contains(&"Bar"));
        assert!(paths.contains(&"Baz"));
    }

    #[test]
    fn builtin_module_include_skipped() {
        let dir = TempDir::new().unwrap();
        let a = parse(
            &dir,
            "class Foo\n  include Comparable\n  include Enumerable\nend\n",
        );
        let includes: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Includes)
            .collect();
        assert!(includes.is_empty());
    }

    // ── require_dependency (P3) ───────────────────────────────────────────

    #[test]
    fn require_dependency_extracted_as_normal() {
        let dir = TempDir::new().unwrap();
        let a = parse(&dir, "require_dependency 'app/services/foo'\n");
        let normals: Vec<_> = a
            .imports
            .iter()
            .filter(|i| i.kind == ImportKind::Normal)
            .collect();
        assert_eq!(normals.len(), 1);
        assert_eq!(normals[0].path, "app/services/foo");
    }
}