a3s-code-core 8.1.0

A3S Code Core - Embeddable AI agent library with tool execution
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
use super::watcher::normalize_file_changes;
use super::*;
use notify::{
    event::{ModifyKind, RenameMode},
    Event, EventKind,
};
use std::collections::HashSet;
use std::process::Command;

fn write(path: &Path, body: &[u8]) {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).unwrap();
    }
    std::fs::write(path, body).unwrap();
}

fn git_available() -> bool {
    Command::new("git").arg("--version").output().is_ok()
}

fn run_git(root: &Path, args: &[&str]) {
    let status = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(args)
        .status()
        .unwrap();
    assert!(
        status.success(),
        "git command failed: git -C {root:?} {args:?}"
    );
}

fn test_file(path: &str) -> LocalWorkspaceFile {
    LocalWorkspaceFile {
        path: path.to_string(),
        size: 0,
        modified_ms: None,
        language: None,
        status: LocalWorkspaceFileStatus::Unknown,
        binary: false,
        generated: false,
    }
}

#[test]
fn manifest_classifies_non_text_assets_before_workspace_retrieval() {
    let workspace = tempfile::tempdir().unwrap();
    write(&workspace.path().join("src/lib.rs"), b"pub fn text() {}\n");
    write(
        &workspace.path().join("architecture.pdf"),
        b"%PDF-1.7\n1 0 obj\n<< /Type /Catalog >>\nendobj\n",
    );
    write(
        &workspace.path().join("recording.mp3"),
        &[b'I', b'D', b'3', 0xff, 0xfb, 0x90, 0x64],
    );
    write(
        &workspace.path().join("opaque.asset"),
        &[0x89, b'A', b'S', b'S', b'E', b'T'],
    );
    write(
        &workspace.path().join("payload.bin"),
        b"ASCII_BYTES_STILL_BELONG_TO_A_NON_TEXT_CONTAINER",
    );

    let files = scan_workspace_files(workspace.path());
    let by_path = files
        .iter()
        .map(|file| (file.path.as_str(), file))
        .collect::<HashMap<_, _>>();

    assert!(!by_path["src/lib.rs"].binary);
    for path in [
        "architecture.pdf",
        "recording.mp3",
        "opaque.asset",
        "payload.bin",
    ] {
        assert!(by_path[path].binary, "{path} must not enter text retrieval");
    }
}

#[test]
fn manifest_index_reduces_glob_candidates() {
    let files = vec![
        test_file("src/main.rs"),
        test_file("crates/demo/src/lib.rs"),
        test_file("README.md"),
        test_file("docs/README.md"),
    ];
    let index = ManifestIndex::build(&files);

    let exact = candidate_indices_for_glob(&index, &WorkspacePath::root(), "src/main.rs")
        .iter()
        .collect::<Vec<_>>();
    assert_eq!(exact, vec![0]);

    let basename = candidate_indices_for_glob(&index, &WorkspacePath::root(), "**/README.md")
        .iter()
        .collect::<Vec<_>>();
    assert_eq!(basename, vec![2, 3]);

    let extension = candidate_indices_for_glob(&index, &WorkspacePath::root(), "**/*.rs")
        .iter()
        .collect::<Vec<_>>();
    assert_eq!(extension, vec![0, 1]);
}

#[test]
fn recent_files_are_bounded_and_ranked_by_heat() {
    let mut recent = RecentFiles::default();
    for index in 0..(RECENT_FILE_LIMIT + 5) {
        recent.touch(format!("src/file_{index:03}.rs"), index as u64);
    }
    recent.touch("src/file_000.rs".to_string(), 10_000);
    recent.touch("src/file_000.rs".to_string(), 10_001);

    let entries = recent.entries(None, usize::MAX, 10_001);

    assert_eq!(entries.len(), RECENT_FILE_LIMIT);
    assert_eq!(entries[0].path, "src/file_000.rs");
    assert_eq!(entries[0].touch_count, 2);
}

#[tokio::test]
async fn manifest_search_matches_glob_and_grep() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(
        &temp.path().join("src/main.rs"),
        b"fn main() {\n    println!(\"hello\");\n}\n",
    );
    write(&temp.path().join("README.md"), b"hello from docs\n");

    let backend = ManifestWorkspaceBackend::new(temp.path());
    let mut rx = backend.manifest().subscribe();
    tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        rx.recv(),
    )
    .await
    .unwrap()
    .unwrap();

    let glob = backend
        .glob(WorkspaceGlobRequest {
            base: backend.normalize("src").unwrap(),
            pattern: "*.rs".to_string(),
        })
        .await
        .unwrap();
    assert_eq!(glob.matches[0].as_str(), "src/main.rs");

    let grep = backend
        .grep(WorkspaceGrepRequest {
            base: WorkspacePath::root(),
            pattern: "hello".to_string(),
            glob: Some("*.rs".to_string()),
            context_lines: 0,
            case_insensitive: false,
            max_output_size: 1024,
        })
        .await
        .unwrap();
    assert_eq!(grep.match_count, 1);
    assert_eq!(grep.file_count, 1);
    assert!(grep.output.contains("src/main.rs:2"));

    let metadata_only = backend
        .grep_with_sources(WorkspaceGrepRequest {
            base: WorkspacePath::root(),
            pattern: "hello".to_string(),
            glob: None,
            context_lines: 0,
            case_insensitive: false,
            max_output_size: 0,
        })
        .await
        .unwrap();
    assert_eq!(metadata_only.result.match_count, 2);
    assert_eq!(metadata_only.result.file_count, 2);
    assert!(metadata_only.result.output.is_empty());
    assert!(!metadata_only.result.truncated);
    assert_eq!(
        metadata_only.matched_paths.unwrap(),
        vec![
            WorkspacePath::from_normalized("README.md"),
            WorkspacePath::from_normalized("src/main.rs")
        ]
    );
}

#[tokio::test]
async fn deferred_manifest_keeps_fallback_search_ready_until_one_way_activation() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(&temp.path().join("src/main.rs"), b"fn main() {}\n");

    let backend = ManifestWorkspaceBackend::new_deferred(temp.path());
    let manifest = backend.manifest();
    let mut snapshots = manifest.subscribe();

    assert!(!manifest.is_active());
    assert_eq!(manifest.snapshot().version, 0);
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert_eq!(manifest.snapshot().version, 0);
    assert!(snapshots.try_recv().is_err());

    // Manifest-backed search deliberately falls back to the local backend
    // while discovery is deferred, so latency-sensitive hosts remain usable.
    let glob = backend
        .glob(WorkspaceGlobRequest {
            base: WorkspacePath::root(),
            pattern: "**/*.rs".to_string(),
        })
        .await
        .unwrap();
    assert_eq!(glob.matches[0].as_str(), "src/main.rs");
    assert_eq!(manifest.snapshot().version, 0);

    assert!(manifest.activate());
    assert!(manifest.is_active());
    assert!(!manifest.activate());
    let ready = tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        snapshots.recv(),
    )
    .await
    .unwrap()
    .unwrap();
    assert!(ready.version > 0);
    assert!(ready.files.iter().any(|file| file.path == "src/main.rs"));
}

#[tokio::test]
async fn eager_manifest_is_active_at_construction() {
    let temp = tempfile::tempdir().unwrap();
    let manifest = LocalWorkspaceManifest::start(temp.path());

    assert!(manifest.is_active());
    assert!(!manifest.activate());
}

#[tokio::test]
async fn manifest_credential_boundary_filters_sensitive_grep_candidates() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(
        &temp.path().join("src/lib.rs"),
        b"pub const BOUNDARY_TOKEN_NAME: &str = \"external\";\n",
    );
    write(
        &temp.path().join("apps/api/.env.local"),
        b"BOUNDARY_TOKEN_NAME=secret\n",
    );

    let backend = ManifestWorkspaceBackend::new_with_access_policy(
        temp.path(),
        LocalWorkspaceAccessPolicy::CredentialBoundary,
    );
    let mut rx = backend.manifest().subscribe();
    tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        rx.recv(),
    )
    .await
    .unwrap()
    .unwrap();

    let grep = backend
        .grep(WorkspaceGrepRequest {
            base: WorkspacePath::root(),
            pattern: "BOUNDARY_TOKEN_NAME".to_string(),
            glob: None,
            context_lines: 0,
            case_insensitive: false,
            max_output_size: 1024,
        })
        .await
        .unwrap();

    assert_eq!(grep.match_count, 1);
    assert_eq!(grep.file_count, 1);
    assert!(grep.output.contains("src/lib.rs"));
    assert!(!grep.output.contains("secret"));
    assert!(!grep.output.contains(".env"));
}

#[cfg(any(unix, windows))]
#[tokio::test]
async fn source_egress_catalog_does_not_change_ordinary_workspace_reads() {
    let temp = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(temp.path().join("src")).unwrap();
    write(&temp.path().join(".env"), b"TOKEN=tool-governed\n");
    std::fs::hard_link(
        temp.path().join(".env"),
        temp.path().join("src/apparently-safe.rs"),
    )
    .unwrap();
    write(&temp.path().join("src/safe.rs"), b"pub fn safe() {}\n");

    let backend = ManifestWorkspaceBackend::new(temp.path());
    let secret = backend.normalize(".env").unwrap();

    assert_eq!(
        backend.read_text(&secret).await.unwrap(),
        "TOKEN=tool-governed\n"
    );
    assert_eq!(
        backend
            .read_text(&backend.normalize("src/apparently-safe.rs").unwrap())
            .await
            .unwrap(),
        "TOKEN=tool-governed\n"
    );

    let catalog = backend.chunk_catalog();
    let snapshot = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            let snapshot = catalog.snapshot().unwrap();
            if snapshot.source_revision() > 0 && snapshot.failed_file_count() == 1 {
                break snapshot;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .unwrap();
    assert_eq!(snapshot.paths(), vec!["src/safe.rs".to_owned()]);
}

#[tokio::test]
async fn host_can_configure_the_manifest_catalog_exactly_once_before_services_attach() {
    let temp = tempfile::tempdir().unwrap();
    let backend = ManifestWorkspaceBackend::new(temp.path());
    let strategy = WorkspaceChunkingStrategy::FixedWindow(
        crate::FixedWindowChunkingOptions::new(512, 64).unwrap(),
    );

    let catalog = backend
        .configure_chunk_catalog(
            strategy.clone(),
            ChunkingConfig::default(),
            ChunkCatalogLimits::default(),
        )
        .unwrap();

    assert!(Arc::ptr_eq(&catalog, &backend.chunk_catalog()));
    let debug = format!("{catalog:?}");
    assert!(debug.contains("FixedWindow"), "{debug}");
    assert!(debug.contains("target_bytes: 512"), "{debug}");
    assert!(backend
        .configure_chunk_catalog(
            strategy,
            ChunkingConfig::default(),
            ChunkCatalogLimits::default(),
        )
        .is_err());
}

#[tokio::test]
async fn manifest_backend_read_write_touch_recent_files() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(&temp.path().join("src/main.rs"), b"fn main() {}\n");

    let backend = ManifestWorkspaceBackend::new(temp.path());
    let mut rx = backend.manifest().subscribe();
    tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        rx.recv(),
    )
    .await
    .unwrap()
    .unwrap();

    let path = backend.normalize("src/main.rs").unwrap();
    backend.read_text(&path).await.unwrap();
    assert_eq!(
        backend.manifest().recent_file_paths(4),
        vec!["src/main.rs".to_string()]
    );

    backend
        .write_text(&path, "fn main() { println!(\"hi\"); }\n")
        .await
        .unwrap();
    let entries = backend.manifest().recent_file_entries(4);
    assert_eq!(entries[0].path, "src/main.rs");
    assert_eq!(entries[0].touch_count, 2);
}

#[tokio::test]
async fn manifest_glob_prioritizes_recent_matching_files() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(&temp.path().join("src/a.rs"), b"pub fn a() {}\n");
    write(&temp.path().join("src/z.rs"), b"pub fn z() {}\n");

    let backend = ManifestWorkspaceBackend::new(temp.path());
    let mut rx = backend.manifest().subscribe();
    tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        rx.recv(),
    )
    .await
    .unwrap()
    .unwrap();

    backend.manifest().touch_file("src/z.rs");
    let glob = backend
        .glob(WorkspaceGlobRequest {
            base: WorkspacePath::root(),
            pattern: "**/*.rs".to_string(),
        })
        .await
        .unwrap();

    assert_eq!(glob.matches[0].as_str(), "src/z.rs");
    assert_eq!(glob.matches[1].as_str(), "src/a.rs");
}

#[tokio::test]
async fn manifest_grep_prioritizes_recent_matches_when_truncated() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(
        &temp.path().join("src/a.rs"),
        b"pub const HIT: &str = \"a\";\n",
    );
    write(
        &temp.path().join("src/z.rs"),
        b"pub const HIT: &str = \"z\";\n",
    );

    let backend = ManifestWorkspaceBackend::new(temp.path());
    let mut rx = backend.manifest().subscribe();
    tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        rx.recv(),
    )
    .await
    .unwrap()
    .unwrap();

    backend.manifest().touch_file("src/z.rs");
    let grep = backend
        .grep(WorkspaceGrepRequest {
            base: WorkspacePath::root(),
            pattern: "HIT".to_string(),
            glob: Some("**/*.rs".to_string()),
            context_lines: 0,
            case_insensitive: false,
            max_output_size: 1,
        })
        .await
        .unwrap();

    assert!(grep.truncated);
    assert!(grep.output.starts_with(">src/z.rs:"), "{}", grep.output);
}

#[tokio::test]
async fn manifest_refreshes_after_file_event() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(&temp.path().join("README.md"), b"# hello\n");
    let manifest = LocalWorkspaceManifest::start(temp.path());
    let mut rx = manifest.subscribe();
    let initial = tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        rx.recv(),
    )
    .await
    .unwrap()
    .unwrap();
    assert!(initial.files.iter().any(|file| file.path == "README.md"));

    write(&temp.path().join("src/lib.rs"), b"pub fn lib() {}\n");
    let updated = tokio::time::timeout(Duration::from_secs(10), async {
        loop {
            let snapshot = rx.recv().await.unwrap();
            if snapshot.files.iter().any(|file| file.path == "src/lib.rs") {
                break snapshot;
            }
        }
    })
    .await
    .unwrap();

    assert!(updated.version > initial.version);
}

#[test]
fn file_change_batch_normalizes_and_merges_duplicate_events() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let created = root.join("src/new.rs");
    let changed = root.join("src/lib.rs");
    let ephemeral = root.join("src/ephemeral.rs");
    let events = vec![
        Event::new(EventKind::Create(notify::event::CreateKind::File)).add_path(created.clone()),
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(created.clone()),
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(changed.clone()),
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(changed),
        Event::new(EventKind::Create(notify::event::CreateKind::File)).add_path(ephemeral.clone()),
        Event::new(EventKind::Remove(notify::event::RemoveKind::File)).add_path(ephemeral),
    ];

    let changes = normalize_file_changes(&root, &events, &HashSet::new());

    assert_eq!(
        changes,
        vec![
            WorkspaceFileChange {
                path: WorkspacePath::from_normalized("src/new.rs"),
                kind: WorkspaceFileChangeKind::Created,
            },
            WorkspaceFileChange {
                path: WorkspacePath::from_normalized("src/lib.rs"),
                kind: WorkspaceFileChangeKind::Changed,
            },
        ]
    );
}

#[test]
fn file_change_batch_treats_create_for_known_file_as_change() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let existing = root.join("src/lib.rs");
    let events =
        vec![Event::new(EventKind::Create(notify::event::CreateKind::File)).add_path(existing)];
    let known_paths = HashSet::from(["src/lib.rs".to_string()]);

    assert_eq!(
        normalize_file_changes(&root, &events, &known_paths),
        vec![WorkspaceFileChange {
            path: WorkspacePath::from_normalized("src/lib.rs"),
            kind: WorkspaceFileChangeKind::Changed,
        }]
    );
}

#[test]
fn file_change_batch_reports_create_delete_and_rename_in_order() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let created = root.join("src/created.rs");
    let deleted = root.join("src/deleted.rs");
    let rename_from = root.join("src/old.rs");
    let rename_to = root.join("src/new.rs");
    let events = vec![
        Event::new(EventKind::Create(notify::event::CreateKind::File)).add_path(created),
        Event::new(EventKind::Remove(notify::event::RemoveKind::File)).add_path(deleted),
        Event::new(EventKind::Modify(ModifyKind::Name(RenameMode::Both)))
            .add_path(rename_from)
            .add_path(rename_to),
    ];

    let known_paths = HashSet::from(["src/new.rs".to_string()]);
    let changes = normalize_file_changes(&root, &events, &known_paths);

    assert_eq!(
        changes,
        vec![
            WorkspaceFileChange {
                path: WorkspacePath::from_normalized("src/created.rs"),
                kind: WorkspaceFileChangeKind::Created,
            },
            WorkspaceFileChange {
                path: WorkspacePath::from_normalized("src/deleted.rs"),
                kind: WorkspaceFileChangeKind::Deleted,
            },
            WorkspaceFileChange {
                path: WorkspacePath::from_normalized("src/old.rs"),
                kind: WorkspaceFileChangeKind::Deleted,
            },
            WorkspaceFileChange {
                path: WorkspacePath::from_normalized("src/new.rs"),
                kind: WorkspaceFileChangeKind::Created,
            },
        ]
    );
}

#[test]
fn file_change_batch_ignores_external_and_invalid_paths() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().canonicalize().unwrap();
    let outside = root.parent().unwrap().join("outside.rs");
    let invalid = root.join("../escape.rs");
    let ignored = root.join("node_modules/package/index.js");
    let events = vec![
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(outside),
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(invalid),
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(ignored),
        Event::new(EventKind::Modify(ModifyKind::Any)).add_path(root.clone()),
    ];

    assert!(normalize_file_changes(&root, &events, &HashSet::new()).is_empty());
}

#[tokio::test]
async fn manifest_change_subscription_reports_same_size_content_changes() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    let path = temp.path().join("src/lib.rs");
    write(&path, b"aaaa\n");
    let manifest = LocalWorkspaceManifest::start(temp.path());
    let mut snapshots = manifest.subscribe();
    let mut changes = manifest.subscribe_changes();
    tokio::time::timeout(
        crate::test_support::external_resource_start_timeout(Duration::from_secs(5)),
        snapshots.recv(),
    )
    .await
    .unwrap()
    .unwrap();

    let received = tokio::time::timeout(Duration::from_secs(10), async {
        let contents = [b"bbbb\n".as_slice(), b"cccc\n".as_slice()];
        let mut attempt = 0;
        loop {
            assert!(attempt < 20, "no content change was observed");
            write(&path, contents[attempt % contents.len()]);
            attempt += 1;
            match tokio::time::timeout(Duration::from_millis(400), changes.recv()).await {
                Ok(Ok(change)) if change.path.as_str() == "src/lib.rs" => break change,
                Ok(Ok(_)) | Ok(Err(_)) | Err(_) => {}
            }
        }
    })
    .await
    .unwrap();

    assert_eq!(received.kind, WorkspaceFileChangeKind::Changed);
}

#[tokio::test]
async fn manifest_search_falls_back_before_initial_scan() {
    let _permit = crate::test_support::resource_intensive_test_permit().await;
    let temp = tempfile::tempdir().unwrap();
    write(&temp.path().join("src/main.rs"), b"fn main() {}\n");
    let backend = ManifestWorkspaceBackend::new(temp.path());
    let glob = backend
        .glob(WorkspaceGlobRequest {
            base: backend.normalize("src").unwrap(),
            pattern: "*.rs".to_string(),
        })
        .await
        .unwrap();
    assert!(glob
        .matches
        .iter()
        .any(|path| path.as_str() == "src/main.rs"));
}

#[test]
fn scan_includes_files_inside_nested_git_workspaces() {
    if !git_available() {
        return;
    }

    let temp = tempfile::tempdir().unwrap();
    run_git(temp.path(), &["init"]);
    write(&temp.path().join("README.md"), b"# root\n");

    let nested = temp.path().join("vendor/child");
    std::fs::create_dir_all(&nested).unwrap();
    run_git(&nested, &["init"]);
    write(&nested.join("src/lib.rs"), b"pub fn child() {}\n");

    let files = scan_workspace_files(temp.path());
    assert!(files.iter().any(|file| file.path == "README.md"));
    assert!(files
        .iter()
        .any(|file| file.path == "vendor/child/src/lib.rs"));
}