Skip to main content

paper/daemon/
mod.rs

1//! Daemon core: IPC server, scheduler, watcher, resource guard, and auto-discovery.
2
3pub mod auto_discover;
4pub mod ipc;
5pub mod resource_guard;
6pub mod scheduler;
7pub mod watcher;
8
9pub use ipc::DaemonHandler;
10
11use crate::cli::Workspace;
12use crate::core::index::{init_db, Connection, Indexer};
13use crate::core::search::SharedEmbedder;
14use crate::daemon::auto_discover::discover_default_roots;
15use crate::daemon::ipc::{run_ipc_server, DaemonRequest, DaemonResponse};
16use crate::daemon::resource_guard::{PauseReason, ResourceGuard, ResourceGuardConfig};
17use crate::daemon::scheduler::RootAwareScheduler;
18use crate::daemon::watcher::Watcher;
19use anyhow::Result;
20use clap::Args;
21use std::path::PathBuf;
22use std::sync::Arc;
23use tokio::signal;
24use tokio::sync::{mpsc, Mutex, Notify, RwLock};
25
26/// Arguments for the daemon subcommand.
27#[derive(Args, Debug, Clone)]
28pub struct DaemonArgs {
29    /// Run in foreground (don't daemonize)
30    #[arg(long)]
31    pub foreground: bool,
32
33    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock)
34    #[arg(long)]
35    pub socket: Option<PathBuf>,
36
37    /// Roots to index (default: auto-discover Documents, Downloads, Desktop)
38    #[arg(long, short)]
39    pub root: Vec<PathBuf>,
40
41    /// Disable file system watcher
42    #[arg(long)]
43    pub no_watch: bool,
44
45    /// Disable scheduler
46    #[arg(long)]
47    pub no_schedule: bool,
48
49    /// Disable resource guard (battery/CPU monitoring)
50    #[arg(long)]
51    pub no_resource_guard: bool,
52
53    /// Full reindex cron expression (default: "0 0 3 * * *" = daily 3 AM)
54    #[arg(long)]
55    pub full_cron: Option<String>,
56
57    /// Incremental index interval in seconds (default: 300 = 5 min)
58    #[arg(long)]
59    pub incremental_interval: Option<u64>,
60
61    /// Debounce time for file watcher in milliseconds (default: 250)
62    #[arg(long)]
63    pub debounce_ms: Option<u64>,
64
65    /// Battery threshold percentage (default: 20)
66    #[arg(long)]
67    pub battery_threshold: Option<u8>,
68
69    /// CPU threshold percentage (default: 80)
70    #[arg(long)]
71    pub cpu_threshold: Option<u8>,
72}
73
74/// Shared daemon state.
75///
76/// Deliberately does NOT hold an `Indexer` or `Connection`: rusqlite
77/// connections are not `Sync`, so each indexing request opens a fresh
78/// connection inside `spawn_blocking` (the same pattern the CLI uses).
79struct DaemonState {
80    roots: RwLock<Vec<PathBuf>>,
81    paused: RwLock<bool>,
82    shutdown: RwLock<bool>,
83    shutdown_notify: Arc<Notify>,
84    db_path: PathBuf,
85    embedder: Option<SharedEmbedder>,
86    /// Held for a whole `IndexRoots` job so scheduler, watcher and IPC runs
87    /// queue instead of overlapping and hitting SQLITE_BUSY.
88    index_lock: Mutex<()>,
89    /// Where the setup-status line lives; cleared when an index pass ends.
90    #[cfg(feature = "daemon")]
91    paths: crate::core::paths::Paths,
92}
93
94/// Clears the setup-status line on every exit path of an index request.
95#[cfg(feature = "daemon")]
96struct ClearSetupStatus<'a>(&'a crate::core::paths::Paths);
97
98#[cfg(feature = "daemon")]
99impl Drop for ClearSetupStatus<'_> {
100    fn drop(&mut self) {
101        crate::bootstrap::clear_setup_status(self.0);
102    }
103}
104
105/// One indexing pass. When it covers exactly the configured roots (the
106/// scheduled passes) it also prunes files deleted since the last pass.
107fn run_index_job(
108    db_path: &std::path::Path,
109    embedder: Option<SharedEmbedder>,
110    roots: &[PathBuf],
111    configured: &[PathBuf],
112) -> Result<crate::core::index::IndexStats> {
113    let conn = Connection::open(db_path)?;
114    init_db(&conn)?;
115    let indexer = Indexer::new(conn, embedder)?;
116    let stats = indexer.index_roots_within(roots, configured)?;
117    let sorted = |v: &[PathBuf]| {
118        let mut v = v.to_vec();
119        v.sort();
120        v
121    };
122    if sorted(roots) == sorted(configured) {
123        indexer.prune_missing()?;
124    }
125    Ok(stats)
126}
127
128/// Daemon request handler.
129struct DaemonHandlerImpl {
130    state: Arc<DaemonState>,
131    scheduler: Arc<RootAwareScheduler>,
132    watcher: Arc<RwLock<Option<Watcher>>>,
133}
134
135#[async_trait::async_trait]
136impl DaemonHandler for DaemonHandlerImpl {
137    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
138        match request {
139            DaemonRequest::IndexRoots { roots } => {
140                #[cfg(feature = "daemon")]
141                let _clear_status = ClearSetupStatus(&self.state.paths);
142                let roots_to_index = if roots.is_empty() {
143                    self.state.roots.read().await.clone()
144                } else {
145                    roots
146                };
147
148                if roots_to_index.is_empty() {
149                    return DaemonResponse::Error {
150                        msg: "No roots configured for indexing".to_string(),
151                    };
152                }
153
154                if *self.state.paused.read().await {
155                    return DaemonResponse::Error {
156                        msg: "Indexing paused by resource guard".to_string(),
157                    };
158                }
159
160                let db_path = self.state.db_path.clone();
161                let embedder = self.state.embedder.clone();
162                // A file named directly (the watcher sends changed files) is
163                // checked against the configured root it lives under.
164                let configured = self.state.roots.read().await.clone();
165
166                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
167                // create it inside the blocking task and run it there.
168                let _running = self.state.index_lock.lock().await;
169                match tokio::task::spawn_blocking(move || {
170                    run_index_job(&db_path, embedder, &roots_to_index, &configured)
171                })
172                .await
173                {
174                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
175                    Ok(Err(e)) => DaemonResponse::Error {
176                        msg: format!("Indexing failed: {e:#}"),
177                    },
178                    Err(e) => DaemonResponse::Error {
179                        msg: format!("Indexing task failed: {e:#}"),
180                    },
181                }
182            }
183            DaemonRequest::AddRoot { path } => {
184                if !path.exists() {
185                    return DaemonResponse::Error {
186                        msg: format!("Path does not exist: {}", path.display()),
187                    };
188                }
189
190                let mut roots = self.state.roots.write().await;
191                if !roots.contains(&path) {
192                    roots.push(path.clone());
193                    drop(roots);
194
195                    if let Some(watcher) = self.watcher.write().await.as_mut() {
196                        let _ = watcher.add_root(path.clone()).await;
197                    }
198                    self.scheduler.add_root(path).await;
199                }
200                DaemonResponse::Ok
201            }
202            DaemonRequest::RemoveRoot { path } => {
203                self.state.roots.write().await.retain(|r| r != &path);
204
205                if let Some(watcher) = self.watcher.write().await.as_mut() {
206                    let _ = watcher.remove_root(&path).await;
207                }
208                self.scheduler.remove_root(&path).await;
209                DaemonResponse::Ok
210            }
211            DaemonRequest::GetStatus => {
212                let paused = *self.state.paused.read().await;
213                // Open one connection and reuse it for both status queries
214                // instead of opening two separate connections (M15).
215                let (indexed_files, model) = match Connection::open(&self.state.db_path) {
216                    Ok(conn) => (
217                        Self::count_indexed_files(&conn),
218                        Self::stored_embedding_model(&conn),
219                    ),
220                    Err(_) => (0, None),
221                };
222
223                DaemonResponse::Status {
224                    indexed_files,
225                    queued: 0,
226                    paused,
227                    model,
228                }
229            }
230            DaemonRequest::Pause => {
231                *self.state.paused.write().await = true;
232                DaemonResponse::Ok
233            }
234            DaemonRequest::Resume => {
235                *self.state.paused.write().await = false;
236                DaemonResponse::Ok
237            }
238            DaemonRequest::Shutdown => {
239                // Signal shutdown via a flag and wake the dispatch loop; do not
240                // re-enqueue Shutdown on the same channel (IK).
241                *self.state.shutdown.write().await = true;
242                self.state.shutdown_notify.notify_waiters();
243                DaemonResponse::Ok
244            }
245        }
246    }
247}
248
249impl DaemonHandlerImpl {
250    fn count_indexed_files(conn: &Connection) -> usize {
251        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
252            .unwrap_or(0) as usize
253    }
254
255    fn stored_embedding_model(conn: &Connection) -> Option<String> {
256        conn.stored_embedding_model().ok().flatten()
257    }
258}
259
260/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
261pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
262    let workspace = Workspace::new();
263
264    // Determine socket path
265    let socket_path = args
266        .socket
267        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
268
269    // Ensure parent directory exists
270    if let Some(parent) = socket_path.parent() {
271        crate::core::paths::create_private_dir(parent)?;
272    }
273
274    // Determine roots to index. Explicit `--root` wins; otherwise the
275    // auto-discovered user directories are combined with any roots persisted in
276    // the config (by `daemon-control add-root` or the MCP add_index_root tool),
277    // so a root added once survives a reboot.
278    let roots = if args.root.is_empty() {
279        let mut roots = discover_default_roots();
280        for root in &workspace.config.roots {
281            if !roots.contains(root) {
282                roots.push(root.clone());
283            }
284        }
285        roots
286    } else {
287        args.root.clone()
288    };
289
290    if roots.is_empty() {
291        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
292    } else {
293        tracing::info!("Daemon will index: {:?}", roots);
294    }
295
296    // Download the default embedding model if this is a fresh install. Doing it
297    // here (rather than in the installer) covers every install channel, and
298    // doing it before the embedder is loaded means the first index pass already
299    // gets vectors instead of needing a reindex later.
300    #[cfg(feature = "daemon")]
301    crate::bootstrap::ensure_models(&workspace).await;
302
303    // The reranker is ~1.1 GB and only search uses it: fetch it without
304    // delaying the first index pass.
305    #[cfg(feature = "daemon")]
306    tokio::spawn(async {
307        crate::bootstrap::ensure_reranker(&crate::core::models::ModelManager::new()).await;
308    });
309
310    // The first pass (queued below) clears this line when it ends; with no
311    // first pass to wait for, the download step was the last background work.
312    #[cfg(feature = "daemon")]
313    let first_pass = !args.no_schedule && crate::bootstrap::index_is_empty(&workspace.paths);
314    #[cfg(feature = "daemon")]
315    if first_pass {
316        crate::bootstrap::set_setup_status(
317            &workspace.paths,
318            "indexing your documents for the first time",
319        );
320    } else {
321        crate::bootstrap::clear_setup_status(&workspace.paths);
322    }
323
324    // Load the embedder once, after the download step above.
325    let embedder = workspace.embedder();
326    let db_path = workspace.paths.db_path();
327
328    // Create channels
329    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
330
331    // Create shared state
332    let state = Arc::new(DaemonState {
333        roots: RwLock::new(roots.clone()),
334        paused: RwLock::new(false),
335        shutdown: RwLock::new(false),
336        shutdown_notify: Arc::new(Notify::new()),
337        db_path,
338        embedder,
339        index_lock: Mutex::new(()),
340        #[cfg(feature = "daemon")]
341        paths: crate::core::paths::Paths::new(),
342    });
343
344    // Create scheduler
345    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
346    let incremental_interval = args
347        .incremental_interval
348        .map(std::time::Duration::from_secs)
349        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
350    let scheduler = Arc::new(RootAwareScheduler::new(
351        &full_cron,
352        incremental_interval,
353        request_tx.clone(),
354    )?);
355    scheduler.set_roots(roots.clone()).await;
356
357    // Create watcher
358    let debounce_ms = args.debounce_ms.unwrap_or(250);
359    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
360    for root in &roots {
361        watcher.add_root(root.clone()).await?;
362    }
363    let watcher = Arc::new(RwLock::new(Some(watcher)));
364
365    // Create resource guard
366    let mut resource_config = ResourceGuardConfig::default();
367    if let Some(b) = args.battery_threshold {
368        resource_config.battery_threshold = b;
369    }
370    if let Some(c) = args.cpu_threshold {
371        resource_config.cpu_threshold = c;
372    }
373    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));
374
375    // Create handler
376    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
377        state: state.clone(),
378        scheduler: scheduler.clone(),
379        watcher: watcher.clone(),
380    });
381
382    // Start components
383    if !args.no_schedule {
384        scheduler.start().await;
385
386        // First install: index now rather than waiting for the first
387        // incremental tick (the scheduler skips its immediate tick on start).
388        #[cfg(feature = "daemon")]
389        if first_pass {
390            tracing::info!("empty index — starting the first indexing pass");
391            scheduler.trigger_incremental().await;
392        }
393    }
394
395    if !args.no_watch {
396        if let Some(w) = watcher.write().await.as_mut() {
397            w.start().await?;
398        }
399    }
400
401    if !args.no_resource_guard {
402        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
403        resource_guard.start_monitoring(pause_tx);
404        let state = state.clone();
405        tokio::spawn(async move {
406            while let Some(reason) = pause_rx.recv().await {
407                match reason {
408                    PauseReason::Resumed => {
409                        *state.paused.write().await = false;
410                        tracing::info!("Resource guard: resuming indexing");
411                    }
412                    other => {
413                        *state.paused.write().await = true;
414                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
415                    }
416                }
417            }
418        });
419    }
420
421    // Start IPC server task
422    let socket_path_clone = socket_path.clone();
423    let handler_clone = handler.clone();
424    let ipc_handle = tokio::spawn(async move {
425        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
426            tracing::error!("IPC server error: {e:#}");
427        }
428    });
429
430    // Handle shutdown signals
431    let shutdown = async {
432        #[cfg(unix)]
433        {
434            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
435            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
436            tokio::select! {
437                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
438                _ = sigint.recv() => tracing::info!("Received SIGINT"),
439            }
440        }
441        #[cfg(windows)]
442        {
443            signal::ctrl_c().await?;
444            tracing::info!("Received Ctrl+C");
445        }
446        Ok::<(), anyhow::Error>(())
447    };
448
449    // Dispatch loop: requests from the scheduler and watcher are handled here;
450    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
451    let dispatch = async {
452        let state = state.clone();
453        loop {
454            tokio::select! {
455                // A request from the scheduler, watcher, or a directly-enqueued
456                // Shutdown.
457                request = request_rx.recv() => {
458                    match request {
459                        Some(request) => {
460                            if *state.shutdown.read().await || matches!(request, DaemonRequest::Shutdown) {
461                                break;
462                            }
463                            let handler = handler.clone();
464                            tokio::spawn(async move {
465                                let _ = handler.handle(request).await;
466                            });
467                        }
468                        None => break, // channel closed
469                    }
470                }
471                // Woken by the Shutdown handler (IK) so we can check the flag.
472                _ = state.shutdown_notify.notified() => {
473                    if *state.shutdown.read().await {
474                        break;
475                    }
476                }
477            }
478        }
479    };
480
481    // Run until shutdown signal or shutdown request
482    tokio::select! {
483        _ = shutdown => {
484            tracing::info!("Shutting down daemon...");
485        }
486        _ = dispatch => {
487            tracing::info!("Shutdown requested via IPC...");
488        }
489    }
490
491    // Graceful shutdown
492    scheduler.stop().await;
493
494    if let Some(w) = watcher.write().await.as_mut() {
495        w.stop().await;
496    }
497
498    ipc_handle.abort();
499    let _ = ipc_handle.await;
500
501    // Clean up socket file
502    let _ = tokio::fs::remove_file(&socket_path).await;
503
504    tracing::info!("Daemon stopped");
505    Ok(0)
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511
512    #[test]
513    fn the_configured_pass_prunes_deleted_files_but_a_partial_one_does_not() {
514        let dir = tempfile::tempdir().unwrap();
515        let root = dir.path().join("docs");
516        std::fs::create_dir(&root).unwrap();
517        let (a, b) = (root.join("a.txt"), root.join("b.txt"));
518        std::fs::write(&a, "alpha zebra").unwrap();
519        std::fs::write(&b, "beta giraffe").unwrap();
520        let db = dir.path().join("chunks.db");
521        let configured = vec![root.clone()];
522        run_index_job(&db, None, &configured, &configured).unwrap();
523        std::fs::remove_file(&a).unwrap();
524        // A watcher-style pass over one other path must not prune.
525        run_index_job(&db, None, std::slice::from_ref(&b), &configured).unwrap();
526        let count = |p: &str| -> i64 {
527            Connection::open(&db)
528                .unwrap()
529                .inner()
530                .query_row(
531                    "SELECT COUNT(*) FROM chunks WHERE source_path = ?",
532                    [p],
533                    |r| r.get(0),
534                )
535                .unwrap()
536        };
537        let a = a.to_string_lossy().to_string();
538        assert_eq!(count(&a), 1);
539        run_index_job(&db, None, &configured, &configured).unwrap();
540        assert_eq!(count(&a), 0);
541    }
542}