sift-grep 0.8.1

Grep-like CLI for sift-core
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
//! Background index refresh daemon: CLI spawn/IPC and server event loop.

mod ipc;
mod refresh;
mod watcher;

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};

use fslock::LockFile;
use sift_core::{
    CorpusMeta, FilterMeta, IndexCoverage, IndexRecord, Indexes, SnapshotId, StoreMeta, WalkMeta,
};
use thiserror::Error;

use crate::grep::paths::CorpusScope;
use crate::index::ReconcileOutcome;

use ipc::{DaemonRequest, DaemonResponse};
use refresh::{IndexRefresh, PendingIndex, RefreshResult, RefreshScope};
use watcher::CorpusWatcher;

pub use ipc::Daemon;

pub(crate) const DAEMON_LOCK: &str = "lock";
const READY_DIR: &str = "daemon-ready";
const READY_POLL_INTERVAL: Duration = Duration::from_millis(20);
const READY_TIMEOUT: Duration = Duration::from_secs(5);
const SPAWN_LOCK: &str = "daemon-spawn.lock";
const DEBOUNCE_MS: u64 = 250;
const SHUTDOWN_POLL: Duration = Duration::from_secs(1);

#[derive(Debug, Error)]
pub enum DaemonError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("daemon error: {0}")]
    Message(String),
}

impl DaemonError {
    pub(crate) fn message(msg: impl Into<String>) -> Self {
        Self::Message(msg.into())
    }
}

impl From<anyhow::Error> for DaemonError {
    fn from(value: anyhow::Error) -> Self {
        Self::Message(value.to_string())
    }
}

impl From<sift_core::Error> for DaemonError {
    fn from(value: sift_core::Error) -> Self {
        Self::Message(value.to_string())
    }
}

/// Options for the background daemon server loop.
pub struct ServeConfig {
    /// Internal spawn handshake file, written once the watcher is active.
    pub ready: Option<PathBuf>,
    pub idle_timeout: Duration,
}

/// Owns daemon process lifecycle and server runtime.
pub struct DaemonOrchestrator {
    sift_dir: PathBuf,
    init_root: Option<PathBuf>,
}

impl DaemonOrchestrator {
    const EXE: &'static str = "sift-daemon";
    #[cfg(windows)]
    const EXE_PLATFORM: &'static str = "sift-daemon.exe";

    #[must_use]
    pub const fn new(sift_dir: PathBuf, init_root: Option<PathBuf>) -> Self {
        Self {
            sift_dir,
            init_root,
        }
    }

    #[must_use]
    pub fn daemon(&self) -> Daemon {
        Daemon::new(self.sift_dir.clone())
    }

    /// Start the background daemon if IPC is not already reachable.
    ///
    /// # Errors
    ///
    /// Propagates spawn and readiness failures.
    pub fn start(&self) -> Result<Daemon, DaemonError> {
        let daemon = self.daemon();
        if !daemon.reachable()? {
            self.spawn()?;
        }
        Ok(daemon)
    }

    /// Run the daemon event loop (called from `sift-daemon` and integration tests).
    ///
    /// # Errors
    ///
    /// Propagates lock-acquisition, metadata, watcher, and IPC setup errors.
    pub fn serve(&self, config: ServeConfig, shutdown: &AtomicBool) -> Result<(), DaemonError> {
        std::fs::create_dir_all(&self.sift_dir)?;

        let sift_dir_raw = self.sift_dir.clone();
        let sift_dir = sift_dir_raw
            .canonicalize()
            .unwrap_or_else(|_| sift_dir_raw.clone());

        let lock_path = sift_dir.join(DAEMON_LOCK);
        let mut lock_file = LockFile::open(&lock_path)?;
        if !lock_file.try_lock()? {
            return Ok(());
        }

        let meta = self.store_meta(&sift_dir)?;

        let pending = Arc::new(Mutex::new(PendingIndex::None));
        let (tx, rx) = mpsc::channel::<Event>();

        let watcher_tx = tx.clone();
        let mut watcher = CorpusWatcher::new(&watcher_tx, &meta.corpus.root)?;

        let idle_timeout = config.idle_timeout;
        let mut phase = Phase::idle(idle_timeout);
        let mut ingest = IngestTracker::from_reconcile(
            Indexes::open(&sift_dir, &meta)
                .and_then(|mut indexes| ReconcileOutcome::rebuild(&mut indexes))?,
        );

        let ipc_tx = tx.clone();
        let ipc_daemon = Daemon::new(sift_dir.clone());
        let listener = ipc_daemon.bind_listener()?;
        std::thread::spawn(move || {
            Daemon::accept_clients(&listener, &ipc_tx);
        });

        if let Some(ready) = config.ready {
            let tmp = ready.with_extension("tmp");
            std::fs::write(&tmp, "")?;
            std::fs::rename(&tmp, &ready)?;
        }

        let store = StorePaths {
            canonical: &sift_dir,
            raw: &sift_dir_raw,
        };
        let events = EventChannel { rx: &rx, tx: &tx };
        let refresh = IndexRefresh {
            tx: events.tx,
            store: &sift_dir,
            pending: &pending,
        };
        let _lock = lock_file;

        DaemonRuntime {
            shutdown,
            pending: &pending,
            events,
            store,
            refresh,
            watcher: &mut watcher,
            phase: &mut phase,
            ingest: &mut ingest,
            idle_timeout,
            debounce: Duration::from_millis(DEBOUNCE_MS),
        }
        .run()
    }

    fn store_meta(&self, sift_dir: &Path) -> Result<StoreMeta, DaemonError> {
        match (StorePaths::read_meta(sift_dir), self.init_root.as_deref()) {
            (Ok(meta), _) => Ok(meta),
            (Err(_), Some(init_root)) => {
                let root = init_root.canonicalize()?;
                Ok(StoreMeta::new(
                    CorpusMeta {
                        root: root.clone(),
                        include_paths: Vec::new(),
                        exclude_paths: CorpusScope::excluded_paths(&root, sift_dir),
                    },
                    IndexCoverage::Complete,
                    WalkMeta {
                        follow_links: false,
                        one_file_system: false,
                        max_depth: None,
                        max_filesize: None,
                    },
                    FilterMeta {
                        visibility: sift_core::VisibilityConfig::default(),
                    },
                    IndexRecord::default_catalog(),
                ))
            }
            (Err(e), None) => Err(e),
        }
    }

    fn spawn(&self) -> Result<(), DaemonError> {
        let sift_dir = &self.sift_dir;
        let init_root = self.init_root.as_deref();
        let exe = Self::executable()?;

        std::fs::create_dir_all(sift_dir)?;

        let spawn_lock_path = sift_dir.join(SPAWN_LOCK);
        let mut spawn_lock = LockFile::open(&spawn_lock_path)?;
        if !spawn_lock.try_lock()? {
            return self.wait_until_reachable(Instant::now() + READY_TIMEOUT);
        }

        {
            let daemon_lock_path = sift_dir.join(DAEMON_LOCK);
            let mut daemon_lock = LockFile::open(&daemon_lock_path)?;
            if !daemon_lock.try_lock()? {
                return self.wait_until_reachable(Instant::now() + READY_TIMEOUT);
            }
        }

        if self.daemon().reachable()? {
            return Ok(());
        }

        let ready_dir = sift_dir.join(READY_DIR);
        std::fs::create_dir_all(&ready_dir)?;
        let pid = std::process::id();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let ready_path = ready_dir.join(format!("{pid}-{now}"));
        let _ = std::fs::remove_file(&ready_path);

        let log_path = sift_dir.join("daemon-spawn.log");
        let stderr = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
            .map_err(DaemonError::Io)?;

        let mut cmd = Command::new(&exe);
        cmd.arg("--sift-dir")
            .arg(sift_dir)
            .stdout(std::process::Stdio::null())
            .stderr(stderr)
            .stdin(std::process::Stdio::null());
        if let Some(root) = init_root {
            cmd.arg("--init-root").arg(root);
        }
        cmd.arg("--ready-file").arg(&ready_path);
        cmd.spawn()?;

        let deadline = Instant::now() + READY_TIMEOUT;
        loop {
            if ready_path.exists() {
                let _ = std::fs::remove_file(&ready_path);
                return Ok(());
            }
            if Instant::now() >= deadline {
                let log_tail = std::fs::read_to_string(&log_path)
                    .ok()
                    .map(|s| {
                        s.lines()
                            .rev()
                            .take(5)
                            .collect::<Vec<_>>()
                            .into_iter()
                            .rev()
                            .collect::<Vec<_>>()
                            .join("\n")
                    })
                    .filter(|s| !s.is_empty());
                let detail = log_tail
                    .map(|tail| format!("\nlast daemon log lines:\n{tail}"))
                    .unwrap_or_default();
                return Err(DaemonError::message(format!(
                    "daemon did not signal readiness within {READY_TIMEOUT:?}{detail}"
                )));
            }
            std::thread::sleep(READY_POLL_INTERVAL);
        }
    }

    fn wait_until_reachable(&self, deadline: Instant) -> Result<(), DaemonError> {
        loop {
            if self.daemon().reachable()? {
                return Ok(());
            }
            if Instant::now() >= deadline {
                return Err(DaemonError::message(format!(
                    "daemon did not become reachable within {READY_TIMEOUT:?}"
                )));
            }
            std::thread::sleep(READY_POLL_INTERVAL);
        }
    }

    /// Resolve the `sift-daemon` binary for spawn and integration tests.
    ///
    /// # Errors
    ///
    /// Returns an IO error if the current executable path cannot be read.
    pub fn executable() -> Result<PathBuf, DaemonError> {
        if let Some(path) = std::env::var_os("CARGO_BIN_EXE_sift-daemon") {
            return Ok(PathBuf::from(path));
        }

        let sift = std::env::current_exe().map_err(DaemonError::Io)?;
        let sibling = sift.with_file_name(Self::EXE);
        if sibling.exists() {
            return Ok(sibling);
        }
        #[cfg(windows)]
        {
            let sibling_exe = sift.with_file_name(Self::EXE_PLATFORM);
            if sibling_exe.exists() {
                return Ok(sibling_exe);
            }
        }

        if let Some(debug_bin) = sift
            .parent()
            .and_then(|p| p.parent())
            .map(|p| p.join(Self::EXE))
            .filter(|p| p.exists())
        {
            return Ok(debug_bin);
        }
        #[cfg(windows)]
        if let Some(debug_bin) = sift
            .parent()
            .and_then(|p| p.parent())
            .map(|p| p.join(Self::EXE_PLATFORM))
            .filter(|p| p.exists())
        {
            return Ok(debug_bin);
        }

        Ok(sibling)
    }
}

enum Event {
    FsChange(notify::Event),
    RefreshFinished(RefreshResult),
    /// IPC request plus the channel the accept loop waits on for the reply.
    Client {
        request: DaemonRequest,
        reply: mpsc::Sender<DaemonResponse>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PhaseInput {
    FsChange,
    RefreshComplete,
    DeadlineReached,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LoopAction {
    None,
    StartRefresh,
    Exit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RefreshFollowUp {
    None,
    Queued,
}

pub(super) enum Phase {
    Idle { deadline: Instant },
    Debouncing { deadline: Instant },
    Refreshing { follow_up: RefreshFollowUp },
}

impl Phase {
    fn idle(idle_timeout: Duration) -> Self {
        Self::Idle {
            deadline: Instant::now() + idle_timeout,
        }
    }

    const fn deadline(&self) -> Option<Instant> {
        match self {
            Self::Idle { deadline } | Self::Debouncing { deadline } => Some(*deadline),
            Self::Refreshing { .. } => None,
        }
    }

    const fn is_refreshing(&self) -> bool {
        matches!(self, Self::Refreshing { .. })
    }

    const fn is_debouncing(&self) -> bool {
        matches!(self, Self::Debouncing { .. })
    }

    fn advance(
        &mut self,
        input: PhaseInput,
        debounce: Duration,
        idle_timeout: Duration,
    ) -> LoopAction {
        let (next, action) = match (std::mem::replace(self, Self::idle(idle_timeout)), input) {
            (Self::Idle { .. } | Self::Debouncing { .. }, PhaseInput::FsChange) => (
                Self::Debouncing {
                    deadline: Instant::now() + debounce,
                },
                LoopAction::None,
            ),
            (Self::Debouncing { .. }, PhaseInput::DeadlineReached)
            | (
                Self::Refreshing {
                    follow_up: RefreshFollowUp::Queued,
                },
                PhaseInput::RefreshComplete,
            ) => (
                Self::Refreshing {
                    follow_up: RefreshFollowUp::None,
                },
                LoopAction::StartRefresh,
            ),
            (Self::Idle { .. }, PhaseInput::DeadlineReached) => {
                (Self::idle(idle_timeout), LoopAction::Exit)
            }
            (Self::Refreshing { .. }, PhaseInput::FsChange) => (
                Self::Refreshing {
                    follow_up: RefreshFollowUp::Queued,
                },
                LoopAction::None,
            ),
            (
                Self::Refreshing {
                    follow_up: RefreshFollowUp::None,
                },
                PhaseInput::RefreshComplete,
            ) => (Self::idle(idle_timeout), LoopAction::None),
            (state, _) => (state, LoopAction::None),
        };
        *self = next;
        action
    }

    fn drain_until_idle(&mut self, rx: &mpsc::Receiver<Event>, idle_timeout: Duration) {
        while self.is_refreshing() {
            match rx.recv_timeout(Duration::from_secs(1)) {
                Ok(Event::RefreshFinished(_)) => *self = Self::idle(idle_timeout),
                Ok(_) | Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
    }
}

struct IngestTracker {
    observed_generation: u64,
    committed_generation: u64,
    committed_snapshot_id: SnapshotId,
}

impl IngestTracker {
    fn from_reconcile(outcome: ReconcileOutcome) -> Self {
        Self {
            observed_generation: 0,
            committed_generation: 0,
            committed_snapshot_id: outcome.snapshot_id,
        }
    }

    const fn observe(&mut self) {
        self.observed_generation = self.observed_generation.saturating_add(1);
    }

    fn finish_refresh(&mut self, result: &RefreshResult) {
        if let RefreshResult::Success(outcome) = result {
            self.committed_generation = self.observed_generation;
            self.committed_snapshot_id = outcome.snapshot_id.clone();
        }
    }

    fn validate_snapshot(
        &self,
        id: &SnapshotId,
        phase: &Phase,
        pending: &PendingIndex,
    ) -> DaemonResponse {
        if &self.committed_snapshot_id == id
            && self.observed_generation == self.committed_generation
            && !pending.is_pending()
            && !phase.is_refreshing()
            && !phase.is_debouncing()
        {
            DaemonResponse::SnapshotValid
        } else {
            DaemonResponse::SnapshotBehind
        }
    }
}

pub(super) struct StorePaths<'a> {
    canonical: &'a Path,
    raw: &'a Path,
}

impl StorePaths<'_> {
    pub(super) fn read_meta(sift_dir: &Path) -> Result<StoreMeta, DaemonError> {
        let mut meta = StoreMeta::read(sift_dir)
            .map_err(|e| DaemonError::message(format!("no store metadata: {e}")))?;
        if meta.indexes.is_empty() {
            meta.indexes = IndexRecord::default_catalog();
        }
        Ok(meta)
    }

    fn is_internal(&self, path: &Path) -> bool {
        path.starts_with(self.canonical) || path.starts_with(self.raw)
    }
}

struct EventChannel<'a> {
    rx: &'a mpsc::Receiver<Event>,
    tx: &'a mpsc::Sender<Event>,
}

enum ChannelPoll {
    Continue,
    Done,
    Input(PhaseInput),
    RefreshFinished(RefreshResult),
    Client {
        request: DaemonRequest,
        reply: mpsc::Sender<DaemonResponse>,
    },
}

struct DaemonRuntime<'a> {
    shutdown: &'a AtomicBool,
    pending: &'a Arc<Mutex<PendingIndex>>,
    events: EventChannel<'a>,
    store: StorePaths<'a>,
    refresh: IndexRefresh<'a>,
    watcher: &'a mut CorpusWatcher,
    phase: &'a mut Phase,
    ingest: &'a mut IngestTracker,
    idle_timeout: Duration,
    debounce: Duration,
}

impl DaemonRuntime<'_> {
    fn run(&mut self) -> Result<(), DaemonError> {
        loop {
            if self.shutdown.load(Ordering::Relaxed) {
                self.phase
                    .drain_until_idle(self.events.rx, self.idle_timeout);
                return Ok(());
            }

            let timeout = self.phase.deadline().map_or(SHUTDOWN_POLL, |d| {
                d.saturating_duration_since(Instant::now())
                    .min(SHUTDOWN_POLL)
            });

            match self.events.poll(&self.store, self.phase, timeout) {
                ChannelPoll::Done => return Ok(()),
                ChannelPoll::Client { request, reply } => {
                    self.handle_client(request, &reply)?;
                }
                ChannelPoll::RefreshFinished(result) => self.finish_refresh(&result),
                ChannelPoll::Input(input) => {
                    if self.advance(input)? {
                        return Ok(());
                    }
                }
                ChannelPoll::Continue => {}
            }
        }
    }

    fn handle_client(
        &mut self,
        request: DaemonRequest,
        reply: &mpsc::Sender<DaemonResponse>,
    ) -> Result<(), DaemonError> {
        match request {
            DaemonRequest::ValidateSnapshot(id) => {
                let response = {
                    let pending = PendingIndex::lock(self.pending)?;
                    self.ingest.validate_snapshot(&id, self.phase, &pending)
                };
                let _ = reply.send(response);
            }
            DaemonRequest::Index(paths) => {
                self.ingest.observe();
                let paths = match StorePaths::read_meta(self.store.raw)
                    .ok()
                    .and_then(|meta| Indexes::open(self.store.raw, &meta).ok())
                {
                    Some(indexes) => match indexes.files() {
                        Some(files) => files.retain_unindexed(paths),
                        None => paths,
                    },
                    None => paths,
                };
                self.refresh.apply_index(
                    paths,
                    reply,
                    self.watcher,
                    self.store.canonical,
                    self.phase,
                )?;
            }
        }
        Ok(())
    }

    fn finish_refresh(&mut self, result: &RefreshResult) {
        self.ingest.finish_refresh(result);
        let action = self.phase.advance(
            PhaseInput::RefreshComplete,
            self.debounce,
            self.idle_timeout,
        );
        if matches!(action, LoopAction::StartRefresh) {
            self.refresh
                .begin(RefreshScope::CorpusAndPending, self.phase);
        }
    }

    fn advance(&mut self, input: PhaseInput) -> Result<bool, DaemonError> {
        if matches!(input, PhaseInput::FsChange) {
            self.ingest.observe();
        }
        let pending_refresh_due = if matches!(self.phase, Phase::Idle { .. })
            && matches!(input, PhaseInput::DeadlineReached)
        {
            PendingIndex::lock(self.pending)?.is_pending()
        } else {
            false
        };
        if pending_refresh_due {
            self.refresh.begin(RefreshScope::PendingOnly, self.phase);
            return Ok(false);
        }
        match self.phase.advance(input, self.debounce, self.idle_timeout) {
            LoopAction::None => Ok(false),
            LoopAction::StartRefresh => {
                self.refresh
                    .begin(RefreshScope::CorpusAndPending, self.phase);
                Ok(false)
            }
            LoopAction::Exit => Ok(true),
        }
    }
}

impl EventChannel<'_> {
    fn poll(&self, store: &StorePaths<'_>, phase: &Phase, timeout: Duration) -> ChannelPoll {
        match self.rx.recv_timeout(timeout) {
            Ok(Event::FsChange(event)) => {
                let internal = matches!(event.kind, notify::EventKind::Access(_))
                    || event.paths.iter().any(|path| store.is_internal(path));
                if internal {
                    ChannelPoll::Continue
                } else {
                    ChannelPoll::Input(PhaseInput::FsChange)
                }
            }
            Ok(Event::RefreshFinished(result)) => ChannelPoll::RefreshFinished(result),
            Ok(Event::Client { request, reply }) => ChannelPoll::Client { request, reply },
            Err(mpsc::RecvTimeoutError::Timeout) => {
                if phase.deadline().is_some_and(|d| Instant::now() >= d) {
                    ChannelPoll::Input(PhaseInput::DeadlineReached)
                } else {
                    ChannelPoll::Continue
                }
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => ChannelPoll::Done,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sift_core::GramWidth;
    use sift_core::VisibilityConfig;
    use std::sync::atomic::Ordering;
    use tempfile::TempDir;

    const DEBOUNCE: Duration = Duration::from_mins(1);
    const IDLE: Duration = Duration::from_mins(10);

    #[test]
    fn round_trip_index_paths() {
        let paths = vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")];
        let mut buf = Vec::new();
        DaemonRequest::index(paths.clone())
            .encode(&mut buf)
            .unwrap();
        let op = DaemonRequest::decode(buf.as_slice()).unwrap();
        assert_eq!(op, DaemonRequest::Index(paths));
    }

    #[test]
    fn round_trip_index_full() {
        let mut buf = Vec::new();
        DaemonRequest::index(vec![]).encode(&mut buf).unwrap();
        let op = DaemonRequest::decode(buf.as_slice()).unwrap();
        assert_eq!(op, DaemonRequest::Index(vec![]));
    }

    #[cfg(unix)]
    #[test]
    fn index_round_trip_over_unix_stream() {
        use std::os::unix::net::UnixStream;
        use std::thread;

        let (mut client, server) = UnixStream::pair().unwrap();
        let paths = vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")];
        let expected = DaemonRequest::index(paths.clone());

        let handle = thread::spawn(move || {
            let mut server = server;
            let op = DaemonRequest::decode(&mut server).unwrap();
            assert_eq!(op, DaemonRequest::index(paths));
            DaemonResponse::Accepted.encode(&mut server).unwrap();
        });

        expected.encode(&mut client).unwrap();
        let response = DaemonResponse::decode(&mut client).unwrap();
        assert_eq!(response, DaemonResponse::Accepted);
        handle.join().unwrap();
    }

    #[test]
    fn pending_index_merge_partial_paths() {
        let mut pending = PendingIndex::None;
        pending.push(vec![PathBuf::from("a.rs")]);
        pending.push(vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")]);
        assert_eq!(
            pending.take(),
            Some(vec![PathBuf::from("a.rs"), PathBuf::from("b.rs")])
        );
    }

    #[test]
    fn pending_index_full_promotes_and_clears_partials() {
        let mut pending = PendingIndex::None;
        pending.push(vec![PathBuf::from("a.rs")]);
        pending.push(Vec::new());
        assert_eq!(pending.take(), Some(Vec::new()));
        assert!(!pending.is_pending());
    }

    #[test]
    fn phase_idle_fs_change_transitions_to_debouncing() {
        let mut phase = Phase::idle(IDLE);
        let action = phase.advance(PhaseInput::FsChange, DEBOUNCE, IDLE);
        assert!(matches!(phase, Phase::Debouncing { .. }));
        assert_eq!(action, LoopAction::None);
    }

    #[test]
    fn phase_idle_deadline_reached_exits() {
        let mut phase = Phase::idle(IDLE);
        let action = phase.advance(PhaseInput::DeadlineReached, DEBOUNCE, IDLE);
        assert!(matches!(phase, Phase::Idle { .. }));
        assert_eq!(action, LoopAction::Exit);
    }

    #[test]
    fn phase_debouncing_deadline_reached_starts_refresh() {
        let mut phase = Phase::Debouncing {
            deadline: Instant::now(),
        };
        let action = phase.advance(PhaseInput::DeadlineReached, DEBOUNCE, IDLE);
        assert!(matches!(
            phase,
            Phase::Refreshing {
                follow_up: RefreshFollowUp::None
            }
        ));
        assert_eq!(action, LoopAction::StartRefresh);
    }

    #[test]
    fn phase_refreshing_complete_with_follow_up_restarts_refresh() {
        let mut phase = Phase::Refreshing {
            follow_up: RefreshFollowUp::Queued,
        };
        let action = phase.advance(PhaseInput::RefreshComplete, DEBOUNCE, IDLE);
        assert!(matches!(
            phase,
            Phase::Refreshing {
                follow_up: RefreshFollowUp::None
            }
        ));
        assert_eq!(action, LoopAction::StartRefresh);
    }

    #[test]
    fn pending_paths_restored_on_reconcile_failure() {
        let dir = TempDir::new().unwrap();
        let sift_dir = dir.path().join(".sift");
        std::fs::create_dir_all(&sift_dir).unwrap();

        let mut pending = PendingIndex::Paths(vec![PathBuf::from("missing.rs")]);
        let meta = StoreMeta::new(
            CorpusMeta {
                root: dir.path().join("does-not-exist"),
                include_paths: Vec::new(),
                exclude_paths: Vec::new(),
            },
            IndexCoverage::Complete,
            WalkMeta {
                follow_links: false,
                one_file_system: false,
                max_depth: None,
                max_filesize: None,
            },
            FilterMeta {
                visibility: VisibilityConfig::default(),
            },
            vec![IndexRecord::ngram(GramWidth::TRIGRAM)],
        );
        StoreMeta::write(&meta, &sift_dir).unwrap();

        pending.reconcile(&sift_dir, &meta);
        assert!(pending.is_pending());
    }

    #[test]
    fn rebind_watcher_skips_when_root_unchanged() {
        let dir = TempDir::new().unwrap();
        let (tx, _rx) = mpsc::channel();
        let mut watcher = CorpusWatcher::new(&tx, dir.path()).unwrap();
        watcher.rebind(dir.path()).unwrap();
        assert_eq!(watcher.root.as_path(), dir.path());
    }

    #[test]
    fn rebind_watcher_switches_to_new_corpus_root() {
        let dir = TempDir::new().unwrap();
        let old_root = dir.path().join("old");
        let new_root = dir.path().join("new");
        std::fs::create_dir_all(&old_root).unwrap();
        std::fs::create_dir_all(&new_root).unwrap();

        let (tx, _rx) = mpsc::channel();
        let mut watcher = CorpusWatcher::new(&tx, &old_root).unwrap();
        watcher.rebind(&new_root).unwrap();
        assert_eq!(watcher.root.as_path(), new_root.as_path());
    }

    #[test]
    fn serve_stops_on_shutdown() {
        let dir = TempDir::new().unwrap();
        let sift_dir = dir.path().join(".sift");

        let meta = StoreMeta::new(
            CorpusMeta {
                root: dir.path().to_path_buf(),
                include_paths: Vec::new(),
                exclude_paths: Vec::new(),
            },
            IndexCoverage::Complete,
            WalkMeta {
                follow_links: false,
                one_file_system: false,
                max_depth: None,
                max_filesize: None,
            },
            FilterMeta {
                visibility: VisibilityConfig::default(),
            },
            vec![IndexRecord::ngram(GramWidth::TRIGRAM)],
        );
        std::fs::create_dir_all(&sift_dir).unwrap();
        StoreMeta::write(&meta, &sift_dir).unwrap();

        let daemon = DaemonOrchestrator::new(sift_dir, None);
        let shutdown = Arc::new(AtomicBool::new(false));

        let handle = std::thread::spawn({
            let shutdown = Arc::clone(&shutdown);
            move || {
                daemon
                    .serve(
                        ServeConfig {
                            ready: None,
                            idle_timeout: Duration::from_mins(2),
                        },
                        shutdown.as_ref(),
                    )
                    .unwrap();
            }
        });

        std::thread::sleep(Duration::from_millis(100));
        shutdown.store(true, Ordering::Relaxed);
        handle.join().unwrap();
    }

    #[test]
    fn serve_returns_early_when_lock_held() {
        let dir = TempDir::new().unwrap();
        let sift_dir = dir.path().join(".sift");
        std::fs::create_dir_all(&sift_dir).unwrap();
        let lock_path = sift_dir.join(DAEMON_LOCK);
        let mut lock = LockFile::open(&lock_path).unwrap();
        lock.try_lock().unwrap();

        let daemon = DaemonOrchestrator::new(sift_dir, None);
        let shutdown = AtomicBool::new(false);
        daemon
            .serve(
                ServeConfig {
                    ready: None,
                    idle_timeout: Duration::from_mins(2),
                },
                &shutdown,
            )
            .unwrap();
    }

    #[test]
    fn ensure_running_skips_spawn_when_ipc_reachable() {
        let dir = TempDir::new().unwrap();
        let sift_dir = dir.path().join(".sift");

        let meta = StoreMeta::new(
            CorpusMeta {
                root: dir.path().to_path_buf(),
                include_paths: Vec::new(),
                exclude_paths: Vec::new(),
            },
            IndexCoverage::Complete,
            WalkMeta {
                follow_links: false,
                one_file_system: false,
                max_depth: None,
                max_filesize: None,
            },
            FilterMeta {
                visibility: VisibilityConfig::default(),
            },
            vec![IndexRecord::ngram(GramWidth::TRIGRAM)],
        );
        std::fs::create_dir_all(&sift_dir).unwrap();
        StoreMeta::write(&meta, &sift_dir).unwrap();

        let daemon = DaemonOrchestrator::new(sift_dir.clone(), None);
        let shutdown = Arc::new(AtomicBool::new(false));
        let handle = std::thread::spawn({
            let shutdown = Arc::clone(&shutdown);
            move || {
                daemon
                    .serve(
                        ServeConfig {
                            ready: None,
                            idle_timeout: Duration::from_mins(2),
                        },
                        shutdown.as_ref(),
                    )
                    .unwrap();
            }
        });

        let deadline = Instant::now() + Duration::from_secs(5);
        while !Daemon::new(sift_dir.clone()).reachable().unwrap() {
            assert!(
                Instant::now() < deadline,
                "daemon ipc did not become reachable"
            );
            std::thread::sleep(Duration::from_millis(20));
        }

        DaemonOrchestrator::new(sift_dir, None).start().unwrap();

        shutdown.store(true, Ordering::Relaxed);
        handle.join().unwrap();
    }
}