scryer-engine 0.2.0

Tree-sitter and stack-graphs AST indexing engine for Scryer code intelligence
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
use std::fs;
use std::time::Duration;
use tempfile::tempdir;

use scryer_db::{Project, Scope, ScryerDb, SourceFile, Symbol};
use scryer_engine::EngineService;

#[tokio::test]
async fn test_scanner_gitignore_and_initial_indexing() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();

    // Set up project files
    fs::create_dir_all(root.join("src"))?;
    fs::create_dir_all(root.join("target"))?;

    fs::write(root.join(".gitignore"), "target/\nignored.rs\n")?;

    fs::write(
        root.join("src/lib.rs"),
        r#"
pub fn root_init() -> bool {
    true
}
"#,
    )?;

    fs::write(
        root.join("src/helper.rs"),
        r#"
pub struct Helper {
    pub id: u64,
}
"#,
    )?;

    // Files that should be ignored
    fs::write(root.join("ignored.rs"), "pub fn ignored_fn() {}")?;
    fs::write(root.join("target/build.rs"), "pub fn build_fn() {}")?;

    let db = ScryerDb::new_in_memory().await?;
    let mut conn = db.lock().await;
    let project = Project::create()
        .slug("test-incremental".to_string())
        .root_path(root.to_string_lossy().to_string())
        .default_branch("main".to_string())
        .is_active(true)
        .created_at("2026-10-06T00:00:00Z".to_string())
        .updated_at("2026-10-06T00:00:00Z".to_string())
        .exec(&mut *conn)
        .await?;
    drop(conn);

    let engine = EngineService::new(db.clone());

    // 1. Initial indexing
    let report1 = engine.index_project(project.id, root).await?;
    assert_eq!(report1.scanned_files, 2);
    assert_eq!(report1.added_files, 2);
    assert_eq!(report1.modified_files, 0);
    assert_eq!(report1.unchanged_files, 0);
    assert_eq!(report1.deleted_files, 0);

    // Verify stored files in DB
    {
        let mut conn = db.lock().await;
        let files = SourceFile::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(files.len(), 2);
        let paths: Vec<String> = files.iter().map(|f| f.path.clone()).collect();
        assert!(paths.contains(&"src/lib.rs".to_string()));
        assert!(paths.contains(&"src/helper.rs".to_string()));

        // Verify symbols
        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(symbols.len(), 2);
        let sym_names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
        assert!(sym_names.contains(&"root_init".to_string()));
        assert!(sym_names.contains(&"Helper".to_string()));
    }

    // 2. Second indexing pass without changes - verify unchanged skip
    let report2 = engine.index_project(project.id, root).await?;
    assert_eq!(report2.scanned_files, 2);
    assert_eq!(report2.added_files, 0);
    assert_eq!(report2.modified_files, 0);
    assert_eq!(report2.unchanged_files, 2);
    assert_eq!(report2.deleted_files, 0);

    // 3. Modify a file - verify clean replacement without orphans
    fs::write(
        root.join("src/helper.rs"),
        r#"
pub struct NewHelper {
    pub name: String,
}

pub fn new_helper_fn() {}
"#,
    )?;

    let report3 = engine.index_project(project.id, root).await?;
    assert_eq!(report3.scanned_files, 2);
    assert_eq!(report3.added_files, 0);
    assert_eq!(report3.modified_files, 1);
    assert_eq!(report3.unchanged_files, 1);
    assert_eq!(report3.deleted_files, 0);

    // Verify that old `Helper` symbol is gone and `NewHelper`, `new_helper_fn` exist
    {
        let mut conn = db.lock().await;
        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        let sym_names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
        assert!(!sym_names.contains(&"Helper".to_string()));
        assert!(sym_names.contains(&"NewHelper".to_string()));
        assert!(sym_names.contains(&"new_helper_fn".to_string()));
        assert!(sym_names.contains(&"root_init".to_string()));
    }

    // 4. Delete a file - verify clean deletion
    fs::remove_file(root.join("src/helper.rs"))?;

    let report4 = engine.index_project(project.id, root).await?;
    assert_eq!(report4.scanned_files, 1);
    assert_eq!(report4.added_files, 0);
    assert_eq!(report4.modified_files, 0);
    assert_eq!(report4.unchanged_files, 1);
    assert_eq!(report4.deleted_files, 1);

    // Verify database only contains src/lib.rs
    {
        let mut conn = db.lock().await;
        let files = SourceFile::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/lib.rs");

        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].name, "root_init");

        let scopes = Scope::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(scopes.len(), 1); // Only root_init scope remains
    }

    Ok(())
}

#[tokio::test]
async fn test_workspace_watcher_reactive_indexing() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();

    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/lib.rs"), "pub fn initial() {}")?;

    let db = ScryerDb::new_in_memory().await?;
    let mut conn = db.lock().await;
    let project = Project::create()
        .slug("test-watcher".to_string())
        .root_path(root.to_string_lossy().to_string())
        .default_branch("main".to_string())
        .is_active(true)
        .created_at("2026-10-06T00:00:00Z".to_string())
        .updated_at("2026-10-06T00:00:00Z".to_string())
        .exec(&mut *conn)
        .await?;
    drop(conn);

    let engine = EngineService::new(db.clone());
    engine.index_project(project.id, root).await?;

    // Start background watcher
    let watcher = engine.watch_project(project.id, root)?;

    // Add a new file on disk
    fs::write(
        root.join("src/dynamic.rs"),
        r#"
pub fn dynamically_added() -> i32 {
    100
}
"#,
    )?;

    // Wait for the 200ms debounce window + worker processing
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Check that watcher picked up the new file and indexed it
    {
        let mut conn = db.lock().await;
        let files = SourceFile::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        let paths: Vec<String> = files.iter().map(|f| f.path.clone()).collect();
        assert!(paths.contains(&"src/dynamic.rs".to_string()));

        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        let names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
        assert!(names.contains(&"dynamically_added".to_string()));
    }

    watcher.stop().await;
    Ok(())
}

async fn test_project(db: &ScryerDb, root: &std::path::Path) -> anyhow::Result<Project> {
    let mut conn = db.lock().await;
    let project = Project::create()
        .slug("test-incremental-extra".to_string())
        .root_path(root.to_string_lossy().to_string())
        .default_branch("main".to_string())
        .is_active(true)
        .created_at("2026-10-06T00:00:00Z".to_string())
        .updated_at("2026-10-06T00:00:00Z".to_string())
        .exec(&mut *conn)
        .await?;
    Ok(project)
}

#[tokio::test]
async fn test_unparseable_file_does_not_abort_index() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/good.rs"), "pub fn good() {}\n")?;
    // Invalid UTF-8 makes the Rust parser fail.
    fs::write(root.join("src/bad.rs"), [0xff, 0xfe, 0xfd, b'\n'])?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());

    service.index_project(project.id, root).await?;

    let mut conn = db.lock().await;
    let files = SourceFile::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let paths: Vec<_> = files.iter().map(|f| f.path.as_str()).collect();
    assert_eq!(paths, ["src/good.rs"], "bad file skipped, good file kept");
    Ok(())
}

#[tokio::test]
async fn test_incremental_index_after_restart_loads_unchanged_files() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/a.rs"), "pub fn helper() {}\n")?;
    fs::write(root.join("src/b.rs"), "pub fn caller() { helper(); }\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    EngineService::new(db.clone())
        .index_project(project.id, root)
        .await?;

    // A new service stands in for a restarted process: same DB, empty engine pool.
    fs::write(
        root.join("src/b.rs"),
        "pub fn caller() { helper(); helper(); }\n",
    )?;
    let restarted = EngineService::new(db.clone());
    let report = restarted.index_project(project.id, root).await?;
    assert_eq!(report.modified_files, 1);
    assert_eq!(report.unchanged_files, 1);

    let engine = restarted.pool().get_or_create(project.id).await;
    let engine = engine.lock().await;
    assert!(
        engine.files.contains_key(std::path::Path::new("src/a.rs")),
        "unchanged file must be in the graph so the modified file resolves against it"
    );
    assert!(engine.files.contains_key(std::path::Path::new("src/b.rs")));
    Ok(())
}

#[tokio::test]
async fn test_batched_rows_round_trip_scopes_and_symbols() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(
        root.join("src/lib.rs"),
        r#"
/// It's a "quoted" doc with a 'single' quote and a backslash \ too.
pub struct Widget {
    pub id: u64,
}

impl Widget {
    /// Builds a widget; mentions O'Reilly.
    pub fn build(id: u64) -> Widget {
        fn inner() -> u64 { 1 }
        Widget { id: id + inner() }
    }
}
"#,
    )?;
    fs::write(root.join("src/other.rs"), "pub fn other() {}\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    EngineService::new(db.clone())
        .index_project(project.id, root)
        .await?;

    let mut conn = db.lock().await;
    let files = SourceFile::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let lib_id = files.iter().find(|f| f.path == "src/lib.rs").unwrap().id;
    let other_id = files.iter().find(|f| f.path == "src/other.rs").unwrap().id;

    let scopes = Scope::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let scope_ids: std::collections::HashSet<u64> = scopes.iter().map(|s| s.id).collect();
    assert_eq!(scope_ids.len(), scopes.len(), "scope ids are unique");
    for scope in &scopes {
        if let Some(parent) = scope.parent_scope_id {
            let parent_scope = scopes.iter().find(|s| s.id == parent).unwrap();
            assert_eq!(parent_scope.file_id, scope.file_id, "parent in same file");
            assert!(
                parent_scope.start_byte <= scope.start_byte
                    && scope.end_byte <= parent_scope.end_byte
            );
        }
    }
    assert!(
        scopes.iter().any(|s| s.parent_scope_id.is_some()),
        "nested scopes keep parents"
    );

    let symbols = Symbol::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let symbol_ids: std::collections::HashSet<u64> = symbols.iter().map(|s| s.id).collect();
    assert_eq!(symbol_ids.len(), symbols.len(), "symbol ids are unique");
    let widget = symbols
        .iter()
        .find(|s| s.name == "Widget" && s.kind != "reexport")
        .unwrap();
    assert_eq!(widget.file_id, lib_id);
    let doc = widget.docstring.as_deref().unwrap_or_default();
    assert!(
        doc.contains("It's a \"quoted\" doc with a 'single' quote and a backslash \\ too."),
        "doc: {doc:?}"
    );
    let build = symbols.iter().find(|s| s.name == "build").unwrap();
    assert!(
        build
            .docstring
            .as_deref()
            .unwrap_or_default()
            .contains("O'Reilly")
    );
    if let Some(scope_id) = build.scope_id {
        assert!(scope_ids.contains(&scope_id), "symbol scope exists");
    }
    let other = symbols.iter().find(|s| s.name == "other").unwrap();
    assert_eq!(other.file_id, other_id);
    assert!(other.dependency_package_id.is_none());
    drop(conn);

    // Rows written through the ORM afterwards must not collide with the explicit ids.
    fs::write(
        root.join("src/other.rs"),
        "pub fn other() {}\npub fn another() {}\n",
    )?;
    EngineService::new(db.clone())
        .index_project(project.id, root)
        .await?;
    let mut conn = db.lock().await;
    let symbols = Symbol::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let ids: std::collections::HashSet<u64> = symbols.iter().map(|s| s.id).collect();
    assert_eq!(ids.len(), symbols.len());
    assert!(symbols.iter().any(|s| s.name == "another"));
    Ok(())
}

#[tokio::test]
async fn test_oversized_source_files_are_not_indexed() -> anyhow::Result<()> {
    use scryer_engine::{WorkspaceScanner, scanner::MAX_SOURCE_FILE_BYTES};

    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/small.rs"), "pub fn small() {}\n")?;
    // A generated-looking file just over the cap: one huge function.
    let mut big = String::from("pub fn big() {\n");
    while (big.len() as u64) <= MAX_SOURCE_FILE_BYTES {
        big.push_str("    let _x = 1;\n");
    }
    big.push_str("}\n");
    fs::write(root.join("src/big.rs"), &big)?;

    let scanned = WorkspaceScanner::new(root).scan();
    assert_eq!(scanned, vec![std::path::PathBuf::from("src/small.rs")]);
    Ok(())
}