paperscope 0.2.3

Paper: local-first document search with exact page and line citations. CLI + MCP server in one binary.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Daemon core: IPC server, scheduler, watcher, resource guard, and auto-discovery.

pub mod auto_discover;
pub mod ipc;
pub mod resource_guard;
pub mod scheduler;
pub mod watcher;

pub use ipc::DaemonHandler;

use crate::cli::Workspace;
use crate::core::index::{init_db, Connection, Indexer};
use crate::core::search::SharedEmbedder;
use crate::daemon::auto_discover::discover_default_roots;
use crate::daemon::ipc::{run_ipc_server, DaemonRequest, DaemonResponse};
use crate::daemon::resource_guard::{PauseReason, ResourceGuard, ResourceGuardConfig};
use crate::daemon::scheduler::RootAwareScheduler;
use crate::daemon::watcher::Watcher;
use anyhow::Result;
use clap::Args;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::signal;
use tokio::sync::{mpsc, Notify, RwLock};

/// Arguments for the daemon subcommand.
#[derive(Args, Debug, Clone)]
pub struct DaemonArgs {
    /// Run in foreground (don't daemonize)
    #[arg(long)]
    pub foreground: bool,

    /// Socket path for IPC (default: ~/.cache/paper/daemon.sock)
    #[arg(long)]
    pub socket: Option<PathBuf>,

    /// Roots to index (default: auto-discover Documents, Downloads, Desktop)
    #[arg(long, short)]
    pub root: Vec<PathBuf>,

    /// Disable file system watcher
    #[arg(long)]
    pub no_watch: bool,

    /// Disable scheduler
    #[arg(long)]
    pub no_schedule: bool,

    /// Disable resource guard (battery/CPU monitoring)
    #[arg(long)]
    pub no_resource_guard: bool,

    /// Full reindex cron expression (default: "0 0 3 * * *" = daily 3 AM)
    #[arg(long)]
    pub full_cron: Option<String>,

    /// Incremental index interval in seconds (default: 300 = 5 min)
    #[arg(long)]
    pub incremental_interval: Option<u64>,

    /// Debounce time for file watcher in milliseconds (default: 250)
    #[arg(long)]
    pub debounce_ms: Option<u64>,

    /// Battery threshold percentage (default: 20)
    #[arg(long)]
    pub battery_threshold: Option<u8>,

    /// CPU threshold percentage (default: 80)
    #[arg(long)]
    pub cpu_threshold: Option<u8>,
}

/// Shared daemon state.
///
/// Deliberately does NOT hold an `Indexer` or `Connection`: rusqlite
/// connections are not `Sync`, so each indexing request opens a fresh
/// connection inside `spawn_blocking` (the same pattern the CLI uses).
struct DaemonState {
    roots: RwLock<Vec<PathBuf>>,
    paused: RwLock<bool>,
    shutdown: RwLock<bool>,
    shutdown_notify: Arc<Notify>,
    db_path: PathBuf,
    embedder: Option<SharedEmbedder>,
}

/// Daemon request handler.
struct DaemonHandlerImpl {
    state: Arc<DaemonState>,
    scheduler: Arc<RootAwareScheduler>,
    watcher: Arc<RwLock<Option<Watcher>>>,
}

#[async_trait::async_trait]
impl DaemonHandler for DaemonHandlerImpl {
    async fn handle(&self, request: DaemonRequest) -> DaemonResponse {
        match request {
            DaemonRequest::IndexRoots { roots } => {
                let roots_to_index = if roots.is_empty() {
                    self.state.roots.read().await.clone()
                } else {
                    roots
                };

                if roots_to_index.is_empty() {
                    return DaemonResponse::Error {
                        msg: "No roots configured for indexing".to_string(),
                    };
                }

                if *self.state.paused.read().await {
                    return DaemonResponse::Error {
                        msg: "Indexing paused by resource guard".to_string(),
                    };
                }

                let db_path = self.state.db_path.clone();
                let embedder = self.state.embedder.clone();

                // Indexing is blocking CPU/IO work and `Indexer` is not `Send`:
                // create it inside the blocking task and run it there.
                match tokio::task::spawn_blocking(
                    move || -> Result<crate::core::index::IndexStats> {
                        let conn = Connection::open(&db_path)?;
                        init_db(&conn)?;
                        let indexer = Indexer::new(conn, embedder)?;
                        indexer.index_roots(&roots_to_index)
                    },
                )
                .await
                {
                    Ok(Ok(stats)) => DaemonResponse::IndexRoots { stats },
                    Ok(Err(e)) => DaemonResponse::Error {
                        msg: format!("Indexing failed: {e}"),
                    },
                    Err(e) => DaemonResponse::Error {
                        msg: format!("Indexing task failed: {e}"),
                    },
                }
            }
            DaemonRequest::AddRoot { path } => {
                if !path.exists() {
                    return DaemonResponse::Error {
                        msg: format!("Path does not exist: {}", path.display()),
                    };
                }

                let mut roots = self.state.roots.write().await;
                if !roots.contains(&path) {
                    roots.push(path.clone());
                    drop(roots);

                    if let Some(watcher) = self.watcher.write().await.as_mut() {
                        let _ = watcher.add_root(path.clone()).await;
                    }
                    self.scheduler.add_root(path).await;
                }
                DaemonResponse::Ok
            }
            DaemonRequest::RemoveRoot { path } => {
                self.state.roots.write().await.retain(|r| r != &path);

                if let Some(watcher) = self.watcher.write().await.as_mut() {
                    let _ = watcher.remove_root(&path).await;
                }
                self.scheduler.remove_root(&path).await;
                DaemonResponse::Ok
            }
            DaemonRequest::GetStatus => {
                let paused = *self.state.paused.read().await;
                // Open one connection and reuse it for both status queries
                // instead of opening two separate connections (M15).
                let (indexed_files, model) = match Connection::open(&self.state.db_path) {
                    Ok(conn) => (
                        Self::count_indexed_files(&conn),
                        Self::stored_embedding_model(&conn),
                    ),
                    Err(_) => (0, None),
                };

                DaemonResponse::Status {
                    indexed_files,
                    queued: 0,
                    paused,
                    model,
                }
            }
            DaemonRequest::Pause => {
                *self.state.paused.write().await = true;
                DaemonResponse::Ok
            }
            DaemonRequest::Resume => {
                *self.state.paused.write().await = false;
                DaemonResponse::Ok
            }
            DaemonRequest::Shutdown => {
                // Signal shutdown via a flag and wake the dispatch loop; do not
                // re-enqueue Shutdown on the same channel (IK).
                *self.state.shutdown.write().await = true;
                self.state.shutdown_notify.notify_waiters();
                DaemonResponse::Ok
            }
        }
    }
}

impl DaemonHandlerImpl {
    fn count_indexed_files(conn: &Connection) -> usize {
        conn.query_i64("SELECT COUNT(DISTINCT path) FROM chunks")
            .unwrap_or(0) as usize
    }

    fn stored_embedding_model(conn: &Connection) -> Option<String> {
        conn.stored_embedding_model().ok().flatten()
    }
}

/// Run the daemon until SIGTERM/SIGINT or an IPC `Shutdown` request.
pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
    let workspace = Workspace::new();

    // Determine socket path
    let socket_path = args
        .socket
        .unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));

    // Ensure parent directory exists
    if let Some(parent) = socket_path.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }

    // Determine roots to index
    let roots = if args.root.is_empty() {
        discover_default_roots()
    } else {
        args.root.clone()
    };

    if roots.is_empty() {
        tracing::warn!("No roots to index (auto-discovery found nothing and no --root provided)");
    } else {
        tracing::info!("Daemon will index: {:?}", roots);
    }

    // Load the embedder once (only if already on disk — never download here).
    let embedder = workspace.embedder();
    let db_path = workspace.paths.db_path();

    // Create channels
    let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);

    // Create shared state
    let state = Arc::new(DaemonState {
        roots: RwLock::new(roots.clone()),
        paused: RwLock::new(false),
        shutdown: RwLock::new(false),
        shutdown_notify: Arc::new(Notify::new()),
        db_path,
        embedder,
    });

    // Create scheduler
    let full_cron = args.full_cron.unwrap_or_else(|| "0 0 3 * * *".to_string());
    let incremental_interval = args
        .incremental_interval
        .map(std::time::Duration::from_secs)
        .unwrap_or_else(|| std::time::Duration::from_secs(5 * 60));
    let scheduler = Arc::new(RootAwareScheduler::new(
        &full_cron,
        incremental_interval,
        request_tx.clone(),
    )?);
    scheduler.set_roots(roots.clone()).await;

    // Create watcher
    let debounce_ms = args.debounce_ms.unwrap_or(250);
    let mut watcher = Watcher::new(debounce_ms, request_tx.clone());
    for root in &roots {
        watcher.add_root(root.clone()).await?;
    }
    let watcher = Arc::new(RwLock::new(Some(watcher)));

    // Create resource guard
    let mut resource_config = ResourceGuardConfig::default();
    if let Some(b) = args.battery_threshold {
        resource_config.battery_threshold = b;
    }
    if let Some(c) = args.cpu_threshold {
        resource_config.cpu_threshold = c;
    }
    let resource_guard = Arc::new(ResourceGuard::with_config(resource_config));

    // Create handler
    let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
        state: state.clone(),
        scheduler: scheduler.clone(),
        watcher: watcher.clone(),
    });

    // Start components
    if !args.no_schedule {
        scheduler.start().await;
    }

    if !args.no_watch {
        if let Some(w) = watcher.write().await.as_mut() {
            w.start().await?;
        }
    }

    if !args.no_resource_guard {
        let (pause_tx, mut pause_rx) = mpsc::channel::<PauseReason>(10);
        resource_guard.start_monitoring(pause_tx);
        let state = state.clone();
        tokio::spawn(async move {
            while let Some(reason) = pause_rx.recv().await {
                match reason {
                    PauseReason::Resumed => {
                        *state.paused.write().await = false;
                        tracing::info!("Resource guard: resuming indexing");
                    }
                    other => {
                        *state.paused.write().await = true;
                        tracing::warn!("Resource guard: pausing indexing due to {:?}", other);
                    }
                }
            }
        });
    }

    // Start IPC server task
    let socket_path_clone = socket_path.clone();
    let handler_clone = handler.clone();
    let ipc_handle = tokio::spawn(async move {
        if let Err(e) = run_ipc_server(&socket_path_clone, handler_clone).await {
            tracing::error!("IPC server error: {e}");
        }
    });

    // Handle shutdown signals
    let shutdown = async {
        #[cfg(unix)]
        {
            let mut sigterm = signal::unix::signal(signal::unix::SignalKind::terminate())?;
            let mut sigint = signal::unix::signal(signal::unix::SignalKind::interrupt())?;
            tokio::select! {
                _ = sigterm.recv() => tracing::info!("Received SIGTERM"),
                _ = sigint.recv() => tracing::info!("Received SIGINT"),
            }
        }
        #[cfg(windows)]
        {
            signal::ctrl_c().await?;
            tracing::info!("Received Ctrl+C");
        }
        Ok::<(), anyhow::Error>(())
    };

    // Dispatch loop: requests from the scheduler and watcher are handled here;
    // IPC requests are handled by the per-connection tasks in `run_ipc_server`.
    let dispatch = async {
        let state = state.clone();
        loop {
            tokio::select! {
                // A request from the scheduler, watcher, or a directly-enqueued
                // Shutdown.
                request = request_rx.recv() => {
                    match request {
                        Some(request) => {
                            if *state.shutdown.read().await || matches!(request, DaemonRequest::Shutdown) {
                                break;
                            }
                            let handler = handler.clone();
                            tokio::spawn(async move {
                                let _ = handler.handle(request).await;
                            });
                        }
                        None => break, // channel closed
                    }
                }
                // Woken by the Shutdown handler (IK) so we can check the flag.
                _ = state.shutdown_notify.notified() => {
                    if *state.shutdown.read().await {
                        break;
                    }
                }
            }
        }
    };

    // Run until shutdown signal or shutdown request
    tokio::select! {
        _ = shutdown => {
            tracing::info!("Shutting down daemon...");
        }
        _ = dispatch => {
            tracing::info!("Shutdown requested via IPC...");
        }
    }

    // Graceful shutdown
    scheduler.stop().await;

    if let Some(w) = watcher.write().await.as_mut() {
        w.stop().await;
    }

    ipc_handle.abort();
    let _ = ipc_handle.await;

    // Clean up socket file
    let _ = tokio::fs::remove_file(&socket_path).await;

    tracing::info!("Daemon stopped");
    Ok(0)
}