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 optional reranker (~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) {
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()
400        && !manager.is_installed(crate::core::models::OPTIONAL_RERANKER)
401    {
402        tracing::info!("downloading the optional reranker in the background");
403        if let Err(error) = manager.ensure(crate::core::models::OPTIONAL_RERANKER).await {
404            tracing::warn!("reranker download failed ({error:#}); results stay dense+keyword");
405        }
406    }
407    #[cfg(not(feature = "embeddings"))]
408    let _ = manager;
409}
410
411const SETUP_STATUS_FILE: &str = "setup-status";
412
413// shortcut: a daemon that dies mid-setup leaves a stale line until the service
414// restarts and rewrites it; upgrade to a pid/heartbeat check if that bites.
415/// Record what the daemon is doing in the background so searches can say so.
416/// Best effort: a failed write only loses the hint.
417pub fn set_setup_status(paths: &Paths, phase: &str) {
418    let _ = std::fs::write(paths.base_dir().join(SETUP_STATUS_FILE), phase);
419}
420
421pub fn clear_setup_status(paths: &Paths) {
422    let _ = std::fs::remove_file(paths.base_dir().join(SETUP_STATUS_FILE));
423}
424
425/// The current background phase, if setup is in progress.
426pub fn setup_status(paths: &Paths) -> Option<String> {
427    let text = std::fs::read_to_string(paths.base_dir().join(SETUP_STATUS_FILE)).ok()?;
428    let text = text.trim();
429    (!text.is_empty()).then(|| text.to_string())
430}
431
432/// True when the index holds no chunks yet, which is the moment to index
433/// immediately rather than wait for the five-minute incremental tick.
434pub fn index_is_empty(paths: &Paths) -> bool {
435    let Ok(connection) = crate::core::index::Connection::open(&paths.db_path()) else {
436        return true;
437    };
438    if crate::core::index::init_db(&connection).is_err() {
439        return true;
440    }
441    connection
442        .query_i64("SELECT COUNT(*) FROM chunks")
443        .map(|count| count == 0)
444        .unwrap_or(true)
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450
451    #[test]
452    fn skips_when_disabled() {
453        let enabled = Switches::default();
454        assert!(should_run("search", &enabled));
455
456        for switches in [
457            Switches {
458                offline: true,
459                ..enabled
460            },
461            Switches {
462                no_autostart: true,
463                ..enabled
464            },
465            Switches {
466                ci: true,
467                ..enabled
468            },
469        ] {
470            assert!(!should_run("search", &switches));
471        }
472    }
473
474    #[test]
475    fn skips_portable_installs_unless_forced() {
476        let portable = Switches {
477            portable: true,
478            ..Switches::default()
479        };
480        assert!(!should_run("search", &portable));
481        assert!(should_run(
482            "search",
483            &Switches {
484                force: true,
485                ..portable
486            }
487        ));
488    }
489
490    #[test]
491    fn skips_commands_that_manage_the_daemon() {
492        for command in SKIP_COMMANDS {
493            assert!(!should_run(command, &Switches::default()), "{command}");
494        }
495        for command in ["search", "answer", "aggregate"] {
496            assert!(should_run(command, &Switches::default()), "{command}");
497        }
498    }
499
500    /// `serve` is what an editor starts — often five sessions at once — so it is
501    /// the one command that must never be the thing that installs a service.
502    #[test]
503    fn serve_never_bootstraps() {
504        assert!(!should_run("serve", &Switches::default()));
505        // Not even the portable force switch, which exists for installs that
506        // want onboarding: a server session is never the right place for it.
507        let forced_portable = Switches {
508            portable: true,
509            force: true,
510            ..Switches::default()
511        };
512        assert!(!should_run("serve", &forced_portable));
513    }
514
515    /// A lock file with nobody holding it is what a killed run leaves behind.
516    /// The old `create_new` test read that state as "someone is setting up".
517    #[test]
518    fn a_lock_file_left_by_a_dead_run_does_not_block_setup() {
519        let dir = tempfile::tempdir().expect("tempdir");
520        let path = dir.path().join(LOCK_FILE);
521        fs::write(&path, b"").expect("write");
522        assert!(
523            BootstrapLock::acquire(&path).is_some(),
524            "an unheld lock file must be acquirable"
525        );
526    }
527
528    /// The basic contract: exclusive while held, released on drop. On its own
529    /// this would also pass against the old `create_new` file lock — the test
530    /// that actually distinguishes the kernel lock is
531    /// [`a_lock_is_released_when_its_holder_is_killed`], which no file-existence
532    /// scheme can pass.
533    #[test]
534    fn a_held_lock_is_exclusive_and_released_on_drop() {
535        let dir = tempfile::tempdir().expect("tempdir");
536        let path = dir.path().join(LOCK_FILE);
537        let first = BootstrapLock::acquire(&path).expect("first acquisition");
538        assert!(
539            BootstrapLock::acquire(&path).is_none(),
540            "a second holder must be refused while the first lives"
541        );
542        drop(first);
543        assert!(
544            BootstrapLock::acquire(&path).is_some(),
545            "dropping the guard must release the lock"
546        );
547    }
548
549    /// Child half of [`a_lock_is_released_when_its_holder_is_killed`]: acquire,
550    /// say so on stdout, then wait to be killed. Ignored by default; the parent
551    /// runs it by exact name in a separate process.
552    #[test]
553    #[ignore = "child process helper for a_lock_is_released_when_its_holder_is_killed"]
554    fn lock_child_acquires_and_waits() {
555        let Ok(path) = std::env::var("PAPER_LOCK_CHILD") else {
556            return;
557        };
558        let lock = BootstrapLock::acquire(Path::new(&path)).expect("child acquires");
559        println!("acquired");
560        std::thread::sleep(Duration::from_secs(60));
561        drop(lock);
562    }
563
564    /// A lock file that cannot even be opened (a read-only mount, a backup
565    /// restored under another owner) must never be mistaken for a held lock.
566    #[cfg(unix)]
567    #[test]
568    fn a_lock_file_that_cannot_be_opened_is_refused_not_assumed_held() {
569        use std::os::unix::fs::PermissionsExt;
570
571        let dir = tempfile::tempdir().expect("tempdir");
572        let path = dir.path().join(LOCK_FILE);
573        fs::write(&path, b"").expect("write");
574        let mut perms = fs::metadata(&path).expect("metadata").permissions();
575        perms.set_mode(0o444);
576        fs::set_permissions(&path, perms).expect("chmod");
577        assert!(
578            BootstrapLock::acquire(&path).is_none(),
579            "an unopenable lock file must refuse, never claim the lock"
580        );
581    }
582
583    /// The property the staleness heuristic was reaching for, proved instead of
584    /// guessed: the kernel drops the lock when the holder dies, so a crashed run
585    /// never wedges the next one.
586    #[test]
587    fn a_lock_is_released_when_its_holder_is_killed() {
588        use std::io::BufRead;
589
590        let dir = tempfile::tempdir().expect("tempdir");
591        let path = dir.path().join(LOCK_FILE);
592        let mut child = std::process::Command::new(std::env::current_exe().expect("exe"))
593            .args([
594                "--exact",
595                "bootstrap::tests::lock_child_acquires_and_waits",
596                "--ignored",
597                "--nocapture",
598            ])
599            .env("PAPER_LOCK_CHILD", &path)
600            .stdout(std::process::Stdio::piped())
601            .stderr(std::process::Stdio::null())
602            .spawn()
603            .expect("spawn helper");
604
605        // libtest writes its own banner before the test's output, so read until
606        // the marker appears or the helper exits.
607        let mut collected = String::new();
608        let mut reader = std::io::BufReader::new(child.stdout.take().expect("stdout"));
609        let mut line = String::new();
610        loop {
611            line.clear();
612            let read = reader.read_line(&mut line).expect("read helper output");
613            if read == 0 {
614                break;
615            }
616            collected.push_str(&line);
617            if line.contains("acquired") {
618                break;
619            }
620        }
621        assert!(
622            collected.contains("acquired"),
623            "helper never acquired the lock: {collected:?}"
624        );
625        assert!(
626            BootstrapLock::acquire(&path).is_none(),
627            "a live holder must refuse a second acquirer"
628        );
629
630        child.kill().expect("kill helper");
631        let _ = child.wait();
632
633        // The close that releases the lock is asynchronous relative to `kill`,
634        // so poll briefly rather than asserting on a race.
635        let mut acquired = None;
636        for _ in 0..100 {
637            if let Some(lock) = BootstrapLock::acquire(&path) {
638                acquired = Some(lock);
639                break;
640            }
641            std::thread::sleep(Duration::from_millis(20));
642        }
643        assert!(
644            acquired.is_some(),
645            "the lock must be free once its holder is dead"
646        );
647    }
648
649    /// The editor-only install: `serve` never provisions, so it must at least say
650    /// that setup has not run — once, on stderr, without blocking the handshake.
651    #[test]
652    fn serve_says_when_setup_has_never_run() {
653        let pending = State {
654            service: ServiceState::Pending,
655            updated: 0,
656        };
657        let notice = pending_setup_notice("serve", &Switches::default(), &pending)
658            .expect("a pending setup must be announced to the editor-only install");
659        assert!(
660            notice.contains("paper index"),
661            "point at the command: {notice}"
662        );
663        assert!(
664            !notice.contains("bootstrap"),
665            "`paper bootstrap` is not a subcommand — never name it: {notice}"
666        );
667        assert!(
668            notice.contains("keyword-only"),
669            "say what search does in the meantime: {notice}"
670        );
671
672        // Silence once setup has run…
673        let installed = State {
674            service: ServiceState::Installed,
675            updated: 0,
676        };
677        assert!(pending_setup_notice("serve", &Switches::default(), &installed).is_none());
678        // …for every other skip-listed command…
679        assert!(pending_setup_notice("doctor", &Switches::default(), &pending).is_none());
680        // …and when onboarding was deliberately turned off.
681        let off = Switches {
682            no_autostart: true,
683            ..Switches::default()
684        };
685        assert!(pending_setup_notice("serve", &off, &pending).is_none());
686    }
687
688    #[test]
689    fn state_round_trips() {
690        let dir = tempfile::tempdir().expect("tempdir");
691        let path = dir.path().join(STATE_FILE);
692
693        let mut state = State::load(&path);
694        assert_eq!(state.service, ServiceState::Pending);
695        assert!(state.should_retry(0));
696
697        state.service = ServiceState::Installed;
698        state.updated = 42;
699        state.save(&path).expect("save");
700
701        let loaded = State::load(&path);
702        assert_eq!(loaded.service, ServiceState::Installed);
703        assert_eq!(loaded.updated, 42);
704        assert!(!loaded.should_retry(10_000));
705    }
706
707    #[test]
708    fn failed_installs_retry_after_the_backoff() {
709        let dir = tempfile::tempdir().expect("tempdir");
710        let path = dir.path().join(STATE_FILE);
711        let state = State {
712            service: ServiceState::Unavailable,
713            updated: 1_000,
714        };
715        state.save(&path).expect("save");
716        let loaded = State::load(&path);
717        assert!(!loaded.should_retry(1_000 + RETRY_AFTER.as_secs() - 1));
718        assert!(loaded.should_retry(1_000 + RETRY_AFTER.as_secs()));
719    }
720
721    #[test]
722    fn unknown_state_file_is_ignored() {
723        let dir = tempfile::tempdir().expect("tempdir");
724        let path = dir.path().join(STATE_FILE);
725        fs::write(&path, "version=0\nservice=installed\n").expect("write");
726        assert_eq!(State::load(&path).service, ServiceState::Pending);
727    }
728
729    #[test]
730    fn setup_status_round_trips_and_missing_is_none() {
731        let dir = tempfile::tempdir().expect("tempdir");
732        let paths = Paths::with_base(dir.path());
733        assert_eq!(setup_status(&paths), None);
734        set_setup_status(&paths, "indexing");
735        assert_eq!(setup_status(&paths).as_deref(), Some("indexing"));
736        clear_setup_status(&paths);
737        assert_eq!(setup_status(&paths), None);
738    }
739
740    #[test]
741    fn empty_index_is_reported_as_empty() {
742        let dir = tempfile::tempdir().expect("tempdir");
743        let paths = Paths::with_base(dir.path());
744        paths.ensure_dirs().expect("dirs");
745        assert!(index_is_empty(&paths));
746    }
747}