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, Mutex, Notify, RwLock};
#[derive(Args, Debug, Clone)]
pub struct DaemonArgs {
#[arg(long)]
pub foreground: bool,
#[arg(long)]
pub socket: Option<PathBuf>,
#[arg(long, short)]
pub root: Vec<PathBuf>,
#[arg(long)]
pub no_watch: bool,
#[arg(long)]
pub no_schedule: bool,
#[arg(long)]
pub no_resource_guard: bool,
#[arg(long)]
pub full_cron: Option<String>,
#[arg(long)]
pub incremental_interval: Option<u64>,
#[arg(long)]
pub debounce_ms: Option<u64>,
#[arg(long)]
pub battery_threshold: Option<u8>,
#[arg(long)]
pub cpu_threshold: Option<u8>,
}
struct DaemonState {
roots: RwLock<Vec<PathBuf>>,
paused: RwLock<bool>,
shutdown: RwLock<bool>,
shutdown_notify: Arc<Notify>,
db_path: PathBuf,
embedder: Option<SharedEmbedder>,
index_lock: Mutex<()>,
}
fn run_index_job(
db_path: &std::path::Path,
embedder: Option<SharedEmbedder>,
roots: &[PathBuf],
configured: &[PathBuf],
) -> Result<crate::core::index::IndexStats> {
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let indexer = Indexer::new(conn, embedder)?;
let stats = indexer.index_roots_within(roots, configured)?;
let sorted = |v: &[PathBuf]| {
let mut v = v.to_vec();
v.sort();
v
};
if sorted(roots) == sorted(configured) {
indexer.prune_missing()?;
}
Ok(stats)
}
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();
let configured = self.state.roots.read().await.clone();
let _running = self.state.index_lock.lock().await;
match tokio::task::spawn_blocking(move || {
run_index_job(&db_path, embedder, &roots_to_index, &configured)
})
.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;
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 => {
*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()
}
}
pub async fn run_daemon(args: DaemonArgs) -> Result<i32> {
let workspace = Workspace::new();
let socket_path = args
.socket
.unwrap_or_else(|| workspace.paths.base_dir().join("daemon.sock"));
if let Some(parent) = socket_path.parent() {
crate::core::paths::create_private_dir(parent)?;
}
let roots = if args.root.is_empty() {
let mut roots = discover_default_roots();
for root in &workspace.config.roots {
if !roots.contains(root) {
roots.push(root.clone());
}
}
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);
}
#[cfg(feature = "daemon")]
crate::bootstrap::ensure_models(&workspace).await;
let embedder = workspace.embedder();
let db_path = workspace.paths.db_path();
let (request_tx, mut request_rx) = mpsc::channel::<DaemonRequest>(100);
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,
index_lock: Mutex::new(()),
});
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;
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)));
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));
let handler: Arc<dyn DaemonHandler> = Arc::new(DaemonHandlerImpl {
state: state.clone(),
scheduler: scheduler.clone(),
watcher: watcher.clone(),
});
if !args.no_schedule {
scheduler.start().await;
#[cfg(feature = "daemon")]
if crate::bootstrap::index_is_empty(&workspace.paths) {
tracing::info!("empty index — starting the first indexing pass");
scheduler.trigger_incremental().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);
}
}
}
});
}
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:#}");
}
});
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>(())
};
let dispatch = async {
let state = state.clone();
loop {
tokio::select! {
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, }
}
_ = state.shutdown_notify.notified() => {
if *state.shutdown.read().await {
break;
}
}
}
}
};
tokio::select! {
_ = shutdown => {
tracing::info!("Shutting down daemon...");
}
_ = dispatch => {
tracing::info!("Shutdown requested via IPC...");
}
}
scheduler.stop().await;
if let Some(w) = watcher.write().await.as_mut() {
w.stop().await;
}
ipc_handle.abort();
let _ = ipc_handle.await;
let _ = tokio::fs::remove_file(&socket_path).await;
tracing::info!("Daemon stopped");
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_configured_pass_prunes_deleted_files_but_a_partial_one_does_not() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("docs");
std::fs::create_dir(&root).unwrap();
let (a, b) = (root.join("a.txt"), root.join("b.txt"));
std::fs::write(&a, "alpha zebra").unwrap();
std::fs::write(&b, "beta giraffe").unwrap();
let db = dir.path().join("chunks.db");
let configured = vec![root.clone()];
run_index_job(&db, None, &configured, &configured).unwrap();
std::fs::remove_file(&a).unwrap();
run_index_job(&db, None, std::slice::from_ref(&b), &configured).unwrap();
let count = |p: &str| -> i64 {
Connection::open(&db)
.unwrap()
.inner()
.query_row(
"SELECT COUNT(*) FROM chunks WHERE source_path = ?",
[p],
|r| r.get(0),
)
.unwrap()
};
let a = a.to_string_lossy().to_string();
assert_eq!(count(&a), 1);
run_index_job(&db, None, &configured, &configured).unwrap();
assert_eq!(count(&a), 0);
}
}