Skip to main content

paper/
bootstrap.rs

1//! First-run automation.
2//!
3//! The installer cannot set Paper up: `install.sh`, `cargo install` and the
4//! Claude plugin have no common post-install hook, and an installer should not
5//! start a long-lived service. So the work happens here, on the first ordinary
6//! command, and only once.
7//!
8//! Effects, in order:
9//!   1. register the background indexer as a user service (launchd/systemd), or
10//!      fall back to a detached daemon for this login session;
11//!   2. the daemon downloads the default models in the background (the
12//!      embedding model first, then the optional reranker);
13//!   3. the daemon indexes the auto-discovered roots immediately (instead of
14//!      waiting for the first five-minute scheduler tick).
15//!
16//! Escape hatches: `PAPER_NO_AUTOSTART=1` (never), `PAPER_OFFLINE=1` (no
17//! network at all), `PAPER_FORCE_BOOTSTRAP=1` (run even when `PAPER_HOME` is
18//! set), and `paper daemon-control uninstall` (turn it off afterwards).
19//!
20//! `CI` suppresses it too: a build machine must never index its own files.
21
22use std::fs::{self, File, TryLockError};
23use std::io;
24use std::path::Path;
25use std::time::{Duration, SystemTime, UNIX_EPOCH};
26
27use crate::core::paths::Paths;
28
29/// Bumped when the state file layout changes; an older file is ignored.
30const STATE_VERSION: &str = "1";
31/// Do not retry a failed service install more often than this.
32const RETRY_AFTER: Duration = Duration::from_secs(60 * 60);
33
34const STATE_FILE: &str = "bootstrap.state";
35const LOCK_FILE: &str = "bootstrap.lock";
36
37/// Commands that must not trigger onboarding: they either manage the daemon
38/// themselves, are diagnostics, or are explicitly user-driven work.
39const SKIP_COMMANDS: &[&str] = &[
40    "bootstrap",
41    "daemon",
42    "daemon-control",
43    "doctor",
44    "uninstall",
45    "models",
46    "index",
47    // `serve` is the MCP server an editor starts, often several at once. It
48    // must answer the handshake and serve keyword results immediately; it must
49    // never install a service or take the setup lock. Without this, five MCP
50    // sessions opening together serialised behind one lock and each tried to
51    // provision — the slowest possible answer to a first `initialize`.
52    "serve",
53];
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56enum ServiceState {
57    /// Never attempted.
58    Pending,
59    /// Service installed, or a session daemon was started successfully.
60    Installed,
61    /// Every attempt failed; retried later, but not on every command.
62    Unavailable,
63}
64
65#[derive(Debug)]
66struct State {
67    service: ServiceState,
68    updated: u64,
69}
70
71impl Default for State {
72    fn default() -> Self {
73        Self {
74            service: ServiceState::Pending,
75            updated: 0,
76        }
77    }
78}
79
80impl State {
81    fn load(path: &Path) -> Self {
82        let Ok(text) = fs::read_to_string(path) else {
83            return Self::default();
84        };
85        if !text
86            .lines()
87            .any(|line| line.trim() == format!("version={STATE_VERSION}"))
88        {
89            return Self::default();
90        }
91        let mut state = Self::default();
92        for line in text.lines() {
93            let Some((key, value)) = line.split_once('=') else {
94                continue;
95            };
96            match key.trim() {
97                "service" => {
98                    state.service = match value.trim() {
99                        "installed" => ServiceState::Installed,
100                        "unavailable" => ServiceState::Unavailable,
101                        _ => ServiceState::Pending,
102                    }
103                }
104                "updated" => state.updated = value.trim().parse().unwrap_or(0),
105                _ => {}
106            }
107        }
108        state
109    }
110
111    fn save(&self, path: &Path) -> io::Result<()> {
112        let contents = format!(
113            "version={STATE_VERSION}\nservice={}\nupdated={}\n",
114            match self.service {
115                ServiceState::Pending => "pending",
116                ServiceState::Installed => "installed",
117                ServiceState::Unavailable => "unavailable",
118            },
119            self.updated
120        );
121        let tmp = path.with_extension("tmp");
122        fs::write(&tmp, contents)?;
123        fs::rename(&tmp, path)
124    }
125
126    fn should_retry(&self, now: u64) -> bool {
127        match self.service {
128            ServiceState::Installed => false,
129            ServiceState::Pending => true,
130            ServiceState::Unavailable => now.saturating_sub(self.updated) >= RETRY_AFTER.as_secs(),
131        }
132    }
133}
134
135/// Environment switches, read once so the decision is testable without touching
136/// the process environment.
137#[derive(Clone, Copy, Debug, Default)]
138struct Switches {
139    offline: bool,
140    no_autostart: bool,
141    ci: bool,
142    portable: bool,
143    force: bool,
144}
145
146impl Switches {
147    fn from_process() -> Self {
148        Self {
149            offline: present("PAPER_OFFLINE"),
150            no_autostart: present("PAPER_NO_AUTOSTART"),
151            ci: present("CI"),
152            portable: present("PAPER_HOME"),
153            force: present("PAPER_FORCE_BOOTSTRAP"),
154        }
155    }
156}
157
158fn present(name: &str) -> bool {
159    match std::env::var(name) {
160        Ok(value) => !value.is_empty() && value != "0",
161        Err(_) => false,
162    }
163}
164
165fn should_run(command: &str, switches: &Switches) -> bool {
166    onboarding_enabled(switches) && !SKIP_COMMANDS.contains(&command)
167}
168
169/// Whether onboarding is allowed to happen at all on this machine. Separate from
170/// [`should_run`] because a skipped command still needs to know whether the
171/// silence is deliberate.
172fn onboarding_enabled(switches: &Switches) -> bool {
173    if switches.offline || switches.no_autostart || switches.ci {
174        return false;
175    }
176    // `PAPER_HOME` marks tests and portable installs; never write services there.
177    !switches.portable || switches.force
178}
179
180/// The one thing a skip-listed command says when setup has never run.
181///
182/// `serve` is skip-listed on purpose (see [`SKIP_COMMANDS`]), but a machine whose
183/// only entry point is the editor would otherwise never be provisioned *and*
184/// never learn why. This returns the notice for exactly that case and `None` for
185/// every other skip — diagnostics and portable/CI runs stay silent.
186///
187/// Every command named here must exist. An earlier draft pointed at
188/// `paper bootstrap`, which is not a subcommand: the one sentence an
189/// editor-only user gets would have handed them a usage dump.
190fn pending_setup_notice(command: &str, switches: &Switches, state: &State) -> Option<&'static str> {
191    if command != "serve" || !onboarding_enabled(switches) {
192        return None;
193    }
194    if state.service != ServiceState::Pending {
195        return None;
196    }
197    Some(
198        "paper: setup has not run on this machine yet — background indexing is off and search \
199         is keyword-only until it does. Run `paper index` once; keyword search here picks it up \
200         on the next query (restart this server to load the embedding model for semantic \
201         search).",
202    )
203}
204
205fn now_unix() -> u64 {
206    SystemTime::now()
207        .duration_since(UNIX_EPOCH)
208        .map(|d| d.as_secs())
209        .unwrap_or(0)
210}
211
212/// Guards the one-time setup against parallel invocations (an editor can start
213/// several MCP sessions at once, each calling `paper serve`).
214///
215/// This is a kernel advisory lock (`flock` / `LockFileEx`, through
216/// [`File::try_lock`]), not a "does the file exist?" test. The difference is
217/// the whole point: a file-based lock has to guess whether its owner is still
218/// alive, and the guess is racy — two processes can both read the same
219/// 15-minute-old file, both decide it is stale, both delete it, and both
220/// "acquire" it. A kernel lock is released when the holder's descriptor closes,
221/// which the OS does even when the holder is killed, so no staleness heuristic
222/// (and no reliance on an mtime a clock change or a restore can move) remains.
223struct BootstrapLock {
224    file: File,
225}
226
227impl BootstrapLock {
228    fn acquire(path: &Path) -> Option<Self> {
229        let file = match fs::OpenOptions::new()
230            .read(true)
231            .write(true)
232            .create(true)
233            .truncate(false)
234            .open(path)
235        {
236            Ok(file) => file,
237            Err(err) => {
238                // A lock file that cannot even be opened (read-only mount, a
239                // backup restored under another owner) must not silently disable
240                // onboarding for the life of the install.
241                tracing::warn!(
242                    "could not open the setup lock at {} ({err:#}); background setup is skipped \
243                     this run",
244                    path.display()
245                );
246                return None;
247            }
248        };
249        match file.try_lock() {
250            Ok(()) => Some(Self { file }),
251            // `WouldBlock` is the ordinary "someone else is setting up" answer.
252            Err(TryLockError::WouldBlock) => None,
253            // Any other error means this filesystem cannot lock at all (some
254            // NFS/SMB/FUSE mounts). Refusing to pretend the lock is ours is
255            // right; doing it in silence is not.
256            Err(TryLockError::Error(err)) => {
257                tracing::warn!(
258                    "this filesystem cannot lock {} ({err:#}); background setup is skipped this \
259                     run — `paper daemon-control install` does the same work without the race",
260                    path.display()
261                );
262                None
263            }
264        }
265    }
266}
267
268impl Drop for BootstrapLock {
269    fn drop(&mut self) {
270        // Dropping the handle releases the lock; unlocking first makes that
271        // explicit and keeps the release observable in this function.
272        let _ = self.file.unlock();
273    }
274}
275
276/// Called from `main` before dispatching `command`. Never fails the command and
277/// never blocks on the network: the daemon does the slow work.
278pub async fn maybe_autostart(command: &str) {
279    let switches = Switches::from_process();
280    if !should_run(command, &switches) {
281        let state = State::load(&Paths::new().base_dir().join(STATE_FILE));
282        if let Some(notice) = pending_setup_notice(command, &switches, &state) {
283            // One line on stderr, no lock, no service, no network: the server
284            // still answers `initialize` immediately.
285            eprintln!("{notice}");
286        }
287        return;
288    }
289
290    let paths = Paths::new();
291    if paths.ensure_dirs().is_err() {
292        return;
293    }
294
295    let state_path = paths.base_dir().join(STATE_FILE);
296    let lock_path = paths.base_dir().join(LOCK_FILE);
297
298    let state = State::load(&state_path);
299    if !state.should_retry(now_unix()) {
300        return;
301    }
302
303    let Some(_lock) = BootstrapLock::acquire(&lock_path) else {
304        return;
305    };
306
307    // Another process may have finished while we waited.
308    let state = State::load(&state_path);
309    if !state.should_retry(now_unix()) {
310        return;
311    }
312
313    eprintln!(
314        "paper: first run — setting up background indexing for your documents \
315         (disable with PAPER_NO_AUTOSTART=1)"
316    );
317
318    let next = match crate::cli::daemon::ensure_service() {
319        Ok(()) => State {
320            service: ServiceState::Installed,
321            updated: now_unix(),
322        },
323        Err(error) => {
324            tracing::warn!("could not install the Paper background service: {error:#}");
325            State {
326                service: ServiceState::Unavailable,
327                updated: now_unix(),
328            }
329        }
330    };
331    let _ = next.save(&state_path);
332}
333
334/// Download the default models if they are missing. Runs inside the daemon, so
335/// the user's command has already returned. Failure is not fatal: keyword
336/// search keeps working and the next daemon start tries again.
337///
338/// Indexing needs the embedding model, so this is awaited before the first
339/// pass. The reranker is not fetched here: see [`ensure_reranker`].
340pub async fn ensure_models(workspace: &crate::cli::Workspace) {
341    let switches = Switches::from_process();
342    if switches.offline || switches.no_autostart {
343        return;
344    }
345    #[cfg(feature = "embeddings")]
346    {
347        if !workspace.embedding_model_installed() {
348            if let Ok(spec) = workspace
349                .model_manager
350                .spec(crate::core::models::MULTILINGUAL_EMBEDDING)
351            {
352                set_setup_status(
353                    &workspace.paths,
354                    &format!(
355                        "downloading the embedding model ({} MB) — keyword and semantic search start once it lands",
356                        spec.size_mb()
357                    ),
358                );
359            }
360            tracing::info!(
361                "downloading the default multilingual embedding model in the background"
362            );
363            if let Err(error) = workspace
364                .model_manager
365                .ensure(crate::core::models::MULTILINGUAL_EMBEDDING)
366                .await
367            {
368                tracing::warn!(
369                    "embedding model download failed ({error:#}); continuing with keyword search"
370                );
371            }
372        }
373    }
374    #[cfg(not(feature = "embeddings"))]
375    let _ = workspace;
376
377    // OCR weights are small (~16 MB) and independent of the embedding stack, so
378    // they are fetched even in a keyword-only build. A failure only disables
379    // OCR; indexing still proceeds with whatever text layers exist.
380    #[cfg(feature = "ocr")]
381    if std::env::var_os("PAPER_NO_OCR").is_none() && !crate::core::extract::ocr::models_present() {
382        tracing::info!("downloading OCR models in the background");
383        if let Err(error) = crate::core::extract::ocr::ensure_models().await {
384            tracing::warn!("OCR model download failed ({error:#}); scanned pages stay unindexed");
385        }
386    }
387}
388
389/// Download the effective reranker (up to ~1.1 GB) if missing. Only search processes
390/// use it and it only improves ordering, so the daemon spawns this instead of
391/// delaying the first index pass. A failed or skipped download costs accuracy,
392/// never functionality. `PAPER_NO_RERANKER=1` keeps it off disk entirely.
393pub async fn ensure_reranker(manager: &crate::core::models::ModelManager, reranker_id: &str) {
394    let switches = Switches::from_process();
395    if switches.offline || switches.no_autostart {
396        return;
397    }
398    #[cfg(feature = "embeddings")]
399    if std::env::var_os("PAPER_NO_RERANKER").is_none() && !manager.is_installed(reranker_id) {
400        tracing::info!("downloading the reranker in the background");
401        if let Err(error) = manager.ensure(reranker_id).await {
402            tracing::warn!("reranker download failed ({error:#}); results stay dense+keyword");
403        }
404    }
405    #[cfg(not(feature = "embeddings"))]
406    let _ = (manager, reranker_id);
407}
408
409/// `PAPER_OFFLINE` is set: nothing may touch the network.
410pub fn is_offline() -> bool {
411    Switches::from_process().offline
412}
413
414const SETUP_STATUS_FILE: &str = "setup-status";
415
416// shortcut: a daemon that dies mid-setup leaves a stale line until the service
417// restarts and rewrites it; upgrade to a pid/heartbeat check if that bites.
418/// Record what the daemon is doing in the background so searches can say so.
419/// Best effort: a failed write only loses the hint.
420pub fn set_setup_status(paths: &Paths, phase: &str) {
421    let _ = std::fs::write(paths.base_dir().join(SETUP_STATUS_FILE), phase);
422}
423
424pub fn clear_setup_status(paths: &Paths) {
425    let _ = std::fs::remove_file(paths.base_dir().join(SETUP_STATUS_FILE));
426}
427
428/// The current background phase, if setup is in progress.
429pub fn setup_status(paths: &Paths) -> Option<String> {
430    let text = std::fs::read_to_string(paths.base_dir().join(SETUP_STATUS_FILE)).ok()?;
431    let text = text.trim();
432    (!text.is_empty()).then(|| text.to_string())
433}
434
435/// True when the index holds no chunks yet, which is the moment to index
436/// immediately rather than wait for the five-minute incremental tick.
437pub fn index_is_empty(paths: &Paths) -> bool {
438    let Ok(connection) = crate::core::index::Connection::open(&paths.db_path()) else {
439        return true;
440    };
441    if crate::core::index::init_db(&connection).is_err() {
442        return true;
443    }
444    connection
445        .query_i64("SELECT COUNT(*) FROM chunks")
446        .map(|count| count == 0)
447        .unwrap_or(true)
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn skips_when_disabled() {
456        let enabled = Switches::default();
457        assert!(should_run("search", &enabled));
458
459        for switches in [
460            Switches {
461                offline: true,
462                ..enabled
463            },
464            Switches {
465                no_autostart: true,
466                ..enabled
467            },
468            Switches {
469                ci: true,
470                ..enabled
471            },
472        ] {
473            assert!(!should_run("search", &switches));
474        }
475    }
476
477    #[test]
478    fn skips_portable_installs_unless_forced() {
479        let portable = Switches {
480            portable: true,
481            ..Switches::default()
482        };
483        assert!(!should_run("search", &portable));
484        assert!(should_run(
485            "search",
486            &Switches {
487                force: true,
488                ..portable
489            }
490        ));
491    }
492
493    #[test]
494    fn skips_commands_that_manage_the_daemon() {
495        for command in SKIP_COMMANDS {
496            assert!(!should_run(command, &Switches::default()), "{command}");
497        }
498        for command in ["search", "answer", "aggregate"] {
499            assert!(should_run(command, &Switches::default()), "{command}");
500        }
501    }
502
503    /// `serve` is what an editor starts — often five sessions at once — so it is
504    /// the one command that must never be the thing that installs a service.
505    #[test]
506    fn serve_never_bootstraps() {
507        assert!(!should_run("serve", &Switches::default()));
508        // Not even the portable force switch, which exists for installs that
509        // want onboarding: a server session is never the right place for it.
510        let forced_portable = Switches {
511            portable: true,
512            force: true,
513            ..Switches::default()
514        };
515        assert!(!should_run("serve", &forced_portable));
516    }
517
518    /// A lock file with nobody holding it is what a killed run leaves behind.
519    /// The old `create_new` test read that state as "someone is setting up".
520    #[test]
521    fn a_lock_file_left_by_a_dead_run_does_not_block_setup() {
522        let dir = tempfile::tempdir().expect("tempdir");
523        let path = dir.path().join(LOCK_FILE);
524        fs::write(&path, b"").expect("write");
525        assert!(
526            BootstrapLock::acquire(&path).is_some(),
527            "an unheld lock file must be acquirable"
528        );
529    }
530
531    /// The basic contract: exclusive while held, released on drop. On its own
532    /// this would also pass against the old `create_new` file lock — the test
533    /// that actually distinguishes the kernel lock is
534    /// [`a_lock_is_released_when_its_holder_is_killed`], which no file-existence
535    /// scheme can pass.
536    #[test]
537    fn a_held_lock_is_exclusive_and_released_on_drop() {
538        let dir = tempfile::tempdir().expect("tempdir");
539        let path = dir.path().join(LOCK_FILE);
540        let first = BootstrapLock::acquire(&path).expect("first acquisition");
541        assert!(
542            BootstrapLock::acquire(&path).is_none(),
543            "a second holder must be refused while the first lives"
544        );
545        drop(first);
546        assert!(
547            BootstrapLock::acquire(&path).is_some(),
548            "dropping the guard must release the lock"
549        );
550    }
551
552    /// Child half of [`a_lock_is_released_when_its_holder_is_killed`]: acquire,
553    /// say so on stdout, then wait to be killed. Ignored by default; the parent
554    /// runs it by exact name in a separate process.
555    #[test]
556    #[ignore = "child process helper for a_lock_is_released_when_its_holder_is_killed"]
557    fn lock_child_acquires_and_waits() {
558        let Ok(path) = std::env::var("PAPER_LOCK_CHILD") else {
559            return;
560        };
561        let lock = BootstrapLock::acquire(Path::new(&path)).expect("child acquires");
562        println!("acquired");
563        std::thread::sleep(Duration::from_secs(60));
564        drop(lock);
565    }
566
567    /// A lock file that cannot even be opened (a read-only mount, a backup
568    /// restored under another owner) must never be mistaken for a held lock.
569    #[cfg(unix)]
570    #[test]
571    fn a_lock_file_that_cannot_be_opened_is_refused_not_assumed_held() {
572        use std::os::unix::fs::PermissionsExt;
573
574        let dir = tempfile::tempdir().expect("tempdir");
575        let path = dir.path().join(LOCK_FILE);
576        fs::write(&path, b"").expect("write");
577        let mut perms = fs::metadata(&path).expect("metadata").permissions();
578        perms.set_mode(0o444);
579        fs::set_permissions(&path, perms).expect("chmod");
580        assert!(
581            BootstrapLock::acquire(&path).is_none(),
582            "an unopenable lock file must refuse, never claim the lock"
583        );
584    }
585
586    /// The property the staleness heuristic was reaching for, proved instead of
587    /// guessed: the kernel drops the lock when the holder dies, so a crashed run
588    /// never wedges the next one.
589    #[test]
590    fn a_lock_is_released_when_its_holder_is_killed() {
591        use std::io::BufRead;
592
593        let dir = tempfile::tempdir().expect("tempdir");
594        let path = dir.path().join(LOCK_FILE);
595        let mut child = std::process::Command::new(std::env::current_exe().expect("exe"))
596            .args([
597                "--exact",
598                "bootstrap::tests::lock_child_acquires_and_waits",
599                "--ignored",
600                "--nocapture",
601            ])
602            .env("PAPER_LOCK_CHILD", &path)
603            .stdout(std::process::Stdio::piped())
604            .stderr(std::process::Stdio::null())
605            .spawn()
606            .expect("spawn helper");
607
608        // libtest writes its own banner before the test's output, so read until
609        // the marker appears or the helper exits.
610        let mut collected = String::new();
611        let mut reader = std::io::BufReader::new(child.stdout.take().expect("stdout"));
612        let mut line = String::new();
613        loop {
614            line.clear();
615            let read = reader.read_line(&mut line).expect("read helper output");
616            if read == 0 {
617                break;
618            }
619            collected.push_str(&line);
620            if line.contains("acquired") {
621                break;
622            }
623        }
624        assert!(
625            collected.contains("acquired"),
626            "helper never acquired the lock: {collected:?}"
627        );
628        assert!(
629            BootstrapLock::acquire(&path).is_none(),
630            "a live holder must refuse a second acquirer"
631        );
632
633        child.kill().expect("kill helper");
634        let _ = child.wait();
635
636        // The close that releases the lock is asynchronous relative to `kill`,
637        // so poll briefly rather than asserting on a race.
638        let mut acquired = None;
639        for _ in 0..100 {
640            if let Some(lock) = BootstrapLock::acquire(&path) {
641                acquired = Some(lock);
642                break;
643            }
644            std::thread::sleep(Duration::from_millis(20));
645        }
646        assert!(
647            acquired.is_some(),
648            "the lock must be free once its holder is dead"
649        );
650    }
651
652    /// The editor-only install: `serve` never provisions, so it must at least say
653    /// that setup has not run — once, on stderr, without blocking the handshake.
654    #[test]
655    fn serve_says_when_setup_has_never_run() {
656        let pending = State {
657            service: ServiceState::Pending,
658            updated: 0,
659        };
660        let notice = pending_setup_notice("serve", &Switches::default(), &pending)
661            .expect("a pending setup must be announced to the editor-only install");
662        assert!(
663            notice.contains("paper index"),
664            "point at the command: {notice}"
665        );
666        assert!(
667            !notice.contains("bootstrap"),
668            "`paper bootstrap` is not a subcommand — never name it: {notice}"
669        );
670        assert!(
671            notice.contains("keyword-only"),
672            "say what search does in the meantime: {notice}"
673        );
674
675        // Silence once setup has run…
676        let installed = State {
677            service: ServiceState::Installed,
678            updated: 0,
679        };
680        assert!(pending_setup_notice("serve", &Switches::default(), &installed).is_none());
681        // …for every other skip-listed command…
682        assert!(pending_setup_notice("doctor", &Switches::default(), &pending).is_none());
683        // …and when onboarding was deliberately turned off.
684        let off = Switches {
685            no_autostart: true,
686            ..Switches::default()
687        };
688        assert!(pending_setup_notice("serve", &off, &pending).is_none());
689    }
690
691    #[test]
692    fn state_round_trips() {
693        let dir = tempfile::tempdir().expect("tempdir");
694        let path = dir.path().join(STATE_FILE);
695
696        let mut state = State::load(&path);
697        assert_eq!(state.service, ServiceState::Pending);
698        assert!(state.should_retry(0));
699
700        state.service = ServiceState::Installed;
701        state.updated = 42;
702        state.save(&path).expect("save");
703
704        let loaded = State::load(&path);
705        assert_eq!(loaded.service, ServiceState::Installed);
706        assert_eq!(loaded.updated, 42);
707        assert!(!loaded.should_retry(10_000));
708    }
709
710    #[test]
711    fn failed_installs_retry_after_the_backoff() {
712        let dir = tempfile::tempdir().expect("tempdir");
713        let path = dir.path().join(STATE_FILE);
714        let state = State {
715            service: ServiceState::Unavailable,
716            updated: 1_000,
717        };
718        state.save(&path).expect("save");
719        let loaded = State::load(&path);
720        assert!(!loaded.should_retry(1_000 + RETRY_AFTER.as_secs() - 1));
721        assert!(loaded.should_retry(1_000 + RETRY_AFTER.as_secs()));
722    }
723
724    #[test]
725    fn unknown_state_file_is_ignored() {
726        let dir = tempfile::tempdir().expect("tempdir");
727        let path = dir.path().join(STATE_FILE);
728        fs::write(&path, "version=0\nservice=installed\n").expect("write");
729        assert_eq!(State::load(&path).service, ServiceState::Pending);
730    }
731
732    #[test]
733    fn setup_status_round_trips_and_missing_is_none() {
734        let dir = tempfile::tempdir().expect("tempdir");
735        let paths = Paths::with_base(dir.path());
736        assert_eq!(setup_status(&paths), None);
737        set_setup_status(&paths, "indexing");
738        assert_eq!(setup_status(&paths).as_deref(), Some("indexing"));
739        clear_setup_status(&paths);
740        assert_eq!(setup_status(&paths), None);
741    }
742
743    #[test]
744    fn empty_index_is_reported_as_empty() {
745        let dir = tempfile::tempdir().expect("tempdir");
746        let paths = Paths::with_base(dir.path());
747        paths.ensure_dirs().expect("dirs");
748        assert!(index_is_empty(&paths));
749    }
750}