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}
90
91/// One indexing pass. When it covers exactly the configured roots (the
92/// scheduled passes) it also prunes files deleted since the last pass.
93fn run_index_job(
94    db_path: &std::path::Path,
95    embedder: Option<SharedEmbedder>,
96    roots: &[PathBuf],
97    configured: &[PathBuf],
98) -> Result<crate::core::index::IndexStats> {
99    let conn = Connection::open(db_path)?;
100    init_db(&conn)?;
101    let indexer = Indexer::new(conn, embedder)?;
102    let stats = indexer.index_roots_within(roots, configured)?;
103    let sorted = |v: &[PathBuf]| {
104        let mut v = v.to_vec();
105        v.sort();
106        v
107    };
108    if sorted(roots) == sorted(configured) {
109        indexer.prune_missing()?;
110    }
111    Ok(stats)
112}
113
114/// Daemon request handler.
115struct DaemonHandlerImpl {
116    state: Arc<DaemonState>,
117    scheduler: Arc<RootAwareScheduler>,
118    watcher: Arc<RwLock<Option<Watcher>>>,
119}
120
121#[async_trait::async_trait]
122impl DaemonHandler for DaemonHandlerImpl {
123    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
124        match request {
125            DaemonRequest::IndexRoots { roots } => {
126                let roots_to_index = if roots.is_empty() {
127                    self.state.roots.read().await.clone()
128                } else {
129                    roots
130                };
131
132                if roots_to_index.is_empty() {
133                    return DaemonResponse::Error {
134                        msg: "No roots configured for indexing".to_string(),
135                    };
136                }
137
138                if *self.state.paused.read().await {
139                    return DaemonResponse::Error {
140                        msg: "Indexing paused by resource guard".to_string(),
141                    };
142                }
143
144                let db_path = self.state.db_path.clone();
145                let embedder = self.state.embedder.clone();
146                // A file named directly (the watcher sends changed files) is
147                // checked against the configured root it lives under.
148                let configured = self.state.roots.read().await.clone();
149
150                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
151                // create it inside the blocking task and run it there.
152                let _running = self.state.index_lock.lock().await;
153                match tokio::task::spawn_blocking(move || {
154                    run_index_job(&db_path, embedder, &roots_to_index, &configured)
155                })
156                .await
157                {
158                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
159                    Ok(Err(e)) => DaemonResponse::Error {
160                        msg: format!("Indexing failed: {e:#}"),
161                    },
162                    Err(e) => DaemonResponse::Error {
163                        msg: format!("Indexing task failed: {e:#}"),
164                    },
165                }
166            }
167            DaemonRequest::AddRoot { path } => {
168                if !path.exists() {
169                    return DaemonResponse::Error {
170                        msg: format!("Path does not exist: {}", path.display()),
171                    };
172                }
173
174                let mut roots = self.state.roots.write().await;
175                if !roots.contains(&path) {
176                    roots.push(path.clone());
177                    drop(roots);
178
179                    if let Some(watcher) = self.watcher.write().await.as_mut() {
180                        let _ = watcher.add_root(path.clone()).await;
181                    }
182                    self.scheduler.add_root(path).await;
183                }
184                DaemonResponse::Ok
185            }
186            DaemonRequest::RemoveRoot { path } => {
187                self.state.roots.write().await.retain(|r| r != &path);
188
189                if let Some(watcher) = self.watcher.write().await.as_mut() {
190                    let _ = watcher.remove_root(&path).await;
191                }
192                self.scheduler.remove_root(&path).await;
193                DaemonResponse::Ok
194            }
195            DaemonRequest::GetStatus => {
196                let paused = *self.state.paused.read().await;
197                // Open one connection and reuse it for both status queries
198                // instead of opening two separate connections (M15).
199                let (indexed_files, model) = match Connection::open(&self.state.db_path) {
200                    Ok(conn) => (
201                        Self::count_indexed_files(&conn),
202                        Self::stored_embedding_model(&conn),
203                    ),
204                    Err(_) => (0, None),
205                };
206
207                DaemonResponse::Status {
208                    indexed_files,
209                    queued: 0,
210                    paused,
211                    model,
212                }
213            }
214            DaemonRequest::Pause => {
215                *self.state.paused.write().await = true;
216                DaemonResponse::Ok
217            }
218            DaemonRequest::Resume => {
219                *self.state.paused.write().await = false;
220                DaemonResponse::Ok
221            }
222            DaemonRequest::Shutdown => {
223                // Signal shutdown via a flag and wake the dispatch loop; do not
224                // re-enqueue Shutdown on the same channel (IK).
225                *self.state.shutdown.write().await = true;
226                self.state.shutdown_notify.notify_waiters();
227                DaemonResponse::Ok
228            }
229        }
230    }
231}
232
233impl DaemonHandlerImpl {
234    fn count_indexed_files(conn: &Connection) -> usize {
235        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
236            .unwrap_or(0) as usize
237    }
238
239    fn stored_embedding_model(conn: &Connection) -> Option<String> {
240        conn.stored_embedding_model().ok().flatten()
241    }
242}
243
244/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
245pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
246    let workspace = Workspace::new();
247
248    // Determine socket path
249    let socket_path = args
250        .socket
251        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
252
253    // Ensure parent directory exists
254    if let Some(parent) = socket_path.parent() {
255        crate::core::paths::create_private_dir(parent)?;
256    }
257
258    // Determine roots to index. Explicit `--root` wins; otherwise the
259    // auto-discovered user directories are combined with any roots persisted in
260    // the config (by `daemon-control add-root` or the MCP add_index_root tool),
261    // so a root added once survives a reboot.
262    let roots = if args.root.is_empty() {
263        let mut roots = discover_default_roots();
264        for root in &workspace.config.roots {
265            if !roots.contains(root) {
266                roots.push(root.clone());
267            }
268        }
269        roots
270    } else {
271        args.root.clone()
272    };
273
274    if roots.is_empty() {
275        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
276    } else {
277        tracing::info!("Daemon will index: {:?}", roots);
278    }
279
280    // Download the default embedding model if this is a fresh install. Doing it
281    // here (rather than in the installer) covers every install channel, and
282    // doing it before the embedder is loaded means the first index pass already
283    // gets vectors instead of needing a reindex later.
284    #[cfg(feature = "daemon")]
285    crate::bootstrap::ensure_models(&workspace).await;
286
287    // Load the embedder once, after the download step above.
288    let embedder = workspace.embedder();
289    let db_path = workspace.paths.db_path();
290
291    // Create channels
292    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
293
294    // Create shared state
295    let state = Arc::new(DaemonState {
296        roots: RwLock::new(roots.clone()),
297        paused: RwLock::new(false),
298        shutdown: RwLock::new(false),
299        shutdown_notify: Arc::new(Notify::new()),
300        db_path,
301        embedder,
302        index_lock: Mutex::new(()),
303    });
304
305    // Create scheduler
306    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
307    let incremental_interval = args
308        .incremental_interval
309        .map(std::time::Duration::from_secs)
310        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
311    let scheduler = Arc::new(RootAwareScheduler::new(
312        &full_cron,
313        incremental_interval,
314        request_tx.clone(),
315    )?);
316    scheduler.set_roots(roots.clone()).await;
317
318    // Create watcher
319    let debounce_ms = args.debounce_ms.unwrap_or(250);
320    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
321    for root in &roots {
322        watcher.add_root(root.clone()).await?;
323    }
324    let watcher = Arc::new(RwLock::new(Some(watcher)));
325
326    // Create resource guard
327    let mut resource_config = ResourceGuardConfig::default();
328    if let Some(b) = args.battery_threshold {
329        resource_config.battery_threshold = b;
330    }
331    if let Some(c) = args.cpu_threshold {
332        resource_config.cpu_threshold = c;
333    }
334    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));
335
336    // Create handler
337    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
338        state: state.clone(),
339        scheduler: scheduler.clone(),
340        watcher: watcher.clone(),
341    });
342
343    // Start components
344    if !args.no_schedule {
345        scheduler.start().await;
346
347        // First install: index now rather than waiting for the first
348        // incremental tick (the scheduler skips its immediate tick on start).
349        #[cfg(feature = "daemon")]
350        if crate::bootstrap::index_is_empty(&workspace.paths) {
351            tracing::info!("empty index — starting the first indexing pass");
352            scheduler.trigger_incremental().await;
353        }
354    }
355
356    if !args.no_watch {
357        if let Some(w) = watcher.write().await.as_mut() {
358            w.start().await?;
359        }
360    }
361
362    if !args.no_resource_guard {
363        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
364        resource_guard.start_monitoring(pause_tx);
365        let state = state.clone();
366        tokio::spawn(async move {
367            while let Some(reason) = pause_rx.recv().await {
368                match reason {
369                    PauseReason::Resumed => {
370                        *state.paused.write().await = false;
371                        tracing::info!("Resource guard: resuming indexing");
372                    }
373                    other => {
374                        *state.paused.write().await = true;
375                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
376                    }
377                }
378            }
379        });
380    }
381
382    // Start IPC server task
383    let socket_path_clone = socket_path.clone();
384    let handler_clone = handler.clone();
385    let ipc_handle = tokio::spawn(async move {
386        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
387            tracing::error!("IPC server error: {e:#}");
388        }
389    });
390
391    // Handle shutdown signals
392    let shutdown = async {
393        #[cfg(unix)]
394        {
395            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
396            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
397            tokio::select! {
398                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
399                _ = sigint.recv() => tracing::info!("Received SIGINT"),
400            }
401        }
402        #[cfg(windows)]
403        {
404            signal::ctrl_c().await?;
405            tracing::info!("Received Ctrl+C");
406        }
407        Ok::<(), anyhow::Error>(())
408    };
409
410    // Dispatch loop: requests from the scheduler and watcher are handled here;
411    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
412    let dispatch = async {
413        let state = state.clone();
414        loop {
415            tokio::select! {
416                // A request from the scheduler, watcher, or a directly-enqueued
417                // Shutdown.
418                request = request_rx.recv() => {
419                    match request {
420                        Some(request) => {
421                            if *state.shutdown.read().await || matches!(request, DaemonRequest::Shutdown) {
422                                break;
423                            }
424                            let handler = handler.clone();
425                            tokio::spawn(async move {
426                                let _ = handler.handle(request).await;
427                            });
428                        }
429                        None => break, // channel closed
430                    }
431                }
432                // Woken by the Shutdown handler (IK) so we can check the flag.
433                _ = state.shutdown_notify.notified() => {
434                    if *state.shutdown.read().await {
435                        break;
436                    }
437                }
438            }
439        }
440    };
441
442    // Run until shutdown signal or shutdown request
443    tokio::select! {
444        _ = shutdown => {
445            tracing::info!("Shutting down daemon...");
446        }
447        _ = dispatch => {
448            tracing::info!("Shutdown requested via IPC...");
449        }
450    }
451
452    // Graceful shutdown
453    scheduler.stop().await;
454
455    if let Some(w) = watcher.write().await.as_mut() {
456        w.stop().await;
457    }
458
459    ipc_handle.abort();
460    let _ = ipc_handle.await;
461
462    // Clean up socket file
463    let _ = tokio::fs::remove_file(&socket_path).await;
464
465    tracing::info!("Daemon stopped");
466    Ok(0)
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    #[test]
474    fn the_configured_pass_prunes_deleted_files_but_a_partial_one_does_not() {
475        let dir = tempfile::tempdir().unwrap();
476        let root = dir.path().join("docs");
477        std::fs::create_dir(&root).unwrap();
478        let (a, b) = (root.join("a.txt"), root.join("b.txt"));
479        std::fs::write(&a, "alpha zebra").unwrap();
480        std::fs::write(&b, "beta giraffe").unwrap();
481        let db = dir.path().join("chunks.db");
482        let configured = vec![root.clone()];
483        run_index_job(&db, None, &configured, &configured).unwrap();
484        std::fs::remove_file(&a).unwrap();
485        // A watcher-style pass over one other path must not prune.
486        run_index_job(&db, None, std::slice::from_ref(&b), &configured).unwrap();
487        let count = |p: &str| -> i64 {
488            Connection::open(&db)
489                .unwrap()
490                .inner()
491                .query_row(
492                    "SELECT COUNT(*) FROM chunks WHERE source_path = ?",
493                    [p],
494                    |r| r.get(0),
495                )
496                .unwrap()
497        };
498        let a = a.to_string_lossy().to_string();
499        assert_eq!(count(&a), 1);
500        run_index_job(&db, None, &configured, &configured).unwrap();
501        assert_eq!(count(&a), 0);
502    }
503}