a3s-code-core 5.2.4

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
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
//! Manifest-backed local workspace services.
//!
//! The manifest is an in-memory index of workspace files. It is built
//! asynchronously, refreshed from filesystem notifications, and used by the
//! local search backend (`glob`/`grep`) to avoid walking the filesystem for
//! every agent tool call. File I/O, command execution, and git operations still
//! delegate to [`LocalWorkspaceBackend`].

use super::{
    escape_control_chars_for_display, validate_relative_pattern, CommandOutput, CommandRequest,
    LocalWorkspaceBackend, WorkspaceCommandRunner, WorkspaceDirEntry, WorkspaceFileSystem,
    WorkspaceGit, WorkspaceGitBranch, WorkspaceGitCheckoutOutput, WorkspaceGitCheckoutRequest,
    WorkspaceGitCommit, WorkspaceGitCreateBranchRequest, WorkspaceGitCreateWorktreeRequest,
    WorkspaceGitDiffRequest, WorkspaceGitRemote, WorkspaceGitRemoveWorktreeRequest,
    WorkspaceGitStash, WorkspaceGitStashProvider, WorkspaceGitStashRequest, WorkspaceGitStatus,
    WorkspaceGitWorktree, WorkspaceGitWorktreeMutation, WorkspaceGitWorktreeProvider,
    WorkspaceGlobRequest, WorkspaceGlobResult, WorkspaceGrepOutcome, WorkspaceGrepRequest,
    WorkspaceGrepResult, WorkspacePath, WorkspacePathResolver, WorkspaceResult, WorkspaceSearch,
    WorkspaceTextRange, WorkspaceTextReader, WorkspaceWriteOutcome,
};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::{hash_map::DefaultHasher, HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, mpsc};

mod scanner;
use scanner::is_relevant_event;
pub use scanner::scan_workspace_files;

const WATCH_DEBOUNCE: Duration = Duration::from_millis(150);
const WATCH_STARTUP_SCAN_INTERVAL: Duration = Duration::from_secs(1);
const SNAPSHOT_CHANNEL_CAPACITY: usize = 16;
const RECENT_FILE_LIMIT: usize = 128;
const RECENT_DECAY_HALF_LIFE_MS: f32 = 10.0 * 60.0 * 1000.0;
const RECENT_FREQUENCY_NORMALIZER: f32 = 16.0;
const RECENT_RECENCY_WEIGHT: f32 = 0.75;

/// Git/workspace status for a file in the manifest.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum LocalWorkspaceFileStatus {
    Tracked,
    Untracked,
    Unknown,
}

/// One manifest entry.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct LocalWorkspaceFile {
    pub path: String,
    pub size: u64,
    pub modified_ms: Option<u64>,
    pub language: Option<String>,
    pub status: LocalWorkspaceFileStatus,
    pub binary: bool,
    pub generated: bool,
}

/// Recency/usage score for a workspace file the user or agent touched.
///
/// Hosts should treat this as a ranking hint, not as an authoritative file
/// list. The manifest filters deleted files when exposing recent entries.
#[derive(Clone, Debug, PartialEq)]
pub struct RecentWorkspaceFile {
    pub path: String,
    pub score: f32,
    pub touched_at_ms: u64,
    pub touch_count: u32,
}

/// Immutable manifest snapshot.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LocalWorkspaceManifestSnapshot {
    pub version: u64,
    pub root: PathBuf,
    pub files: Vec<LocalWorkspaceFile>,
    pub scanned_at_ms: u64,
}

impl LocalWorkspaceManifestSnapshot {
    pub fn empty(root: PathBuf) -> Self {
        Self {
            version: 0,
            root,
            files: Vec::new(),
            scanned_at_ms: now_ms(),
        }
    }

    pub fn file_paths(&self) -> Vec<String> {
        self.files.iter().map(|file| file.path.clone()).collect()
    }
}

/// Shared in-memory workspace manifest.
pub struct LocalWorkspaceManifest {
    state: Arc<RwLock<ManifestState>>,
    recent: Arc<RwLock<RecentFiles>>,
    snapshots: broadcast::Sender<LocalWorkspaceManifestSnapshot>,
    task: tokio::task::JoinHandle<()>,
}

impl LocalWorkspaceManifest {
    /// Start the manifest scanner/watcher for `root`.
    pub fn start(root: impl Into<PathBuf>) -> Arc<Self> {
        let root = root.into();
        let root = root.canonicalize().unwrap_or_else(|_| root.clone());
        let initial = LocalWorkspaceManifestSnapshot::empty(root.clone());
        let state = Arc::new(RwLock::new(ManifestState {
            fingerprint: fingerprint_files(&initial.files),
            index: Arc::new(ManifestIndex::build(&initial.files)),
            snapshot: Arc::new(initial),
        }));
        let recent = Arc::new(RwLock::new(RecentFiles::default()));
        let (snapshots, _) = broadcast::channel(SNAPSHOT_CHANNEL_CAPACITY);
        let task_state = Arc::clone(&state);
        let task_snapshots = snapshots.clone();
        let task = tokio::spawn(async move {
            run_manifest_task(root, task_state, task_snapshots).await;
        });
        Arc::new(Self {
            state,
            recent,
            snapshots,
            task,
        })
    }

    pub fn snapshot(&self) -> LocalWorkspaceManifestSnapshot {
        self.state
            .read()
            .map(|state| (*state.snapshot).clone())
            .unwrap_or_else(|_| LocalWorkspaceManifestSnapshot::empty(PathBuf::new()))
    }

    pub fn subscribe(&self) -> broadcast::Receiver<LocalWorkspaceManifestSnapshot> {
        self.snapshots.subscribe()
    }

    /// Record that a workspace-relative file was opened, read, or written.
    ///
    /// This intentionally does not require the initial manifest scan to have
    /// completed. The public recent-file views filter against the current
    /// manifest index, so early touches become visible after the file is indexed
    /// and deleted files disappear automatically.
    pub fn touch_file(&self, path: impl AsRef<str>) -> bool {
        let Some(path) = normalize_recent_file_path(path.as_ref()) else {
            return false;
        };
        let Ok(mut recent) = self.recent.write() else {
            return false;
        };
        recent.touch(path, now_ms());
        true
    }

    /// Return the hottest known files, newest/frequently used first.
    pub fn recent_file_entries(&self, limit: usize) -> Vec<RecentWorkspaceFile> {
        if limit == 0 {
            return Vec::new();
        }
        let Some(index) = self.state.read().ok().map(|state| Arc::clone(&state.index)) else {
            return Vec::new();
        };
        self.recent
            .read()
            .map(|recent| recent.entries(Some(&index), limit, now_ms()))
            .unwrap_or_default()
    }

    /// Return recent file paths only, preserving hot-file order.
    pub fn recent_file_paths(&self, limit: usize) -> Vec<String> {
        self.recent_file_entries(limit)
            .into_iter()
            .map(|entry| entry.path)
            .collect()
    }
}

impl Drop for LocalWorkspaceManifest {
    fn drop(&mut self) {
        self.task.abort();
    }
}

struct ManifestState {
    fingerprint: u64,
    index: Arc<ManifestIndex>,
    snapshot: Arc<LocalWorkspaceManifestSnapshot>,
}

#[derive(Debug, Default)]
struct RecentFiles {
    entries: HashMap<String, RecentFileState>,
    next_sequence: u64,
}

impl RecentFiles {
    fn touch(&mut self, path: String, now: u64) {
        self.next_sequence = self.next_sequence.saturating_add(1);
        let sequence = self.next_sequence;
        self.entries
            .entry(path.clone())
            .and_modify(|entry| {
                entry.touched_at_ms = now;
                entry.touch_count = entry.touch_count.saturating_add(1);
                entry.sequence = sequence;
            })
            .or_insert(RecentFileState {
                path,
                touched_at_ms: now,
                touch_count: 1,
                sequence,
            });
        self.prune(now);
    }

    fn entries(
        &self,
        index: Option<&ManifestIndex>,
        limit: usize,
        now: u64,
    ) -> Vec<RecentWorkspaceFile> {
        let mut entries = self
            .entries
            .values()
            .filter(|entry| {
                index
                    .map(|index| index.by_path.contains_key(&entry.path))
                    .unwrap_or(true)
            })
            .map(|entry| {
                let score = recent_score(entry, now);
                (
                    entry.sequence,
                    RecentWorkspaceFile {
                        path: entry.path.clone(),
                        score,
                        touched_at_ms: entry.touched_at_ms,
                        touch_count: entry.touch_count,
                    },
                )
            })
            .collect::<Vec<_>>();

        entries.sort_by(|(left_sequence, left), (right_sequence, right)| {
            right
                .score
                .total_cmp(&left.score)
                .then_with(|| right.touched_at_ms.cmp(&left.touched_at_ms))
                .then_with(|| right_sequence.cmp(left_sequence))
                .then_with(|| left.path.cmp(&right.path))
        });
        entries
            .into_iter()
            .take(limit)
            .map(|(_, entry)| entry)
            .collect()
    }

    fn prune(&mut self, now: u64) {
        if self.entries.len() <= RECENT_FILE_LIMIT {
            return;
        }

        let keep = self
            .entries
            .values()
            .map(|entry| (entry.path.clone(), recent_score(entry, now), entry.sequence))
            .collect::<Vec<_>>();
        let mut keep = keep;
        keep.sort_by(|left, right| {
            right
                .1
                .total_cmp(&left.1)
                .then_with(|| right.2.cmp(&left.2))
                .then_with(|| left.0.cmp(&right.0))
        });
        let keep = keep
            .into_iter()
            .take(RECENT_FILE_LIMIT)
            .map(|(path, _, _)| path)
            .collect::<HashSet<_>>();
        self.entries.retain(|path, _| keep.contains(path));
    }
}

#[derive(Debug)]
struct RecentFileState {
    path: String,
    touched_at_ms: u64,
    touch_count: u32,
    sequence: u64,
}

#[derive(Debug, Default)]
struct ManifestIndex {
    all: Vec<usize>,
    by_path: HashMap<String, usize>,
    by_basename: HashMap<String, Vec<usize>>,
    by_extension: HashMap<String, Vec<usize>>,
}

impl ManifestIndex {
    fn build(files: &[LocalWorkspaceFile]) -> Self {
        let mut index = Self {
            all: Vec::with_capacity(files.len()),
            by_path: HashMap::with_capacity(files.len()),
            by_basename: HashMap::new(),
            by_extension: HashMap::new(),
        };

        for (file_index, file) in files.iter().enumerate() {
            index.all.push(file_index);
            index.by_path.insert(file.path.clone(), file_index);
            if let Some(name) = Path::new(&file.path)
                .file_name()
                .and_then(|name| name.to_str())
            {
                index
                    .by_basename
                    .entry(name.to_string())
                    .or_default()
                    .push(file_index);
            }
            if let Some(extension) = Path::new(&file.path)
                .extension()
                .and_then(|extension| extension.to_str())
                .filter(|extension| !extension.is_empty())
            {
                index
                    .by_extension
                    .entry(extension.to_string())
                    .or_default()
                    .push(file_index);
            }
        }

        index
    }
}

struct ManifestSearchSnapshot {
    snapshot: Arc<LocalWorkspaceManifestSnapshot>,
    index: Arc<ManifestIndex>,
}

/// Local backend that uses an in-memory manifest for search.
pub struct ManifestWorkspaceBackend {
    local: Arc<LocalWorkspaceBackend>,
    manifest: Arc<LocalWorkspaceManifest>,
}

impl ManifestWorkspaceBackend {
    pub fn new(root: impl Into<PathBuf>) -> Arc<Self> {
        let local = Arc::new(LocalWorkspaceBackend::new(root.into()));
        let manifest = LocalWorkspaceManifest::start(local.root.clone());
        Self::from_manifest(local, manifest)
    }

    pub fn from_manifest(
        local: Arc<LocalWorkspaceBackend>,
        manifest: Arc<LocalWorkspaceManifest>,
    ) -> Arc<Self> {
        Arc::new(Self { local, manifest })
    }

    pub fn manifest(&self) -> Arc<LocalWorkspaceManifest> {
        Arc::clone(&self.manifest)
    }

    pub fn local_root(&self) -> &Path {
        &self.local.root
    }

    fn manifest_ready(&self) -> Option<ManifestSearchSnapshot> {
        let state = self.manifest.state.read().ok()?;
        (state.snapshot.version > 0).then(|| ManifestSearchSnapshot {
            snapshot: Arc::clone(&state.snapshot),
            index: Arc::clone(&state.index),
        })
    }

    fn fallback_search(&self) -> Arc<LocalWorkspaceBackend> {
        Arc::clone(&self.local)
    }

    fn recent_path_ranks(&self, index: &ManifestIndex) -> HashMap<String, usize> {
        self.manifest
            .recent
            .read()
            .map(|recent| {
                recent
                    .entries(Some(index), RECENT_FILE_LIMIT, now_ms())
                    .into_iter()
                    .enumerate()
                    .map(|(rank, entry)| (entry.path, rank))
                    .collect()
            })
            .unwrap_or_default()
    }
}

impl WorkspacePathResolver for ManifestWorkspaceBackend {
    fn normalize(&self, input: &str) -> Result<WorkspacePath> {
        self.local.normalize(input)
    }
}

#[async_trait]
impl WorkspaceFileSystem for ManifestWorkspaceBackend {
    async fn read_text(&self, path: &WorkspacePath) -> WorkspaceResult<String> {
        let content = self.local.read_text(path).await?;
        self.manifest.touch_file(path.as_str());
        Ok(content)
    }

    async fn write_text(
        &self,
        path: &WorkspacePath,
        content: &str,
    ) -> WorkspaceResult<WorkspaceWriteOutcome> {
        let outcome = self.local.write_text(path, content).await?;
        self.manifest.touch_file(path.as_str());
        Ok(outcome)
    }

    async fn list_dir(&self, path: &WorkspacePath) -> WorkspaceResult<Vec<WorkspaceDirEntry>> {
        self.local.list_dir(path).await
    }
}

#[async_trait]
impl WorkspaceTextReader for ManifestWorkspaceBackend {
    async fn read_text_range(
        &self,
        path: &WorkspacePath,
        offset: usize,
        limit: usize,
    ) -> WorkspaceResult<WorkspaceTextRange> {
        let range = self.local.read_text_range(path, offset, limit).await?;
        self.manifest.touch_file(path.as_str());
        Ok(range)
    }
}

#[async_trait]
impl WorkspaceCommandRunner for ManifestWorkspaceBackend {
    async fn exec(&self, request: CommandRequest) -> Result<CommandOutput> {
        self.local.exec(request).await
    }
}

#[async_trait]
impl WorkspaceSearch for ManifestWorkspaceBackend {
    async fn glob(&self, request: WorkspaceGlobRequest) -> Result<WorkspaceGlobResult> {
        validate_relative_pattern(&request.pattern, "glob pattern")?;
        let Some(search_snapshot) = self.manifest_ready() else {
            return self.fallback_search().glob(request).await;
        };
        let pattern = glob::Pattern::new(&request.pattern)
            .map_err(|e| anyhow!("Invalid glob pattern '{}': {}", request.pattern, e))?;
        let candidates =
            candidate_indices_for_glob(&search_snapshot.index, &request.base, &request.pattern);
        let recent_ranks = self.recent_path_ranks(&search_snapshot.index);

        let mut matches = Vec::new();
        for file_index in
            recent_first_candidate_indices(&candidates, &search_snapshot.index, &recent_ranks)
        {
            let Some(file) = search_snapshot.snapshot.files.get(file_index) else {
                continue;
            };
            let Some(relative_to_base) = relative_to_base(&file.path, &request.base) else {
                continue;
            };
            if glob_matches(&pattern, relative_to_base) {
                matches.push(WorkspacePath::from_normalized(file.path.clone()));
            }
        }

        sort_paths_by_recent(&mut matches, &recent_ranks);
        Ok(WorkspaceGlobResult { matches })
    }

    async fn grep(&self, request: WorkspaceGrepRequest) -> Result<WorkspaceGrepResult> {
        Ok(self.grep_with_sources(request).await?.result)
    }

    async fn grep_with_sources(
        &self,
        request: WorkspaceGrepRequest,
    ) -> Result<WorkspaceGrepOutcome> {
        if let Some(ref glob) = request.glob {
            validate_relative_pattern(glob, "grep glob filter")?;
        }
        let Some(search_snapshot) = self.manifest_ready() else {
            return self.fallback_search().grep_with_sources(request).await;
        };

        let regex_pattern = if request.case_insensitive {
            format!("(?i){}", request.pattern)
        } else {
            request.pattern.clone()
        };
        let regex = regex::Regex::new(&regex_pattern)
            .map_err(|e| anyhow!("Invalid regex pattern '{}': {}", request.pattern, e))?;
        let glob = request
            .glob
            .as_deref()
            .map(glob::Pattern::new)
            .transpose()
            .map_err(|e| anyhow!("Invalid grep glob filter: {e}"))?;

        let mut output = String::new();
        let mut match_count = 0;
        let mut file_count = 0;
        let mut total_size = 0;
        let mut matched_paths = Vec::new();

        let candidates = request
            .glob
            .as_deref()
            .map(|glob| candidate_indices_for_glob(&search_snapshot.index, &request.base, glob))
            .unwrap_or_else(|| CandidateIndices::Indexed(&search_snapshot.index.all));
        let recent_ranks = self.recent_path_ranks(&search_snapshot.index);

        for file_index in
            recent_first_candidate_indices(&candidates, &search_snapshot.index, &recent_ranks)
        {
            let Some(file) = search_snapshot.snapshot.files.get(file_index) else {
                continue;
            };
            if file.binary {
                continue;
            }
            let Some(relative_to_base) = relative_to_base(&file.path, &request.base) else {
                continue;
            };
            if let Some(glob) = &glob {
                if !glob_matches(glob, relative_to_base) {
                    continue;
                }
            }

            let full_path = search_snapshot.snapshot.root.join(&file.path);
            let content = match std::fs::read_to_string(&full_path) {
                Ok(content) => content,
                Err(_) => continue,
            };
            let lines: Vec<&str> = content.lines().collect();
            let file_matches = lines
                .iter()
                .enumerate()
                .filter_map(|(line_idx, line)| regex.is_match(line).then_some(line_idx))
                .collect::<Vec<_>>();

            if file_matches.is_empty() {
                continue;
            }

            file_count += 1;
            let workspace_path = WorkspacePath::from_normalized(file.path.clone());
            let display_path = escape_control_chars_for_display(&file.path);
            let mut path_recorded = false;
            for &match_idx in &file_matches {
                if total_size > request.max_output_size {
                    return Ok(WorkspaceGrepOutcome {
                        result: WorkspaceGrepResult {
                            output,
                            match_count,
                            file_count,
                            truncated: true,
                        },
                        matched_paths: Some(matched_paths),
                    });
                }

                if !path_recorded {
                    matched_paths.push(workspace_path.clone());
                    path_recorded = true;
                }
                match_count += 1;
                let start = match_idx.saturating_sub(request.context_lines);
                let end = (match_idx + request.context_lines + 1).min(lines.len());

                for (i, line) in lines[start..end].iter().enumerate() {
                    let abs_i = start + i;
                    let prefix = if abs_i == match_idx { ">" } else { " " };
                    let line = format!("{}{}:{}: {}\n", prefix, display_path, abs_i + 1, line);
                    total_size += line.len();
                    output.push_str(&line);
                }

                if request.context_lines > 0 {
                    output.push_str("--\n");
                    total_size += 3;
                }
            }
        }

        Ok(WorkspaceGrepOutcome {
            result: WorkspaceGrepResult {
                output,
                match_count,
                file_count,
                truncated: false,
            },
            matched_paths: Some(matched_paths),
        })
    }
}

#[async_trait]
impl WorkspaceGit for ManifestWorkspaceBackend {
    async fn is_repository(&self) -> Result<bool> {
        self.local.is_repository().await
    }

    async fn status(&self) -> Result<WorkspaceGitStatus> {
        self.local.status().await
    }

    async fn log(&self, max_count: usize) -> Result<Vec<WorkspaceGitCommit>> {
        self.local.log(max_count).await
    }

    async fn list_branches(&self) -> Result<Vec<WorkspaceGitBranch>> {
        self.local.list_branches().await
    }

    async fn create_branch(&self, request: WorkspaceGitCreateBranchRequest) -> Result<()> {
        self.local.create_branch(request).await
    }

    async fn checkout(
        &self,
        request: WorkspaceGitCheckoutRequest,
    ) -> Result<WorkspaceGitCheckoutOutput> {
        self.local.checkout(request).await
    }

    async fn diff(&self, request: WorkspaceGitDiffRequest) -> Result<String> {
        self.local.diff(request).await
    }

    async fn list_remotes(&self) -> Result<Vec<WorkspaceGitRemote>> {
        self.local.list_remotes().await
    }
}

#[async_trait]
impl WorkspaceGitStashProvider for ManifestWorkspaceBackend {
    async fn list_stashes(&self) -> Result<Vec<WorkspaceGitStash>> {
        self.local.list_stashes().await
    }

    async fn stash(&self, request: WorkspaceGitStashRequest) -> Result<()> {
        self.local.stash(request).await
    }
}

#[async_trait]
impl WorkspaceGitWorktreeProvider for ManifestWorkspaceBackend {
    async fn list_worktrees(&self) -> Result<Vec<WorkspaceGitWorktree>> {
        self.local.list_worktrees().await
    }

    async fn create_worktree(
        &self,
        request: WorkspaceGitCreateWorktreeRequest,
    ) -> Result<WorkspaceGitWorktreeMutation> {
        self.local.create_worktree(request).await
    }

    async fn remove_worktree(
        &self,
        request: WorkspaceGitRemoveWorktreeRequest,
    ) -> Result<WorkspaceGitWorktreeMutation> {
        self.local.remove_worktree(request).await
    }
}

async fn run_manifest_task(
    root: PathBuf,
    state: Arc<RwLock<ManifestState>>,
    snapshots: broadcast::Sender<LocalWorkspaceManifestSnapshot>,
) {
    let (event_tx, mut event_rx) = mpsc::unbounded_channel();
    // Readiness must not depend on the platform watcher service. Watcher
    // construction is blocking on some platforms and can be slow or fail
    // under resource pressure, while the initial manifest is still useful.
    publish_scan(&root, &state, &snapshots).await;

    let watcher_root = root.clone();
    let mut watcher_task = tokio::task::spawn_blocking(move || {
        RecommendedWatcher::new(
            move |event| {
                let _ = event_tx.send(event);
            },
            Config::default(),
        )
        .and_then(|mut watcher| {
            watcher.watch(&watcher_root, RecursiveMode::Recursive)?;
            Ok(watcher)
        })
    });
    let watcher = loop {
        tokio::select! {
            result = &mut watcher_task => break result,
            _ = tokio::time::sleep(WATCH_STARTUP_SCAN_INTERVAL) => {
                // Continue providing a fresh manifest while the platform
                // watcher service is slow to initialize.
                publish_scan(&root, &state, &snapshots).await;
            }
        }
    };
    let Ok(Ok(_watcher)) = watcher else {
        return;
    };
    // Close the scan-to-watch registration window: files changed while the
    // watcher was being constructed are captured by this second scan.
    publish_scan(&root, &state, &snapshots).await;

    while let Some(event) = event_rx.recv().await {
        let Ok(event) = event else {
            continue;
        };
        if !is_relevant_event(&event, &root) {
            continue;
        }
        tokio::time::sleep(WATCH_DEBOUNCE).await;
        while let Ok(event) = event_rx.try_recv() {
            if let Ok(event) = event {
                if !is_relevant_event(&event, &root) {
                    continue;
                }
            }
        }
        publish_scan(&root, &state, &snapshots).await;
    }
}

async fn publish_scan(
    root: &Path,
    state: &Arc<RwLock<ManifestState>>,
    snapshots: &broadcast::Sender<LocalWorkspaceManifestSnapshot>,
) {
    let root = root.to_path_buf();
    let Ok(files) = tokio::task::spawn_blocking(move || scan_workspace_files(&root)).await else {
        return;
    };
    let Some(snapshot) = update_state(state, files) else {
        return;
    };
    let _ = snapshots.send(snapshot);
}

fn update_state(
    state: &Arc<RwLock<ManifestState>>,
    files: Vec<LocalWorkspaceFile>,
) -> Option<LocalWorkspaceManifestSnapshot> {
    let fingerprint = fingerprint_files(&files);
    let index = Arc::new(ManifestIndex::build(&files));
    let Ok(mut state) = state.write() else {
        return None;
    };
    if state.snapshot.version > 0 && state.fingerprint == fingerprint {
        return None;
    }
    state.fingerprint = fingerprint;
    state.index = index;
    state.snapshot = Arc::new(LocalWorkspaceManifestSnapshot {
        version: state.snapshot.version + 1,
        root: state.snapshot.root.clone(),
        files,
        scanned_at_ms: now_ms(),
    });
    Some((*state.snapshot).clone())
}

enum CandidateIndices<'a> {
    Indexed(&'a [usize]),
    Single(Option<usize>),
}

impl<'a> CandidateIndices<'a> {
    fn iter(&self) -> Box<dyn Iterator<Item = usize> + '_> {
        match self {
            Self::Indexed(indices) => Box::new(indices.iter().copied()),
            Self::Single(Some(index)) => Box::new(std::iter::once(*index)),
            Self::Single(None) => Box::new(std::iter::empty()),
        }
    }

    fn len(&self) -> usize {
        match self {
            Self::Indexed(indices) => indices.len(),
            Self::Single(Some(_)) => 1,
            Self::Single(None) => 0,
        }
    }

    fn contains(&self, index: usize) -> bool {
        match self {
            Self::Indexed(indices) => indices.contains(&index),
            Self::Single(Some(candidate)) => *candidate == index,
            Self::Single(None) => false,
        }
    }
}

fn recent_first_candidate_indices(
    candidates: &CandidateIndices<'_>,
    index: &ManifestIndex,
    recent_ranks: &HashMap<String, usize>,
) -> Vec<usize> {
    if recent_ranks.is_empty() {
        return candidates.iter().collect();
    }

    let mut hot = recent_ranks
        .iter()
        .filter_map(|(path, rank)| {
            let file_index = *index.by_path.get(path)?;
            candidates
                .contains(file_index)
                .then_some((*rank, file_index))
        })
        .collect::<Vec<_>>();
    hot.sort_unstable_by_key(|(rank, _)| *rank);

    let mut out = Vec::with_capacity(candidates.len());
    let mut seen = HashSet::with_capacity(hot.len());
    for (_, file_index) in hot {
        if seen.insert(file_index) {
            out.push(file_index);
        }
    }
    out.extend(
        candidates
            .iter()
            .filter(|file_index| !seen.contains(file_index)),
    );
    out
}

fn sort_paths_by_recent(paths: &mut [WorkspacePath], recent_ranks: &HashMap<String, usize>) {
    paths.sort_by(|left, right| {
        recent_ranks
            .get(left.as_str())
            .copied()
            .unwrap_or(usize::MAX)
            .cmp(
                &recent_ranks
                    .get(right.as_str())
                    .copied()
                    .unwrap_or(usize::MAX),
            )
            .then_with(|| left.as_str().cmp(right.as_str()))
    });
}

fn candidate_indices_for_glob<'a>(
    index: &'a ManifestIndex,
    base: &WorkspacePath,
    pattern: &str,
) -> CandidateIndices<'a> {
    if !has_glob_meta(pattern) && pattern.contains('/') {
        return CandidateIndices::Single(
            literal_workspace_path(base, pattern)
                .and_then(|path| index.by_path.get(&path).copied()),
        );
    }

    if let Some(name) = literal_terminal_segment(pattern) {
        return index
            .by_basename
            .get(name)
            .map(|indices| CandidateIndices::Indexed(indices))
            .unwrap_or(CandidateIndices::Single(None));
    }

    if let Some(extension) = simple_extension_terminal(pattern) {
        return index
            .by_extension
            .get(extension)
            .map(|indices| CandidateIndices::Indexed(indices))
            .unwrap_or(CandidateIndices::Single(None));
    }

    CandidateIndices::Indexed(&index.all)
}

fn literal_workspace_path(base: &WorkspacePath, pattern: &str) -> Option<String> {
    let pattern = normalize_relative_path_lossy(Path::new(pattern))?;
    if pattern.is_empty() {
        return None;
    }
    if base.is_root() {
        Some(pattern)
    } else {
        Some(format!(
            "{}/{}",
            base.as_str().trim_end_matches('/'),
            pattern
        ))
    }
}

fn literal_terminal_segment(pattern: &str) -> Option<&str> {
    let terminal = pattern
        .trim_end_matches('/')
        .rsplit('/')
        .next()
        .filter(|segment| !segment.is_empty())?;
    (!has_glob_meta(terminal)).then_some(terminal)
}

fn simple_extension_terminal(pattern: &str) -> Option<&str> {
    let terminal = pattern.trim_end_matches('/').rsplit('/').next()?;
    let extension = terminal.strip_prefix("*.")?;
    (!extension.is_empty() && !has_glob_meta(extension)).then_some(extension)
}

fn has_glob_meta(pattern: &str) -> bool {
    pattern
        .bytes()
        .any(|byte| matches!(byte, b'*' | b'?' | b'[' | b']' | b'{' | b'}'))
}

fn fingerprint_files(files: &[LocalWorkspaceFile]) -> u64 {
    let mut hasher = DefaultHasher::new();
    files.hash(&mut hasher);
    hasher.finish()
}

fn recent_score(entry: &RecentFileState, now: u64) -> f32 {
    let age_ms = now.saturating_sub(entry.touched_at_ms) as f32;
    let recency = (-age_ms / RECENT_DECAY_HALF_LIFE_MS).exp();
    let frequency =
        ((entry.touch_count as f32) + 1.0).ln() / (RECENT_FREQUENCY_NORMALIZER + 1.0).ln();
    RECENT_RECENCY_WEIGHT * recency + (1.0 - RECENT_RECENCY_WEIGHT) * frequency.min(1.0)
}

fn normalize_recent_file_path(path: &str) -> Option<String> {
    let path = path.trim();
    if path.is_empty() {
        return None;
    }
    let normalized = normalize_relative_path_lossy(Path::new(path))?;
    (!normalized.is_empty()).then_some(normalized)
}

fn normalize_relative_path_lossy(path: &Path) -> Option<String> {
    let mut parts = Vec::new();
    for component in path.components() {
        match component {
            Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
            Component::CurDir => {}
            _ => return None,
        }
    }
    Some(parts.join("/"))
}

fn relative_to_base<'a>(path: &'a str, base: &WorkspacePath) -> Option<&'a str> {
    if base.is_root() {
        return Some(path);
    }
    let base = base.as_str().trim_end_matches('/');
    if path == base {
        Some("")
    } else {
        path.strip_prefix(base)
            .and_then(|tail| tail.strip_prefix('/'))
            .filter(|tail| !tail.is_empty())
    }
}

fn glob_matches(pattern: &glob::Pattern, path: &str) -> bool {
    let path = Path::new(path);
    pattern.matches_path(path)
        || path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| pattern.matches(name))
}

fn now_ms() -> u64 {
    system_time_ms(SystemTime::now())
}

fn system_time_ms(time: SystemTime) -> u64 {
    time.duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis() as u64)
        .unwrap_or_default()
}

#[cfg(test)]
#[path = "manifest/tests.rs"]
mod tests;