From a631d0a90f70805226b9ff8c663fc297cff69cd0 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 13:01:30 +0100 Subject: [PATCH 1/4] fix(core): adopt upstream when a dirty worktree is identical to it A worktree with another machine's snapshot applied stayed BehindDirty forever after the author committed and pushed that work. When the worktree content is byte-identical to the upstream tree, a mixed reset moves the branch without touching any file. Co-Authored-By: Claude Sonnet 5.5 --- crates/grove-core/src/receive.rs | 28 +++++++++++++++++++++++++- crates/grove-core/src/snapshot.rs | 33 ++++++++++++++++++++----------- crates/grove-core/tests/sync.rs | 31 ++++++++++++++++++++++------- 3 files changed, 73 insertions(+), 19 deletions(-) diff --git a/crates/grove-core/src/receive.rs b/crates/grove-core/src/receive.rs index 9491255..8a43e8d 100644 --- a/crates/grove-core/src/receive.rs +++ b/crates/grove-core/src/receive.rs @@ -109,13 +109,39 @@ pub enum Received { Declined(String), } +/// A dirty worktree that is behind its upstream is normally left alone. The exception is when its +/// content is exactly the upstream tree (typical: another machine's snapshot was applied here and +/// its author then committed and pushed it). Then moving the branch and index to upstream with a +/// mixed reset changes no file and loses nothing. +fn adopt_if_identical( + g: &Git, + machine: &str, + stamp: &str, + st: State, +) -> Result { + let worktree_tree = crate::snapshot::worktree_tree(g.dir())?; + let upstream_tree = g.run(&["rev-parse", "@{upstream}^{tree}"])?; + if worktree_tree != upstream_tree { + return Ok(Received::Skipped(st)); + } + let from = g.run(&["rev-parse", "HEAD"])?; + let bref = backup_ref(machine, stamp, &format!("receive/{}", current_branch(g)?)); + g.run(&["update-ref", &bref, &from])?; + g.run(&["reset", "-q", "@{upstream}"])?; + let to = g.run(&["rev-parse", "HEAD"])?; + Ok(Received::FastForwarded { from, to }) +} + /// Fast-forward a clean, strictly-behind worktree to its upstream. Anything else is skipped. pub fn receive(worktree: &Path, machine: &str, stamp: &str) -> Result { let st = state(worktree); + let g = Git::new(worktree); + if st == State::BehindDirty { + return adopt_if_identical(&g, machine, stamp, st); + } if st != State::Behind { return Ok(Received::Skipped(st)); } - let g = Git::new(worktree); let clash = ignored_conflicts(&g, "@{upstream}")?; if !clash.is_empty() { return Ok(Received::Declined(format!( diff --git a/crates/grove-core/src/snapshot.rs b/crates/grove-core/src/snapshot.rs index 3717947..ff592bb 100644 --- a/crates/grove-core/src/snapshot.rs +++ b/crates/grove-core/src/snapshot.rs @@ -39,17 +39,12 @@ fn temp_index_path() -> PathBuf { std::env::temp_dir().join(format!("grove-index-{}-{nanos}", std::process::id())) } -/// Take a snapshot of `worktree` for `machine`. `message_stamp` is embedded in the -/// commit message (callers pass a timestamp; keeping it a parameter keeps this testable). -pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result { - let git = Git::new(worktree); +/// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones), +/// built in a temporary copy of the index so the real index is never modified. The returned +/// guard keeps the temporary index alive; `Git` has it set as `GIT_INDEX_FILE` and the author +/// identity forced. +fn stage(git: &Git) -> Result<(TempIndex, Git, String), GitError> { let gitdir = PathBuf::from(git.run(&["rev-parse", "--absolute-git-dir"])?); - let branch = git - .probe(&["symbolic-ref", "--short", "-q", "HEAD"])? - .ok_or_else(|| GitError::Other("detached HEAD: cannot snapshot".into()))?; - let refname = ref_name(machine, &branch); - - // Work on a copy of the real index so the user's index is never modified. let tmp = TempIndex(temp_index_path()); let real_index = gitdir.join("index"); if real_index.exists() { @@ -62,9 +57,25 @@ pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result Result { + Ok(stage(&Git::new(worktree))?.2) +} + +/// Take a snapshot of `worktree` for `machine`. `message_stamp` is embedded in the +/// commit message (callers pass a timestamp; keeping it a parameter keeps this testable). +pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result { + let git = Git::new(worktree); + let branch = git + .probe(&["symbolic-ref", "--short", "-q", "HEAD"])? + .ok_or_else(|| GitError::Other("detached HEAD: cannot snapshot".into()))?; + let refname = ref_name(machine, &branch); + let (_tmp, snap, tree) = stage(&git)?; let prev = snap.probe(&["rev-parse", "-q", "--verify", &refname])?; if let Some(p) = &prev { diff --git a/crates/grove-core/tests/sync.rs b/crates/grove-core/tests/sync.rs index 594329a..08207c4 100644 --- a/crates/grove-core/tests/sync.rs +++ b/crates/grove-core/tests/sync.rs @@ -2,6 +2,7 @@ mod common; use common::*; use grove_core::git::Git; use grove_core::receive::Applied; +use grove_core::receive::Received; use grove_core::state::State; use grove_core::sync::{Options, sync_repo}; use std::fs; @@ -70,20 +71,36 @@ fn two_machines_converge_without_manual_git() { assert_eq!(fs::read_to_string(db.join("a.txt")).unwrap(), "1\nwork\n"); assert!(db.join("scratch.txt").exists()); - // A commits and pushes by hand; B (now dirty from the applied WIP) must not be touched. + // A commits and pushes by hand. B's applied copy is byte-identical to that commit, so B + // adopts it (mixed reset, no file touched) and ends clean. ga.run(&["add", "-A"]).unwrap(); ga.run(&["commit", "-qm", "work"]).unwrap(); ga.run(&["push", "-q"]).unwrap(); let rb2 = sync_repo(&db, &opts("B", "t3")).unwrap(); - assert_eq!(rb2.worktrees[0].state, State::BehindDirty); + assert_eq!(rb2.worktrees[0].state, State::Synced); + assert!(matches!( + rb2.worktrees[0].received, + Some(Received::FastForwarded { .. }) + )); assert_eq!(fs::read_to_string(db.join("a.txt")).unwrap(), "1\nwork\n"); + assert!( + Git::new(&db) + .run(&["status", "--porcelain"]) + .unwrap() + .is_empty() + ); - // Discarding B's applied copy makes it clean; the next sync fast-forwards it. - Git::new(&db).run(&["checkout", "-q", "--", "."]).unwrap(); - fs::remove_file(db.join("scratch.txt")).unwrap(); + // If B has its own extra edit when the next upstream commit arrives, it must not be touched. + fs::write(da.join("a.txt"), "1\nwork\nmore\n").unwrap(); + ga.run(&["commit", "-qam", "more"]).unwrap(); + ga.run(&["push", "-q"]).unwrap(); + fs::write(db.join("a.txt"), "1\nwork\nlocal\n").unwrap(); let rb3 = sync_repo(&db, &opts("B", "t4")).unwrap(); - assert_eq!(rb3.worktrees[0].state, State::Synced); - assert!(db.join("scratch.txt").exists()); + assert_eq!(rb3.worktrees[0].state, State::BehindDirty); + assert_eq!( + fs::read_to_string(db.join("a.txt")).unwrap(), + "1\nwork\nlocal\n" + ); } #[test] From 41ef589e582e28472c6cf78d75917fa6d923c2f9 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 13:01:30 +0100 Subject: [PATCH 2/4] feat(daemon): add groved with inotify watching, scheduler and IPC Debounced per-repo passes, periodic full pass, exponential backoff, pause and resume, JSON protocol over a Unix socket, activity log, grove daemon CLI client and a systemd user unit. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 195 +++++++++++++ Cargo.toml | 2 +- contrib/groved.service | 13 + crates/grove-daemon/Cargo.toml | 20 ++ crates/grove-daemon/src/activity.rs | 93 ++++++ crates/grove-daemon/src/daemon.rs | 430 ++++++++++++++++++++++++++++ crates/grove-daemon/src/discover.rs | 59 ++++ crates/grove-daemon/src/ipc.rs | 211 ++++++++++++++ crates/grove-daemon/src/lib.rs | 11 + crates/grove-daemon/src/main.rs | 36 +++ crates/grove-daemon/tests/daemon.rs | 309 ++++++++++++++++++++ crates/grove/Cargo.toml | 2 + crates/grove/src/main.rs | 100 +++++++ 13 files changed, 1480 insertions(+), 1 deletion(-) create mode 100644 contrib/groved.service create mode 100644 crates/grove-daemon/Cargo.toml create mode 100644 crates/grove-daemon/src/activity.rs create mode 100644 crates/grove-daemon/src/daemon.rs create mode 100644 crates/grove-daemon/src/discover.rs create mode 100644 crates/grove-daemon/src/ipc.rs create mode 100644 crates/grove-daemon/src/lib.rs create mode 100644 crates/grove-daemon/src/main.rs create mode 100644 crates/grove-daemon/tests/daemon.rs diff --git a/Cargo.lock b/Cargo.lock index a5a2423..d1374b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -58,6 +58,12 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "clap" version = "4.6.7" @@ -117,6 +123,8 @@ dependencies = [ "anyhow", "clap", "grove-core", + "grove-daemon", + "serde_json", ] [[package]] @@ -127,6 +135,17 @@ dependencies = [ "toml", ] +[[package]] +name = "grove-daemon" +version = "0.1.0" +dependencies = [ + "anyhow", + "grove-core", + "notify", + "serde", + "serde_json", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -149,12 +168,135 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys", +] + +[[package]] +name = "notify" +version = "8.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab" +dependencies = [ + "bitflags", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "objc2-core-foundation", + "objc2-core-services", + "walkdir", + "windows-sys", +] + +[[package]] +name = "notify-types" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-core-services" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -179,6 +321,15 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "serde" version = "1.0.229" @@ -209,6 +360,19 @@ dependencies = [ "syn", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "serde_spanned" version = "1.1.3" @@ -286,6 +450,31 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -306,3 +495,9 @@ name = "winnow" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index b734370..b764f5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/grove-core", "crates/grove"] +members = ["crates/grove-core", "crates/grove", "crates/grove-daemon"] [workspace.package] edition = "2024" diff --git a/contrib/groved.service b/contrib/groved.service new file mode 100644 index 0000000..7b17fd6 --- /dev/null +++ b/contrib/groved.service @@ -0,0 +1,13 @@ +[Unit] +Description=grove daemon (keeps git repos in sync across machines) +Documentation=https://git.zenvairo.es/dasemu/Grove + +[Service] +Type=simple +ExecStart=%h/.local/bin/groved +Restart=on-failure +RestartSec=5 +# Nothing to flush on stop: all durable state lives in git, so a plain SIGTERM is safe. + +[Install] +WantedBy=default.target diff --git a/crates/grove-daemon/Cargo.toml b/crates/grove-daemon/Cargo.toml new file mode 100644 index 0000000..61d6838 --- /dev/null +++ b/crates/grove-daemon/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "grove-daemon" +description = "grove user daemon: file watching, scheduler and IPC server" +edition.workspace = true +version.workspace = true +license.workspace = true + +[lib] +name = "grove_daemon" + +[[bin]] +name = "groved" +path = "src/main.rs" + +[dependencies] +anyhow = "1.0.104" +grove-core = { version = "0.1.0", path = "../grove-core" } +notify = "8.2.2" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" diff --git a/crates/grove-daemon/src/activity.rs b/crates/grove-daemon/src/activity.rs new file mode 100644 index 0000000..08fcfe0 --- /dev/null +++ b/crates/grove-daemon/src/activity.rs @@ -0,0 +1,93 @@ +//! Activity log: JSON lines on disk (rotated at 5 MiB), a ring buffer in memory and live +//! subscribers (the IPC `subscribe` command). + +use serde::Serialize; +use std::collections::VecDeque; +use std::fs::OpenOptions; +use std::io::Write; +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +const RING: usize = 500; +const MAX_FILE: u64 = 5 * 1024 * 1024; + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Event { + pub ts: u64, + pub kind: String, + pub repo: Option, + pub msg: String, +} + +pub struct Activity { + file: Option, + ring: Mutex>, + subs: Mutex>>, +} + +pub fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +impl Activity { + pub fn new(file: Option) -> Arc { + Arc::new(Activity { + file, + ring: Mutex::new(VecDeque::new()), + subs: Mutex::new(Vec::new()), + }) + } + + pub fn log(&self, kind: &str, repo: Option<&str>, msg: impl Into) { + let ev = Event { + ts: now_secs(), + kind: kind.to_string(), + repo: repo.map(str::to_string), + msg: msg.into(), + }; + self.append(&ev); + { + let mut ring = self.ring.lock().unwrap(); + if ring.len() == RING { + ring.pop_front(); + } + ring.push_back(ev.clone()); + } + self.subs + .lock() + .unwrap() + .retain(|s| s.send(ev.clone()).is_ok()); + } + + fn append(&self, ev: &Event) { + let Some(path) = &self.file else { return }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if std::fs::metadata(path).is_ok_and(|m| m.len() > MAX_FILE) { + let _ = std::fs::rename(path, path.with_extension("jsonl.1")); + } + if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(path) + && let Ok(line) = serde_json::to_string(ev) + { + let _ = writeln!(f, "{line}"); + } + } + + pub fn recent(&self, limit: usize) -> Vec { + let ring = self.ring.lock().unwrap(); + let skip = ring.len().saturating_sub(limit); + ring.iter().skip(skip).cloned().collect() + } + + pub fn subscribe(&self) -> Receiver { + let (tx, rx) = channel(); + self.subs.lock().unwrap().push(tx); + rx + } +} diff --git a/crates/grove-daemon/src/daemon.rs b/crates/grove-daemon/src/daemon.rs new file mode 100644 index 0000000..91fb931 --- /dev/null +++ b/crates/grove-daemon/src/daemon.rs @@ -0,0 +1,430 @@ +//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything +//! the watcher missed, failures back off exponentially. One worker thread runs the sync passes, +//! so passes never overlap. + +use crate::activity::{Activity, now_secs}; +use crate::discover::discover; +use crate::ipc; +use grove_core::config::Config; +use grove_core::receive::Received; +use grove_core::sync::{Options, sync_repo}; +use notify::{EventKind, RecursiveMode, Watcher}; +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +const MAX_BACKOFF: Duration = Duration::from_secs(300); + +#[derive(Debug, Clone)] +pub struct Settings { + pub socket: PathBuf, + pub activity_log: Option, + pub remote: String, +} + +impl Settings { + /// Standard locations: socket in `$XDG_RUNTIME_DIR/grove`, log in the state dir. + pub fn standard() -> Settings { + let state = Config::state_dir().unwrap_or_else(|| std::env::temp_dir().join("grove")); + Settings { + socket: ipc::default_socket_path(), + activity_log: Some(state.join("activity.jsonl")), + remote: "origin".into(), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct WtStatus { + pub branch: Option, + pub state: String, +} + +#[derive(Debug, Clone)] +pub struct RepoStatus { + /// `idle`, `pending`, `syncing` or `error`. + pub phase: &'static str, + pub last_sync: Option, + pub last_error: Option, + pub worktrees: Vec, + pub failures: u32, +} + +impl Default for RepoStatus { + fn default() -> Self { + RepoStatus { + phase: "idle", + last_sync: None, + last_error: None, + worktrees: Vec::new(), + failures: 0, + } + } +} + +#[derive(Debug, Default)] +pub struct Shared { + pub paused: bool, + pub repos: BTreeMap, +} + +pub enum Msg { + Changed(PathBuf), + /// Sync one repo (or all) as soon as possible. + SyncNow(Option), + Shutdown, +} + +#[derive(Clone)] +pub struct Ctx { + pub shared: Arc>, + pub activity: Arc, + pub tx: Sender, + pub machine: String, +} + +pub struct Daemon { + pub ctx: Ctx, + socket: PathBuf, + stop: Arc, + worker: Option>, + server: Option>, +} + +impl Daemon { + pub fn start(cfg: Config, st: Settings) -> std::io::Result { + let (tx, rx) = channel(); + let ctx = Ctx { + shared: Arc::default(), + activity: Activity::new(st.activity_log.clone()), + tx, + machine: cfg.machine.name.clone(), + }; + let stop = Arc::new(AtomicBool::new(false)); + let server = ipc::serve(&st.socket, ctx.clone(), stop.clone())?; + let worker = { + let ctx = ctx.clone(); + std::thread::spawn(move || run(cfg, st, rx, ctx)) + }; + ctx.activity.log("start", None, "daemon started"); + Ok(Daemon { + socket: server.socket.clone(), + ctx, + stop, + worker: Some(worker), + server: Some(server.handle), + }) + } + + /// Stop the worker and the IPC server. Work in progress is never lost: the worker finishes + /// the pass it is running and everything else lives in git. + pub fn shutdown(mut self) { + self.stop.store(true, Ordering::SeqCst); + let _ = self.ctx.tx.send(Msg::Shutdown); + if let Some(h) = self.worker.take() { + let _ = h.join(); + } + if let Some(h) = self.server.take() { + let _ = h.join(); + } + let _ = std::fs::remove_file(&self.socket); + } +} + +fn stamp() -> String { + static SEQ: AtomicU64 = AtomicU64::new(0); + let ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + format!("{ms}-{}", SEQ.fetch_add(1, Ordering::SeqCst)) +} + +/// Matches one path component against an ignore pattern: exact name or `*suffix`. +fn pattern_matches(pat: &str, name: &str) -> bool { + match pat.strip_prefix('*') { + Some(suffix) => name.ends_with(suffix), + None => name == pat, + } +} + +/// True for paths whose changes must not trigger a sync: git internals and user-ignored names. +pub fn ignored(rel: &Path, extra: &[String]) -> bool { + rel.components().any(|c| { + let n = c.as_os_str().to_string_lossy(); + n == ".git" + || n == ".bare" + || n == ".grove-stage" + || extra.iter().any(|p| pattern_matches(p, &n)) + }) +} + +fn repo_of<'a>(path: &Path, repos: &'a [PathBuf]) -> Option<&'a PathBuf> { + repos.iter().find(|r| path.starts_with(r)) +} + +struct Watch { + watcher: Option, + repos: Arc>>, + watched: Vec, +} + +fn make_watch(tx: Sender, extra: Vec, ctx: &Ctx) -> Watch { + let repos: Arc>> = Arc::default(); + let cb_repos = repos.clone(); + let handler = move |res: notify::Result| { + let Ok(ev) = res else { return }; + if matches!(ev.kind, EventKind::Access(_)) { + return; + } + let repos = cb_repos.lock().unwrap(); + for p in &ev.paths { + if let Some(r) = repo_of(p, &repos) + && let Ok(rel) = p.strip_prefix(r) + && !ignored(rel, &extra) + { + let _ = tx.send(Msg::Changed(r.clone())); + } + } + }; + let watcher = match notify::recommended_watcher(handler) { + Ok(w) => Some(w), + Err(e) => { + ctx.activity.log( + "watch_error", + None, + format!("file watching unavailable, periodic passes only: {e}"), + ); + None + } + }; + Watch { + watcher, + repos, + watched: Vec::new(), + } +} + +impl Watch { + fn add(&mut self, repo: &Path, ctx: &Ctx) { + if self.watched.iter().any(|w| w == repo) { + return; + } + self.watched.push(repo.to_path_buf()); + self.repos.lock().unwrap().push(repo.to_path_buf()); + if let Some(w) = &mut self.watcher + && let Err(e) = w.watch(repo, RecursiveMode::Recursive) + { + ctx.activity.log( + "watch_error", + Some(&repo.display().to_string()), + format!( + "cannot watch (raise fs.inotify.max_user_watches?): {e}; relying on periodic passes" + ), + ); + } + } +} + +fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec { + let found = discover(root); + let mut shared = ctx.shared.lock().unwrap(); + for r in &found { + shared.repos.entry(r.clone()).or_default(); + } + drop(shared); + for r in &found { + watch.add(r, ctx); + } + found +} + +fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { + let debounce = Duration::from_millis(cfg.sync.snapshot_debounce_ms); + let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1)); + let root = cfg.root_path(); + let mut watch = make_watch(ctx.tx.clone(), cfg.sync.ignore_extra.clone(), &ctx); + rescan(&root, &mut watch, &ctx); + let materialize = cfg.groups.iter().all(|g| g.auto_materialize); + + // due_at: when a repo should next be synced; backoff_until: earliest retry after failures. + let mut due_at: HashMap = HashMap::new(); + let mut backoff_until: HashMap = HashMap::new(); + let mut next_full = Instant::now(); + + loop { + let now = Instant::now(); + let wake = due_at + .values() + .copied() + .chain([next_full]) + .min() + .unwrap_or(next_full); + let timeout = wake + .saturating_duration_since(now) + .min(Duration::from_secs(1)); + match rx.recv_timeout(timeout) { + Ok(Msg::Changed(r)) => { + let at = Instant::now() + debounce; + due_at.insert(r.clone(), at); + if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(&r) + && s.phase == "idle" + { + s.phase = "pending"; + } + } + Ok(Msg::SyncNow(Some(r))) => { + backoff_until.remove(&r); + due_at.insert(r, Instant::now()); + } + Ok(Msg::SyncNow(None)) => { + backoff_until.clear(); + next_full = Instant::now(); + } + Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + } + if ctx.shared.lock().unwrap().paused { + continue; + } + let now = Instant::now(); + if now >= next_full { + for r in rescan(&root, &mut watch, &ctx) { + due_at.insert(r, now); + } + next_full = now + fetch_every; + } + let mut due: Vec = due_at + .iter() + .filter(|(_, t)| **t <= now) + .map(|(r, _)| r.clone()) + .collect(); + due.sort(); + for r in due { + if let Some(until) = backoff_until.get(&r).filter(|u| **u > now) { + due_at.insert(r, *until); + continue; + } + due_at.remove(&r); + let failures = pass(&r, &cfg, &st, materialize, &ctx); + if failures == 0 { + backoff_until.remove(&r); + } else { + let wait = + Duration::from_secs(5u64.saturating_mul(1 << failures.min(6))).min(MAX_BACKOFF); + backoff_until.insert(r, Instant::now() + wait); + } + if ctx.shared.lock().unwrap().paused { + break; + } + } + } + ctx.activity.log("stop", None, "daemon stopped"); +} + +/// One sync pass for `repo`; returns the number of consecutive failures (0 = success). +fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx) -> u32 { + let name = repo.display().to_string(); + set_phase(ctx, repo, "syncing"); + let opts = Options { + machine: cfg.machine.name.clone(), + stamp: stamp(), + remote: st.remote.clone(), + offline: false, + materialize, + }; + let result = sync_repo(repo, &opts); + let mut shared = ctx.shared.lock().unwrap(); + let status = shared.repos.entry(repo.to_path_buf()).or_default(); + let mut errors: Vec = Vec::new(); + match result { + Err(e) => errors.push(e.to_string()), + Ok(rep) => { + errors.extend(rep.fetch_error.clone()); + let mut now_wts = Vec::new(); + for w in &rep.worktrees { + let branch = w.branch.clone().unwrap_or_else(|| "(detached)".into()); + let state = format!("{:?}", w.state).to_lowercase(); + if let Some(kind) = w.snapshot { + ctx.activity + .log("snapshot", Some(&name), format!("{branch}: {kind}")); + } + match &w.received { + Some(Received::FastForwarded { .. }) => { + ctx.activity + .log("fast_forward", Some(&name), branch.clone()) + } + Some(Received::Declined(why)) => ctx.activity.log( + "declined", + Some(&name), + format!("{branch}: not fast-forwarded: {why}"), + ), + _ => {} + } + if let Some((m, a)) = &w.applied { + ctx.activity + .log("applied", Some(&name), format!("{branch}: {a:?} from {m}")); + } + let prev = status + .worktrees + .iter() + .find(|p| p.branch.as_deref() == Some(&branch)) + .map(|p| p.state.clone()); + if prev.as_deref() != Some(&state) { + ctx.activity + .log("state", Some(&name), format!("{branch}: {state}")); + } + errors.extend(w.errors.iter().map(|e| format!("{branch}: {e}"))); + now_wts.push(WtStatus { + branch: w.branch.clone(), + state, + }); + } + status.worktrees = now_wts; + for p in &rep.materialized { + ctx.activity + .log("materialized", Some(&name), p.display().to_string()); + } + for a in &rep.archived { + ctx.activity.log("archived", Some(&name), format!("{a:?}")); + } + } + } + if errors.is_empty() { + status.phase = "idle"; + status.failures = 0; + status.last_error = None; + status.last_sync = Some(now_secs()); + } else { + status.phase = "error"; + status.failures += 1; + status.last_error = Some(errors.join("; ")); + ctx.activity.log("error", Some(&name), errors.join("; ")); + } + status.failures +} + +fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) { + if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) { + s.phase = phase; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ignores_git_internals_and_patterns() { + let extra = vec!["node_modules".to_string(), "*.swp".to_string()]; + assert!(ignored(Path::new(".bare/objects/ab"), &extra)); + assert!(ignored(Path::new("main/.git"), &extra)); + assert!(ignored(Path::new("main/node_modules/x/y.js"), &extra)); + assert!(ignored(Path::new("main/src/.a.rs.swp"), &extra)); + assert!(!ignored(Path::new("main/src/a.rs"), &extra)); + } +} diff --git a/crates/grove-daemon/src/discover.rs b/crates/grove-daemon/src/discover.rs new file mode 100644 index 0000000..33a4cfc --- /dev/null +++ b/crates/grove-daemon/src/discover.rs @@ -0,0 +1,59 @@ +//! Finds the repos managed under the workspace root: `root/` or `root//`, +//! where a repo has a `.bare` directory (bare + worktrees layout) or a `.git`. + +use std::path::{Path, PathBuf}; + +fn is_repo(p: &Path) -> bool { + p.join(".bare").is_dir() || p.join(".git").exists() +} + +fn subdirs(p: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(p) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) + .filter(|e| !e.file_name().to_string_lossy().starts_with('.')) + .map(|e| e.path()) + .collect(); + v.sort(); + v +} + +pub fn discover(root: &Path) -> Vec { + let mut out = Vec::new(); + for child in subdirs(root) { + if is_repo(&child) { + out.push(child); + } else { + out.extend(subdirs(&child).into_iter().filter(|g| is_repo(g))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_repos_at_depth_one_and_two_and_skips_hidden() { + let base = std::env::temp_dir().join(format!("grove-disc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in [ + "a/.git", + "grp/b/.bare", + "grp/plain", + ".hidden/.git", + "c/inner/.git", + ] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + let found = discover(&base); + assert_eq!( + found, + vec![base.join("a"), base.join("c/inner"), base.join("grp/b")] + ); + std::fs::remove_dir_all(&base).unwrap(); + } +} diff --git a/crates/grove-daemon/src/ipc.rs b/crates/grove-daemon/src/ipc.rs new file mode 100644 index 0000000..df75143 --- /dev/null +++ b/crates/grove-daemon/src/ipc.rs @@ -0,0 +1,211 @@ +//! Local IPC: a Unix socket speaking line-delimited JSON, protocol version 1. +//! +//! Request: `{"v":1,"cmd":"status"|"ping"|"pause"|"resume"|"sync"|"log"|"subscribe", ...}` +//! Response: `{"v":1,"ok":true,"data":...}` or `{"v":1,"ok":false,"error":"..."}`. +//! After `subscribe` the server keeps the connection open and streams `{"v":1,"event":{...}}`. + +use crate::activity::now_secs; +use crate::daemon::{Ctx, Msg}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Write}; +use std::os::unix::fs::DirBuilderExt; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::JoinHandle; +use std::time::Duration; + +pub const PROTOCOL: u32 = 1; + +pub struct Server { + pub socket: PathBuf, + pub handle: JoinHandle<()>, +} + +/// `$XDG_RUNTIME_DIR/grove/grove.sock`, falling back to the state dir. +pub fn default_socket_path() -> PathBuf { + let base = std::env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .or_else(grove_core::config::Config::state_dir) + .unwrap_or_else(std::env::temp_dir); + base.join("grove").join("grove.sock") +} + +#[derive(Deserialize)] +struct Request { + v: u32, + cmd: String, + #[serde(default)] + repo: Option, + #[serde(default)] + limit: Option, +} + +pub fn serve(socket: &Path, ctx: Ctx, stop: Arc) -> std::io::Result { + if let Some(dir) = socket.parent() { + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir)?; + } + if socket.exists() { + if UnixStream::connect(socket).is_ok() { + return Err(std::io::Error::new( + std::io::ErrorKind::AddrInUse, + format!( + "another daemon is already listening on {}", + socket.display() + ), + )); + } + std::fs::remove_file(socket)?; // stale socket from a crashed daemon + } + let listener = UnixListener::bind(socket)?; + listener.set_nonblocking(true)?; + let handle = std::thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + match listener.accept() { + Ok((conn, _)) => { + let ctx = ctx.clone(); + let stop = stop.clone(); + std::thread::spawn(move || connection(conn, ctx, stop)); + } + Err(_) => std::thread::sleep(Duration::from_millis(50)), + } + } + }); + Ok(Server { + socket: socket.to_path_buf(), + handle, + }) +} + +fn reply(conn: &mut UnixStream, v: Value) -> bool { + writeln!(conn, "{v}").is_ok() +} + +fn err(msg: &str) -> Value { + json!({"v": PROTOCOL, "ok": false, "error": msg}) +} + +fn ok(data: Value) -> Value { + json!({"v": PROTOCOL, "ok": true, "data": data}) +} + +fn connection(mut conn: UnixStream, ctx: Ctx, stop: Arc) { + let _ = conn.set_nonblocking(false); + let Ok(read_half) = conn.try_clone() else { + return; + }; + for line in BufReader::new(read_half).lines() { + let Ok(line) = line else { return }; + if line.trim().is_empty() { + continue; + } + let req: Request = match serde_json::from_str(&line) { + Ok(r) => r, + Err(e) => { + if !reply(&mut conn, err(&format!("bad request: {e}"))) { + return; + } + continue; + } + }; + if req.v != PROTOCOL { + let msg = format!( + "unsupported protocol version {} (server speaks {PROTOCOL})", + req.v + ); + if !reply(&mut conn, err(&msg)) { + return; + } + continue; + } + if req.cmd == "subscribe" { + let rx = ctx.activity.subscribe(); + if !reply(&mut conn, ok(json!("subscribed"))) { + return; + } + while !stop.load(Ordering::SeqCst) { + if let Ok(ev) = rx.recv_timeout(Duration::from_secs(1)) + && !reply(&mut conn, json!({"v": PROTOCOL, "event": ev})) + { + return; + } + } + return; + } + if !reply(&mut conn, handle(&req, &ctx)) { + return; + } + } +} + +fn handle(req: &Request, ctx: &Ctx) -> Value { + match req.cmd.as_str() { + "ping" => ok(json!("pong")), + "status" => { + let s = ctx.shared.lock().unwrap(); + let repos: Vec = s + .repos + .iter() + .map(|(p, r)| { + json!({ + "path": p.display().to_string(), + "phase": r.phase, + "last_sync": r.last_sync, + "last_error": r.last_error, + "failures": r.failures, + "worktrees": r.worktrees.iter() + .map(|w| json!({"branch": w.branch, "state": w.state})) + .collect::>(), + }) + }) + .collect(); + ok( + json!({"machine": ctx.machine, "paused": s.paused, "now": now_secs(), "repos": repos}), + ) + } + "pause" | "resume" => { + let paused = req.cmd == "pause"; + ctx.shared.lock().unwrap().paused = paused; + ctx.activity.log( + &req.cmd, + None, + if paused { + "sync paused" + } else { + "sync resumed" + }, + ); + if !paused { + let _ = ctx.tx.send(Msg::SyncNow(None)); + } + ok(json!({"paused": paused})) + } + "sync" => { + let target = req.repo.as_ref().map(PathBuf::from); + if let Some(t) = &target + && !ctx.shared.lock().unwrap().repos.contains_key(t) + { + return err("unknown repo"); + } + let _ = ctx.tx.send(Msg::SyncNow(target)); + ok(json!("queued")) + } + "log" => ok(json!(ctx.activity.recent(req.limit.unwrap_or(50)))), + other => err(&format!("unknown command {other:?}")), + } +} + +/// Send one request and read one response. For use by the CLI and tests. +pub fn request(socket: &Path, req: &Value) -> std::io::Result { + let mut conn = UnixStream::connect(socket)?; + conn.set_read_timeout(Some(Duration::from_secs(10)))?; + writeln!(conn, "{req}")?; + let mut line = String::new(); + BufReader::new(conn).read_line(&mut line)?; + serde_json::from_str(&line).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) +} diff --git a/crates/grove-daemon/src/lib.rs b/crates/grove-daemon/src/lib.rs new file mode 100644 index 0000000..760ccfe --- /dev/null +++ b/crates/grove-daemon/src/lib.rs @@ -0,0 +1,11 @@ +//! grove user daemon: watches managed repos, debounces changes, runs sync passes on a schedule +//! and serves a small JSON protocol over a Unix socket. All durable state lives in git; the +//! daemon itself holds nothing that a crash could lose. + +pub mod activity; +pub mod daemon; +pub mod discover; +pub mod ipc; + +pub use activity::{Activity, Event}; +pub use daemon::{Daemon, Settings}; diff --git a/crates/grove-daemon/src/main.rs b/crates/grove-daemon/src/main.rs new file mode 100644 index 0000000..6b6ea72 --- /dev/null +++ b/crates/grove-daemon/src/main.rs @@ -0,0 +1,36 @@ +//! `groved`: the grove user daemon (run it as a systemd user service, see `contrib/`). + +use anyhow::{Context, Result}; +use grove_core::config::Config; +use grove_daemon::{Daemon, Settings}; +use std::path::PathBuf; + +fn main() -> Result<()> { + let mut args = std::env::args().skip(1); + let mut config: Option = None; + while let Some(a) = args.next() { + match a.as_str() { + "--config" => config = Some(args.next().context("--config needs a path")?.into()), + "-h" | "--help" => { + println!("groved [--config PATH]\nKeeps the repos under root.path in sync."); + return Ok(()); + } + other => anyhow::bail!("unknown argument {other:?}"), + } + } + let path = config + .or_else(Config::default_path) + .context("cannot determine config path")?; + let cfg = Config::load(&path)?; + let st = Settings::standard(); + eprintln!( + "groved: machine {:?}, root {}, socket {}", + cfg.machine.name, + cfg.root_path().display(), + st.socket.display() + ); + let _daemon = Daemon::start(cfg, st).context("cannot start daemon")?; + loop { + std::thread::park(); + } +} diff --git a/crates/grove-daemon/tests/daemon.rs b/crates/grove-daemon/tests/daemon.rs new file mode 100644 index 0000000..85ee586 --- /dev/null +++ b/crates/grove-daemon/tests/daemon.rs @@ -0,0 +1,309 @@ +use grove_core::config::Config; +use grove_daemon::{Daemon, Settings, ipc}; +use serde_json::json; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(dir) + .args(args) + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@t") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@t") + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?} in {}: {}", + dir.display(), + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +fn wait_until(what: &str, secs: u64, mut f: impl FnMut() -> bool) { + let end = Instant::now() + Duration::from_secs(secs); + while Instant::now() < end { + if f() { + return; + } + std::thread::sleep(Duration::from_millis(100)); + } + panic!("timed out waiting for {what}"); +} + +struct World { + base: PathBuf, + remote: PathBuf, +} + +fn tmpdir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("grove-dt-{tag}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d +} + +/// A bare remote plus one seeded clone per machine under `//repo`. +fn world(tag: &str, machines: &[&str]) -> World { + let base = tmpdir(tag); + let remote = base.join("remote.git"); + fs::create_dir_all(&remote).unwrap(); + git(&remote, &["init", "-q", "--bare", "-b", "main"]); + let seed = base.join("seed"); + fs::create_dir_all(&seed).unwrap(); + git(&seed, &["init", "-q", "-b", "main"]); + fs::write(seed.join("a.txt"), "one\n").unwrap(); + git(&seed, &["add", "-A"]); + git(&seed, &["commit", "-qm", "init"]); + git( + &seed, + &["remote", "add", "origin", remote.to_str().unwrap()], + ); + git(&seed, &["push", "-q", "origin", "main"]); + for m in machines { + let dir = base.join(m); + fs::create_dir_all(&dir).unwrap(); + git(&dir, &["clone", "-q", remote.to_str().unwrap(), "repo"]); + } + World { base, remote } +} + +fn config(w: &World, machine: &str, debounce_ms: u64, fetch_s: u64) -> Config { + Config::parse(&format!( + "[machine]\nname = \"{machine}\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = {debounce_ms}\nfetch_interval_s = {fetch_s}\n", + w.base.join(machine).display() + )) + .unwrap() +} + +fn settings(w: &World, machine: &str) -> Settings { + Settings { + socket: w.base.join(format!("{machine}.sock")), + activity_log: Some(w.base.join(format!("{machine}.jsonl"))), + remote: "origin".into(), + } +} + +fn start(w: &World, machine: &str) -> Daemon { + Daemon::start(config(w, machine, 200, 2), settings(w, machine)).unwrap() +} + +#[test] +fn edit_on_a_shows_up_on_b() { + let w = world("converge", &["pca", "pcb"]); + let a = start(&w, "pca"); + let b = start(&w, "pcb"); + let file_a = w.base.join("pca/repo/new.txt"); + fs::write(&file_a, "hello\n").unwrap(); + fs::write(w.base.join("pca/repo/a.txt"), "one\nedited\n").unwrap(); + let on_b = w.base.join("pcb/repo/new.txt"); + wait_until("new.txt on B", 30, || { + fs::read_to_string(&on_b).is_ok_and(|s| s == "hello\n") + }); + assert_eq!( + fs::read_to_string(w.base.join("pcb/repo/a.txt")).unwrap(), + "one\nedited\n" + ); + // The user's branch on A was never touched by the daemon. + assert_eq!( + git(&w.base.join("pca/repo"), &["log", "--oneline"]) + .lines() + .count(), + 1 + ); + a.shutdown(); + b.shutdown(); +} + +#[test] +fn committed_work_fast_forwards_the_other_machine() { + let w = world("ff", &["pca", "pcb"]); + let a = start(&w, "pca"); + let b = start(&w, "pcb"); + let ra = w.base.join("pca/repo"); + fs::write(ra.join("c.txt"), "committed\n").unwrap(); + git(&ra, &["add", "-A"]); + git(&ra, &["commit", "-qm", "c"]); + git(&ra, &["push", "-q", "origin", "main"]); + let rb = w.base.join("pcb/repo"); + wait_until("B fast-forwarded", 30, || rb.join("c.txt").exists()); + wait_until("B synced", 30, || { + git(&rb, &["status", "--porcelain"]).is_empty() + && git(&rb, &["log", "--oneline"]).lines().count() == 2 + }); + a.shutdown(); + b.shutdown(); +} + +#[test] +fn ipc_status_pause_resume_log_and_subscribe() { + let w = world("ipc", &["pca"]); + let st = settings(&w, "pca"); + let sock = st.socket.clone(); + let d = Daemon::start(config(&w, "pca", 200, 2), st).unwrap(); + + assert_eq!( + ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).unwrap()["data"], + "pong" + ); + let bad = ipc::request(&sock, &json!({"v":99,"cmd":"ping"})).unwrap(); + assert_eq!(bad["ok"], false); + let unknown = ipc::request(&sock, &json!({"v":1,"cmd":"nope"})).unwrap(); + assert_eq!(unknown["ok"], false); + + let repo = w.base.join("pca/repo"); + wait_until("status lists the repo", 10, || { + let s = ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap(); + s["data"]["repos"].as_array().is_some_and(|r| r.len() == 1) + }); + + // While paused, edits must not produce a snapshot. + assert_eq!( + ipc::request(&sock, &json!({"v":1,"cmd":"pause"})).unwrap()["data"]["paused"], + true + ); + fs::write(repo.join("p.txt"), "paused\n").unwrap(); + std::thread::sleep(Duration::from_secs(3)); + assert!( + git(&repo, &["for-each-ref", "refs/sync/"]).is_empty(), + "snapshot while paused" + ); + + // Resume: the pending change is snapshotted; subscribers see it. + let mut sub = std::os::unix::net::UnixStream::connect(&sock).unwrap(); + use std::io::{BufRead, BufReader, Write}; + writeln!(sub, "{}", json!({"v":1,"cmd":"subscribe"})).unwrap(); + sub.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + let mut rd = BufReader::new(sub); + let mut line = String::new(); + rd.read_line(&mut line).unwrap(); + assert!(line.contains("subscribed")); + ipc::request(&sock, &json!({"v":1,"cmd":"resume"})).unwrap(); + let mut saw_snapshot = false; + for _ in 0..20 { + line.clear(); + if rd.read_line(&mut line).unwrap() == 0 { + break; + } + if line.contains("\"kind\":\"snapshot\"") { + saw_snapshot = true; + break; + } + } + assert!(saw_snapshot, "no snapshot event streamed"); + assert!(git(&repo, &["for-each-ref", "refs/sync/"]).contains("refs/sync/pca/main")); + + let log = ipc::request(&sock, &json!({"v":1,"cmd":"log","limit":100})).unwrap(); + let kinds: Vec<&str> = log["data"] + .as_array() + .unwrap() + .iter() + .map(|e| e["kind"].as_str().unwrap()) + .collect(); + assert!( + kinds.contains(&"pause") && kinds.contains(&"resume") && kinds.contains(&"snapshot"), + "{kinds:?}" + ); + assert!( + w.base.join("pca.jsonl").exists(), + "activity log file written" + ); + d.shutdown(); + assert!(!sock.exists(), "socket removed on shutdown"); + let _ = &w.remote; +} + +#[test] +fn second_daemon_on_same_socket_is_refused_and_stale_socket_is_reused() { + let w = world("sock", &["pca"]); + let st = settings(&w, "pca"); + let d = Daemon::start(config(&w, "pca", 200, 2), st.clone()).unwrap(); + assert!(Daemon::start(config(&w, "pca", 200, 2), st.clone()).is_err()); + d.shutdown(); + // A leftover socket file with nobody listening must not block startup. + fs::write(&st.socket, "").unwrap(); + let d = Daemon::start(config(&w, "pca", 200, 2), st).unwrap(); + d.shutdown(); +} + +#[test] +fn killing_the_daemon_loses_nothing_and_a_restart_recovers() { + let w = world("crash", &["pca"]); + let repo = w.base.join("pca/repo"); + let cfg_path = w.base.join("config.toml"); + fs::write( + &cfg_path, + format!( + "[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n", + w.base.join("pca").display() + ), + ) + .unwrap(); + let runtime = w.base.join("run"); + fs::create_dir_all(&runtime).unwrap(); + let spawn = || { + Command::new(env!("CARGO_BIN_EXE_groved")) + .arg("--config") + .arg(&cfg_path) + .env("XDG_RUNTIME_DIR", &runtime) + .env("XDG_STATE_HOME", w.base.join("state")) + .env("GIT_AUTHOR_NAME", "t") + .spawn() + .unwrap() + }; + let mut child = spawn(); + std::thread::sleep(Duration::from_millis(300)); + fs::write(repo.join("wip.txt"), "precious\n").unwrap(); + // Kill at an arbitrary moment: maybe before, during or after a pass. + std::thread::sleep(Duration::from_millis(400)); + child.kill().unwrap(); + child.wait().unwrap(); + + assert_eq!( + fs::read_to_string(repo.join("wip.txt")).unwrap(), + "precious\n" + ); + assert!( + !repo.join(".git/index.lock").exists(), + "stale index.lock after kill" + ); + git(&repo, &["fsck", "--no-dangling"]); + + // Restart over the stale socket: the snapshot is (re)taken and the work is still there. + let mut child = spawn(); + wait_until("snapshot after restart", 30, || { + git(&repo, &["for-each-ref", "refs/sync/"]).contains("refs/sync/pca/main") + }); + assert_eq!( + fs::read_to_string(repo.join("wip.txt")).unwrap(), + "precious\n" + ); + child.kill().unwrap(); + child.wait().unwrap(); +} + +#[test] +fn work_in_progress_then_committed_on_a_leaves_b_clean() { + let w = world("wipcommit", &["pca", "pcb"]); + let a = start(&w, "pca"); + let b = start(&w, "pcb"); + let ra = w.base.join("pca/repo"); + let rb = w.base.join("pcb/repo"); + fs::write(ra.join("w.txt"), "wip\n").unwrap(); + wait_until("WIP on B", 30, || rb.join("w.txt").exists()); + git(&ra, &["add", "-A"]); + git(&ra, &["commit", "-qm", "w"]); + git(&ra, &["push", "-q", "origin", "main"]); + wait_until("B clean at the new commit", 30, || { + git(&rb, &["status", "--porcelain"]).is_empty() + && git(&rb, &["log", "--oneline"]).lines().count() == 2 + }); + assert_eq!(fs::read_to_string(rb.join("w.txt")).unwrap(), "wip\n"); + a.shutdown(); + b.shutdown(); +} diff --git a/crates/grove/Cargo.toml b/crates/grove/Cargo.toml index 917c3ca..aa043ce 100644 --- a/crates/grove/Cargo.toml +++ b/crates/grove/Cargo.toml @@ -8,3 +8,5 @@ version.workspace = true anyhow = "1.0.104" clap = { version = "4.6.7", features = ["derive"] } grove-core = { version = "0.1.0", path = "../grove-core" } +grove-daemon = { version = "0.1.0", path = "../grove-daemon" } +serde_json = "1.0.154" diff --git a/crates/grove/src/main.rs b/crates/grove/src/main.rs index afa81e8..ca5e2f8 100644 --- a/crates/grove/src/main.rs +++ b/crates/grove/src/main.rs @@ -49,6 +49,28 @@ enum Cmd { }, /// Check the local setup Doctor, + /// Talk to the running daemon (`groved`) + Daemon { + #[command(subcommand)] + action: DaemonCmd, + }, +} + +#[derive(Subcommand)] +enum DaemonCmd { + /// Show every managed repo and its state + Status, + /// Stop syncing until `resume` + Pause, + /// Resume syncing (runs a full pass right away) + Resume, + /// Sync now: one repo (path as shown by `status`) or all + Sync { repo: Option }, + /// Show recent activity + Log { + #[arg(long, default_value_t = 30)] + limit: usize, + }, } fn load_config(arg: &Option) -> Result { @@ -66,9 +88,87 @@ fn stamp() -> String { .to_string() } +fn daemon(action: &DaemonCmd) -> Result<()> { + use serde_json::json; + let socket = grove_daemon::ipc::default_socket_path(); + let ask = |req: serde_json::Value| -> Result { + let resp = grove_daemon::ipc::request(&socket, &req).with_context(|| { + format!( + "cannot reach the daemon at {} (is groved running?)", + socket.display() + ) + })?; + if resp["ok"] != true { + bail!( + "daemon error: {}", + resp["error"].as_str().unwrap_or("unknown") + ); + } + Ok(resp["data"].clone()) + }; + match action { + DaemonCmd::Status => { + let d = ask(json!({"v": 1, "cmd": "status"}))?; + println!( + "machine {} {}", + d["machine"].as_str().unwrap_or("?"), + if d["paused"] == true { + "PAUSED" + } else { + "running" + } + ); + for r in d["repos"].as_array().into_iter().flatten() { + println!( + "{} [{}]", + r["path"].as_str().unwrap_or("?"), + r["phase"].as_str().unwrap_or("?") + ); + for w in r["worktrees"].as_array().into_iter().flatten() { + println!( + " {:<24} {}", + w["branch"].as_str().unwrap_or("(detached)"), + w["state"].as_str().unwrap_or("?") + ); + } + if let Some(e) = r["last_error"].as_str() { + println!(" error: {e}"); + } + } + } + DaemonCmd::Pause => { + ask(json!({"v": 1, "cmd": "pause"}))?; + println!("paused"); + } + DaemonCmd::Resume => { + ask(json!({"v": 1, "cmd": "resume"}))?; + println!("resumed"); + } + DaemonCmd::Sync { repo } => { + let repo = repo.as_ref().map(|p| p.display().to_string()); + ask(json!({"v": 1, "cmd": "sync", "repo": repo}))?; + println!("queued"); + } + DaemonCmd::Log { limit } => { + let d = ask(json!({"v": 1, "cmd": "log", "limit": limit}))?; + for e in d.as_array().into_iter().flatten() { + println!( + "{} {:<12} {} {}", + e["ts"], + e["kind"].as_str().unwrap_or("?"), + e["repo"].as_str().unwrap_or("-"), + e["msg"].as_str().unwrap_or("") + ); + } + } + } + Ok(()) +} + fn main() -> Result<()> { let cli = Cli::parse(); match &cli.cmd { + Cmd::Daemon { action } => daemon(action), Cmd::Status { path } => status(path), Cmd::Snapshot { path } => { let cfg = load_config(&cli.config)?; From 3f5ef285036110c78210d69f07037a90152c0b45 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 13:01:30 +0100 Subject: [PATCH 3/4] docs: document phase 2 daemon Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 7 ++-- docs/phase2.md | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) create mode 100644 docs/phase2.md diff --git a/CLAUDE.md b/CLAUDE.md index b377ac4..284ca5c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,21 +4,22 @@ Linux tool that keeps chosen git repos continuously in sync across machines, including uncommitted work, via snapshot refs (`refs/sync//`) on a primary remote. Planned as a Rust workspace (core, providers, daemon, CLI, Tauri GUI). Currently in -**Phase 0 done, Phase 1 implemented and validated against the real Gitea with two simulated machines (real two-PC run still pending)**: `grove-core` + `grove` CLI (`status`, `snapshot`, `add`, `sync`, `doctor`); daemon, GUI and providers do not exist yet. Do not start a +**Phase 0 done, Phase 1 implemented and validated against the real Gitea with two simulated machines (real two-PC run still pending)**: `grove-core` + `grove` CLI (`status`, `snapshot`, `add`, `sync`, `doctor`); daemon (`groved`, Phase 2) implemented (not yet run on the real two PCs); GUI and providers do not exist yet. Do not start a new phase before its predecessor's results are written to `docs/`. ## Commands - Check shell scripts: `for f in spikes/*.sh; do bash -n "$f"; done` - Throwaway Forgejo (dev only, Podman): `spikes/forgejo-up.sh`, then `spikes/phase0.sh` - Rust: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test` +- Daemon: `cargo run -p grove-daemon --bin groved -- --config PATH`; client `grove daemon status` ## Architecture -See `docs/` (`phase0-spike.md`, `phase1.md`, `DECISIONS.md`). Git is the storage layer; shell out to +See `docs/` (`phase0-spike.md`, `phase1.md`, `phase2.md`, `DECISIONS.md`). Git is the storage layer; shell out to system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the user's branch or index. ## Conventions -- Dependencies: serde+toml (config), clap+anyhow (CLI), approved. Ask before adding more. +- Dependencies: serde+toml (config), clap+anyhow (CLI), notify+serde_json (daemon), approved. Ask before adding more. - Everything in the repo is English. Open questions go to `docs/DECISIONS.md`. - Never destroy local work; divergence is surfaced, never auto-merged. diff --git a/docs/phase2.md b/docs/phase2.md new file mode 100644 index 0000000..cff2069 --- /dev/null +++ b/docs/phase2.md @@ -0,0 +1,89 @@ +# Phase 2: daemon + +`groved` (crate `grove-daemon`) is a per-user daemon. It adds no sync logic of its own: every pass +is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only decides *when*. + +## Behaviour + +- **Repos**: every directory `root/` or `root//` that has a `.bare` or `.git` + (dot-directories skipped). Rediscovered at every full pass, so new repos are picked up. +- **Watching**: inotify (crate `notify`), recursive per repo. Changes under `.git`, `.bare`, + `.grove-stage` and anything matching `sync.ignore_extra` (exact component name or `*suffix`) are + ignored. If a watch cannot be set (typically `ENOSPC`, raise `fs.inotify.max_user_watches`) it is + logged and the periodic pass still covers that repo. +- **Debounce**: each event pushes the repo's next pass to `now + snapshot_debounce_ms`. +- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply + snapshots, materialize/archive). Also what catches missed events. +- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass; + it finds nothing to do and ends the chain. +- **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at + 5 min, and are logged as `error`. `sync` over IPC clears the backoff. +- **Locks**: grove never takes the user's index (snapshots use a temp index) so git's own locks are + not contended; a git command that fails because the user holds a lock is just a failed pass that + is retried. +- **Pause**: `pause` stops all passes (events keep accumulating); `resume` runs a full pass. +- **Crash safety**: nothing durable lives in the daemon. Killing it at any point leaves the working + tree and index untouched; the next start rediscovers and resyncs (covered by a kill -9 test). + There is no signal handler: SIGTERM ends the process, which is safe for the same reason. + +## IPC (protocol version 1) + +Unix socket `$XDG_RUNTIME_DIR/grove/grove.sock` (directory mode 0700; falls back to the state dir). +Line-delimited JSON, one request per line: + +```json +{"v":1,"cmd":"status"} +{"v":1,"ok":true,"data":{"machine":"pca","paused":false,"repos":[{"path":"...","phase":"idle", + "last_sync":1790000000,"last_error":null,"failures":0, + "worktrees":[{"branch":"main","state":"synced"}]}]}} +``` + +| `cmd` | Extra fields | Result | +|---|---|---| +| `ping` | | `"pong"` | +| `status` | | machine, paused flag, repos with phase (`idle`/`pending`/`syncing`/`error`) and worktree states | +| `pause`, `resume` | | `{"paused": bool}` | +| `sync` | `repo` (optional path) | `"queued"` | +| `log` | `limit` (default 50) | recent activity events | +| `subscribe` | | `"subscribed"`, then a stream of `{"v":1,"event":{...}}` until the client closes | + +Errors: `{"v":1,"ok":false,"error":"..."}`. A different `v` is rejected. A second daemon on the same +socket is refused; a stale socket file left by a crash is replaced. + +## Activity log + +JSON lines in `/activity.jsonl` (rotated at 5 MiB to `.jsonl.1`), the last 500 events in +memory, and live via `subscribe`. Kinds: `start`, `stop`, `snapshot`, `fast_forward`, `applied`, +`declined`, `state` (worktree state changed), `materialized`, `archived`, `error`, `watch_error`, +`pause`, `resume`. + +## CLI + +`grove daemon status | pause | resume | sync [REPO] | log [--limit N]`. + +## Install (systemd user service) + +```bash +install -Dm755 target/release/groved ~/.local/bin/groved +install -Dm644 contrib/groved.service ~/.config/systemd/user/groved.service +systemctl --user daemon-reload +systemctl --user enable --now groved +journalctl --user -u groved -f +``` + +Socket activation was considered and not done: the daemon must run anyway to watch files. + +## Found by the daemon tests + +A worktree that had another machine's snapshot applied stayed `BehindDirty` forever once the author +committed and pushed that work. `receive` now adopts the upstream commit with a mixed reset when the +worktree's content is byte-identical to the upstream tree (`receive::adopt_if_identical`); any +other dirty worktree is still left alone. + +## Not done + +- GUI/tray (Phase 3), providers and wizards (Phase 4). +- Remote-change notifications (webhooks); only polling at `fetch_interval_s`. +- Config reload: restart the daemon after editing `config.toml`. +- Watching skips no heavy ignored directories (`node_modules`, `target`) at watch time; add them to + `sync.ignore_extra` to avoid triggering passes, and raise the inotify limit if needed. From 0e77dd26d90f92d6649a90b179bb17df82e10e9b Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 13:05:38 +0100 Subject: [PATCH 4/4] fix(daemon): address review findings Idle paused loop no longer spins, local snapshots continue during network backoff, debounce has a maximum wait, sync accepts non-canonical paths, removed repos are dropped, socket dir mode is enforced. adopt_if_identical now skips worktrees with staged changes. Co-Authored-By: Claude Sonnet 5.5 --- crates/grove-core/src/receive.rs | 4 ++ crates/grove-core/tests/sync.rs | 37 +++++++++++++++++ crates/grove-daemon/src/daemon.rs | 53 +++++++++++++++++++----- crates/grove-daemon/src/ipc.rs | 22 +++++++--- crates/grove-daemon/tests/daemon.rs | 62 +++++++++++++++++++++++++++++ docs/phase2.md | 22 ++++++++-- 6 files changed, 182 insertions(+), 18 deletions(-) diff --git a/crates/grove-core/src/receive.rs b/crates/grove-core/src/receive.rs index 8a43e8d..8c2bf4c 100644 --- a/crates/grove-core/src/receive.rs +++ b/crates/grove-core/src/receive.rs @@ -119,6 +119,10 @@ fn adopt_if_identical( stamp: &str, st: State, ) -> Result { + // Anything staged (partial `add -p`, intent-to-add) would be lost by the index reset: skip. + if g.probe(&["diff", "--cached", "--quiet"])?.is_none() { + return Ok(Received::Skipped(st)); + } let worktree_tree = crate::snapshot::worktree_tree(g.dir())?; let upstream_tree = g.run(&["rev-parse", "@{upstream}^{tree}"])?; if worktree_tree != upstream_tree { diff --git a/crates/grove-core/tests/sync.rs b/crates/grove-core/tests/sync.rs index 08207c4..132d73b 100644 --- a/crates/grove-core/tests/sync.rs +++ b/crates/grove-core/tests/sync.rs @@ -131,3 +131,40 @@ fn unreachable_remote_is_reported_but_local_snapshot_still_taken() { assert!(!r.worktrees[0].errors.is_empty(), "push failure surfaced"); assert_eq!(r.worktrees[0].state, State::Dirty); } + +#[test] +fn staged_changes_block_adoption_so_the_index_is_never_reset() { + let base = tmpdir("staged"); + let remote = base.join("r.git"); + Git::new(&base) + .run(&[ + "init", + "-q", + "--bare", + "-b", + "main", + remote.to_str().unwrap(), + ]) + .unwrap(); + let seed = init(&base.join("seed")); + seed.run(&["remote", "add", "origin", remote.to_str().unwrap()]) + .unwrap(); + commit(&seed, "a.txt", "1\n"); + seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap(); + let (ga, da) = clone(&base, &remote, "A"); + let (_gb, db) = clone(&base, &remote, "B"); + fs::write(da.join("a.txt"), "1\nwork\n").unwrap(); + sync_repo(&da, &opts("A", "t1")).unwrap(); + sync_repo(&db, &opts("B", "t2")).unwrap(); + // B stages an intermediate version, then its worktree matches what A will commit. + let gb = Git::new(&db); + fs::write(db.join("a.txt"), "1\nstaged\n").unwrap(); + gb.run(&["add", "a.txt"]).unwrap(); + fs::write(db.join("a.txt"), "1\nwork\n").unwrap(); + ga.run(&["add", "-A"]).unwrap(); + ga.run(&["commit", "-qm", "work"]).unwrap(); + ga.run(&["push", "-q"]).unwrap(); + let r = sync_repo(&db, &opts("B", "t3")).unwrap(); + assert_eq!(r.worktrees[0].state, State::BehindDirty); + assert_eq!(gb.run(&["show", ":a.txt"]).unwrap(), "1\nstaged"); +} diff --git a/crates/grove-daemon/src/daemon.rs b/crates/grove-daemon/src/daemon.rs index 91fb931..c80bdb7 100644 --- a/crates/grove-daemon/src/daemon.rs +++ b/crates/grove-daemon/src/daemon.rs @@ -233,6 +233,7 @@ impl Watch { fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec { let found = discover(root); let mut shared = ctx.shared.lock().unwrap(); + shared.repos.retain(|p, _| found.contains(p)); for r in &found { shared.repos.entry(r.clone()).or_default(); } @@ -254,6 +255,10 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { // due_at: when a repo should next be synced; backoff_until: earliest retry after failures. let mut due_at: HashMap = HashMap::new(); let mut backoff_until: HashMap = HashMap::new(); + // first_at: first unsynced event of a repo, so a constant stream of events cannot postpone + // its snapshot beyond `max_wait`. + let mut first_at: HashMap = HashMap::new(); + let max_wait = (debounce * 10).max(Duration::from_secs(5)); let mut next_full = Instant::now(); loop { @@ -264,12 +269,20 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { .chain([next_full]) .min() .unwrap_or(next_full); - let timeout = wake + let mut timeout = wake .saturating_duration_since(now) .min(Duration::from_secs(1)); + if ctx.shared.lock().unwrap().paused { + // Nothing is due while paused: only wait for commands, never spin on past deadlines. + timeout = Duration::from_secs(1); + } match rx.recv_timeout(timeout) { Ok(Msg::Changed(r)) => { - let at = Instant::now() + debounce; + let now = Instant::now(); + let first = *first_at.entry(r.clone()).or_insert(now); + let at = (now + debounce).min(first + max_wait); + // An earlier deadline (e.g. an immediate `sync`) is never pushed back. + let at = due_at.get(&r).map_or(at, |old| at.min(*old)); due_at.insert(r.clone(), at); if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(&r) && s.phase == "idle" @@ -293,7 +306,9 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { } let now = Instant::now(); if now >= next_full { - for r in rescan(&root, &mut watch, &ctx) { + let found = rescan(&root, &mut watch, &ctx); + due_at.retain(|r, _| found.contains(r)); + for r in found { due_at.insert(r, now); } next_full = now + fetch_every; @@ -305,12 +320,19 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { .collect(); due.sort(); for r in due { - if let Some(until) = backoff_until.get(&r).filter(|u| **u > now) { - due_at.insert(r, *until); + if !ctx.shared.lock().unwrap().repos.contains_key(&r) { + due_at.remove(&r); continue; } due_at.remove(&r); - let failures = pass(&r, &cfg, &st, materialize, &ctx); + first_at.remove(&r); + // While backing off after a failure, still snapshot local work (no network needed); + // the network is retried at the first pass after the backoff expires. + let offline = backoff_until.get(&r).is_some_and(|u| *u > now); + let failures = pass(&r, &cfg, &st, materialize, offline, &ctx); + if offline { + continue; + } if failures == 0 { backoff_until.remove(&r); } else { @@ -327,14 +349,21 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { } /// One sync pass for `repo`; returns the number of consecutive failures (0 = success). -fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx) -> u32 { +fn pass( + repo: &Path, + cfg: &Config, + st: &Settings, + materialize: bool, + offline: bool, + ctx: &Ctx, +) -> u32 { let name = repo.display().to_string(); set_phase(ctx, repo, "syncing"); let opts = Options { machine: cfg.machine.name.clone(), stamp: stamp(), remote: st.remote.clone(), - offline: false, + offline, materialize, }; let result = sync_repo(repo, &opts); @@ -394,7 +423,13 @@ fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx) } } } - if errors.is_empty() { + if offline { + // A snapshot-only pass during backoff changes neither the failure count nor the phase. + status.phase = if status.failures > 0 { "error" } else { "idle" }; + if !errors.is_empty() { + ctx.activity.log("error", Some(&name), errors.join("; ")); + } + } else if errors.is_empty() { status.phase = "idle"; status.failures = 0; status.last_error = None; diff --git a/crates/grove-daemon/src/ipc.rs b/crates/grove-daemon/src/ipc.rs index df75143..c5350d3 100644 --- a/crates/grove-daemon/src/ipc.rs +++ b/crates/grove-daemon/src/ipc.rs @@ -49,6 +49,8 @@ pub fn serve(socket: &Path, ctx: Ctx, stop: Arc) -> std::io::Result< .recursive(true) .mode(0o700) .create(dir)?; + // The mode above only applies to a directory we create: enforce it on an existing one. + std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; } if socket.exists() { if UnixStream::connect(socket).is_ok() { @@ -187,11 +189,21 @@ fn handle(req: &Request, ctx: &Ctx) -> Value { } "sync" => { let target = req.repo.as_ref().map(PathBuf::from); - if let Some(t) = &target - && !ctx.shared.lock().unwrap().repos.contains_key(t) - { - return err("unknown repo"); - } + // Match by canonical path so `.`, relative and symlinked paths work. + let target = match target { + None => None, + Some(t) => { + let want = std::fs::canonicalize(&t).unwrap_or(t); + let shared = ctx.shared.lock().unwrap(); + let found = shared.repos.keys().find(|k| { + std::fs::canonicalize(k).unwrap_or_else(|_| (*k).clone()) == want + }); + match found { + Some(k) => Some(k.clone()), + None => return err("unknown repo"), + } + } + }; let _ = ctx.tx.send(Msg::SyncNow(target)); ok(json!("queued")) } diff --git a/crates/grove-daemon/tests/daemon.rs b/crates/grove-daemon/tests/daemon.rs index 85ee586..a4cddf2 100644 --- a/crates/grove-daemon/tests/daemon.rs +++ b/crates/grove-daemon/tests/daemon.rs @@ -307,3 +307,65 @@ fn work_in_progress_then_committed_on_a_leaves_b_clean() { a.shutdown(); b.shutdown(); } + +fn cpu_ticks(pid: u32) -> u64 { + let stat = fs::read_to_string(format!("/proc/{pid}/stat")).unwrap(); + let rest = stat.rsplit_once(')').unwrap().1; + let f: Vec<&str> = rest.split_whitespace().collect(); + f[11].parse::().unwrap() + f[12].parse::().unwrap() // utime + stime +} + +#[test] +fn paused_daemon_does_not_spin() { + let w = world("spin", &["pca"]); + let cfg_path = w.base.join("config.toml"); + fs::write( + &cfg_path, + format!( + "[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n", + w.base.join("pca").display() + ), + ) + .unwrap(); + let runtime = w.base.join("run"); + fs::create_dir_all(&runtime).unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_groved")) + .arg("--config") + .arg(&cfg_path) + .env("XDG_RUNTIME_DIR", &runtime) + .env("XDG_STATE_HOME", w.base.join("state")) + .spawn() + .unwrap(); + let sock = runtime.join("grove/grove.sock"); + wait_until("daemon up", 10, || { + ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).is_ok() + }); + ipc::request(&sock, &json!({"v":1,"cmd":"pause"})).unwrap(); + std::thread::sleep(Duration::from_millis(1500)); // let any in-flight pass finish + let before = cpu_ticks(child.id()); + std::thread::sleep(Duration::from_secs(3)); // well past several fetch intervals + let used = cpu_ticks(child.id()) - before; + child.kill().unwrap(); + child.wait().unwrap(); + assert!(used < 30, "paused daemon burned {used} ticks of CPU in 3 s"); +} + +#[test] +fn sync_accepts_a_non_canonical_repo_path_and_unknown_repos_are_rejected() { + let w = world("path", &["pca"]); + let st = settings(&w, "pca"); + let sock = st.socket.clone(); + let d = Daemon::start(config(&w, "pca", 200, 60), st).unwrap(); + let repo = w.base.join("pca/repo"); + wait_until("repo listed", 10, || { + ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"]["repos"] + .as_array() + .is_some_and(|r| r.len() == 1) + }); + let odd = format!("{}/../repo/.", repo.display()); + let ok = ipc::request(&sock, &json!({"v":1,"cmd":"sync","repo":odd})).unwrap(); + assert_eq!(ok["ok"], true, "{ok}"); + let bad = ipc::request(&sock, &json!({"v":1,"cmd":"sync","repo":"/nonexistent"})).unwrap(); + assert_eq!(bad["ok"], false); + d.shutdown(); +} diff --git a/docs/phase2.md b/docs/phase2.md index cff2069..654f186 100644 --- a/docs/phase2.md +++ b/docs/phase2.md @@ -11,17 +11,21 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de `.grove-stage` and anything matching `sync.ignore_extra` (exact component name or `*suffix`) are ignored. If a watch cannot be set (typically `ENOSPC`, raise `fs.inotify.max_user_watches`) it is logged and the periodic pass still covers that repo. -- **Debounce**: each event pushes the repo's next pass to `now + snapshot_debounce_ms`. +- **Debounce**: each event pushes the repo's next pass to `now + snapshot_debounce_ms`, but never + later than `max(10 x debounce, 5 s)` after the first unsynced event, so a constantly written file + cannot starve snapshots. - **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply snapshots, materialize/archive). Also what catches missed events. - **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass; it finds nothing to do and ends the chain. - **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at - 5 min, and are logged as `error`. `sync` over IPC clears the backoff. + 5 min, and are logged as `error`. `sync` over IPC clears the backoff. While backing off, changes + are still snapshotted locally (an offline pass); only the network is retried after the backoff. - **Locks**: grove never takes the user's index (snapshots use a temp index) so git's own locks are not contended; a git command that fails because the user holds a lock is just a failed pass that is retried. -- **Pause**: `pause` stops all passes (events keep accumulating); `resume` runs a full pass. +- **Pause**: `pause` stops all passes (events keep accumulating, the loop idles at 1 s ticks); + `resume` runs a full pass. - **Crash safety**: nothing durable lives in the daemon. Killing it at any point leaves the working tree and index untouched; the next start rediscovers and resyncs (covered by a kill -9 test). There is no signal handler: SIGTERM ends the process, which is safe for the same reason. @@ -73,15 +77,25 @@ journalctl --user -u groved -f Socket activation was considered and not done: the daemon must run anyway to watch files. +## Latency + +Measured on the real Gitea with default settings (2 s debounce, 60 s fetch): an edit on A showed up on +B after 58 s, and a commit pushed on A left B clean at the new commit after 60 s. Worst case is +`debounce + fetch_interval_s + pass time`; lower `fetch_interval_s` for faster convergence. + ## Found by the daemon tests A worktree that had another machine's snapshot applied stayed `BehindDirty` forever once the author committed and pushed that work. `receive` now adopts the upstream commit with a mixed reset when the worktree's content is byte-identical to the upstream tree (`receive::adopt_if_identical`); any -other dirty worktree is still left alone. +other dirty worktree is still left alone, including one with staged changes (the reset would +discard the staged version). ## Not done +- `Daemon::shutdown` finishes the queued passes first, and idle client connections are not joined. + `groved` never calls it (no signal handler), so this only matters for tests and embedding. +- Peer-credential check on the socket: access control is the 0700 directory only. - GUI/tray (Phase 3), providers and wizards (Phase 4). - Remote-change notifications (webhooks); only polling at `fetch_interval_s`. - Config reload: restart the daemon after editing `config.toml`.