Milestone 1: sync engine and lunesync CLI

Rust workspace with core (watch, settle, save, sync over a plain Git
remote, keep-both on same-line edits, offline queueing, tidy) and the
lunesync CLI (device, add, run, service, status, checkpoint, tidy,
history). Tests cover byte-exact round trips, keep-both, offline
catch-up and adopting an existing vault.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 23:11:24 +07:00
commit 25b8be5bbd
18 changed files with 3601 additions and 0 deletions

10
cli/Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "lunesync"
version = "0.1.0"
edition = "2024"
[dependencies]
anyhow = "1.0.104"
chrono = "0.4.45"
clap = { version = "4.6.7", features = ["derive"] }
lune-core = { version = "0.1.0", path = "../core" }

333
cli/src/main.rs Normal file
View File

@@ -0,0 +1,333 @@
mod service;
use anyhow::{Context, Result, bail};
use chrono::{Local, TimeZone};
use clap::{Parser, Subcommand, ValueEnum};
use lune_core::config::{Config, VaultConfig};
use lune_core::runner::{self, Timing};
use lune_core::state::{self, SyncState};
use lune_core::tidy::{self, Keep};
use lune_core::vault::{self, Added, Vault};
use lune_core::remote;
use std::path::{Path, PathBuf};
#[derive(Parser)]
#[command(name = "lunesync", version, about = "Keeps every copy of your vaults in sync.")]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Show or set this device's label (e.g. Codex, Hermes)
Device {
#[command(subcommand)]
action: Option<DeviceCmd>,
},
/// Start syncing a folder: downloads into an empty folder, adopts one that already has notes
Add {
name: String,
folder: PathBuf,
#[arg(long)]
remote: String,
},
/// Keep every vault in sync, in the foreground
Run,
/// Keep `lunesync run` going in the background (launchd / systemd)
Service {
#[command(subcommand)]
action: ServiceCmd,
},
/// How each vault is doing
Status { vault: Option<String> },
/// Save a named point in history right now and share it
Checkpoint {
message: String,
#[arg(long)]
vault: Option<String>,
},
/// List notes where both versions were kept, or pick one
Tidy {
#[command(subcommand)]
action: Option<TidyCmd>,
#[arg(long)]
vault: Option<String>,
},
/// Recent history entries and which device made them
History {
#[arg(long)]
vault: Option<String>,
#[arg(short = 'n', default_value_t = 15)]
count: usize,
},
}
#[derive(Subcommand)]
enum DeviceCmd {
/// Set the label shown on everything this device shares
Name { label: String },
}
#[derive(Subcommand)]
enum ServiceCmd {
/// Install and start the background service
Install {
/// Only show what would be installed
#[arg(long)]
print: bool,
},
/// Stop and remove the background service
Uninstall,
}
#[derive(Subcommand)]
enum TidyCmd {
/// Keep one version (mine = this device's), or both as separate notes
Keep { choice: KeepArg, file: PathBuf },
}
#[derive(Clone, Copy, ValueEnum)]
enum KeepArg {
Mine,
Theirs,
Both,
}
fn main() {
if let Err(e) = run_cli(Cli::parse()) {
eprintln!("lunesync: {e:#}");
std::process::exit(1);
}
}
fn run_cli(cli: Cli) -> Result<()> {
let mut config = Config::load()?;
let cwd = std::env::current_dir()?;
match cli.command {
Command::Device { action: None } => println!("This device is \"{}\".", config.device_label()),
Command::Device { action: Some(DeviceCmd::Name { label }) } => {
let label = label.trim().to_string();
if label.is_empty() {
bail!("the label can't be empty");
}
config.device_name = Some(label.clone());
config.save()?;
println!("This device is now \"{label}\". Everything it shares will carry that name.");
}
Command::Add { name, folder, remote } => add(&mut config, &name, &folder, &remote)?,
Command::Run => run(&config)?,
Command::Service { action: ServiceCmd::Install { print } } => service::install(print)?,
Command::Service { action: ServiceCmd::Uninstall } => service::uninstall()?,
Command::Status { vault } => {
let vaults: Vec<&VaultConfig> = match vault {
Some(n) => vec![config.find(&n).with_context(|| format!("no vault named \"{n}\""))?],
None => config.vaults.iter().collect(),
};
if vaults.is_empty() {
println!("No vaults yet. Add one with `lunesync add <name> <folder> --remote <url>`.");
}
println!("Device: {}", config.device_label());
for v in vaults {
print_status(v, &config.device_label());
}
}
Command::Checkpoint { message, vault } => {
let cfg = config.pick(vault.as_deref(), &cwd)?;
let v = Vault::open(cfg, &config.device_label())?;
let _op = state::op_lock(&v.git_dir)?;
v.checkpoint(&message)?;
println!("Checkpoint \"{message}\" saved in {}.", v.name);
share_now(&v);
}
Command::Tidy { action: None, vault } => {
let list: Vec<&VaultConfig> = match vault {
Some(n) => vec![config.pick(Some(&n), &cwd)?],
None => config.vaults.iter().collect(),
};
let mut any = false;
for cfg in list {
let v = Vault::open(cfg, &config.device_label())?;
for k in tidy::list(&v)? {
if !any {
println!("Notes changed in two places (both versions kept):");
}
any = true;
println!(" {:<12} {} ← {}", v.name, k.note, k.copy);
}
}
if any {
println!("\nPick one with `lunesync tidy keep mine|theirs|both <file>` (mine = this device's version).");
} else {
println!("Nothing to tidy.");
}
}
Command::Tidy { action: Some(TidyCmd::Keep { choice, file }), vault } => {
let (cfg, rel) = locate(&config, vault.as_deref(), &cwd, &file)?;
let v = Vault::open(cfg, &config.device_label())?;
let _op = state::op_lock(&v.git_dir)?;
let choice = match choice {
KeepArg::Mine => Keep::Mine,
KeepArg::Theirs => Keep::Theirs,
KeepArg::Both => Keep::Both,
};
match tidy::keep(&v, &rel, choice)? {
Some(saved) => println!("{}.", saved.message),
None => println!("Nothing changed."),
}
share_now(&v);
}
Command::History { vault, count } => {
let cfg = config.pick(vault.as_deref(), &cwd)?;
let v = Vault::open(cfg, &config.device_label())?;
let Some(head) = v.head_commit()? else {
println!("No history yet.");
return Ok(());
};
let repo = v.repo();
let mut walk = repo.revwalk()?;
walk.set_sorting(lune_core::git2::Sort::TIME)?;
walk.push(head.id())?;
for id in walk.take(count) {
let c = repo.find_commit(id?)?;
let when = Local.timestamp_opt(c.time().seconds(), 0).single().map(|t| t.format("%Y-%m-%d %H:%M").to_string());
println!(
"{} {:<10} {}",
when.unwrap_or_default(),
c.author().name().unwrap_or("?"),
c.summary().ok().flatten().unwrap_or("")
);
}
}
}
Ok(())
}
fn add(config: &mut Config, name: &str, folder: &Path, remote: &str) -> Result<()> {
if config.find(name).is_some() {
bail!("there's already a vault named \"{name}\"");
}
let folder = if folder.is_absolute() { folder.to_path_buf() } else { std::env::current_dir()?.join(folder) };
let label = config.device_label();
let (cfg, added, sync_error) = vault::add(name, &folder, remote, &label)?;
match added {
Added::Downloaded(n) => println!("Downloaded {name}: {n} files in {}.", cfg.path.display()),
Added::Adopted(n) => println!("Adopted {name}: {n} files in {}, nothing moved or rewritten.", cfg.path.display()),
Added::StartedEmpty => println!("Started {name} in {} (the remote is empty).", cfg.path.display()),
}
if let Some(e) = sync_error {
println!("Not shared yet: {e}. `lunesync run` will keep trying.");
}
config.vaults.push(cfg);
config.save()?;
println!("Next: `lunesync run` to keep it in sync (or `lunesync service install` to run it in the background).");
Ok(())
}
fn run(config: &Config) -> Result<()> {
if config.vaults.is_empty() {
bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>`");
}
let label = config.device_label();
let poll = config.poll_interval();
let log = |vault: &str, msg: &str| println!("{} {vault:<10} {msg}", Local::now().format("%H:%M:%S"));
std::thread::scope(|s| {
for cfg in &config.vaults {
let label = &label;
s.spawn(move || {
loop {
match runner::run(cfg, label, poll, Timing::default(), &log) {
Ok(()) => return,
Err(e) if format!("{e}").contains("already being synced") => {
log(&cfg.name, &format!("{e:#}"));
return;
}
Err(e) => {
log(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
std::thread::sleep(std::time::Duration::from_secs(30));
}
}
}
});
}
});
Ok(())
}
/// After a one-off command, try to share right away; the runner picks it up otherwise.
fn share_now(v: &Vault) {
match v.sync() {
Ok(r) if r.waiting_for_local_edits => println!("Will share once your current edits settle."),
Ok(_) => {
println!("Shared.");
let mut st = SyncState::load(&v.git_dir);
st.last_synced = Some(chrono::Utc::now().timestamp());
st.last_attempt = st.last_synced;
st.last_error = None;
let _ = st.save(&v.git_dir);
}
Err(e) => println!("Not shared yet ({}); it will go out when the remote is reachable.", remote::describe_error(&e)),
}
}
fn print_status(cfg: &VaultConfig, label: &str) {
println!("\n{} — {}", cfg.name, cfg.path.display());
let v = match Vault::open(cfg, label) {
Ok(v) => v,
Err(e) => {
println!(" Can't open: {e:#}");
return;
}
};
let st = SyncState::load(&v.git_dir);
let waiting = v.waiting_files().unwrap_or(0);
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
let headline = match &st.last_error {
Some(e) if e.starts_with("offline") => format!("Offline · waiting to sync · {changes}"),
Some(e) => format!("Can't sync: {e}{}", if waiting > 0 { format!(" · {changes} waiting") } else { String::new() }),
None if waiting > 0 => format!("Waiting to sync · {changes}"),
None if st.last_synced.is_some() => format!("Synced {}", ago(st.last_synced.unwrap())),
None => "Not synced yet".to_string(),
};
println!(" {headline}");
if let Some(t) = st.last_synced {
println!(" Last sync: {} ({})", Local.timestamp_opt(t, 0).unwrap().format("%Y-%m-%d %H:%M:%S"), ago(t));
}
let to_tidy = tidy::list(&v).map(|l| l.len()).unwrap_or(0);
if to_tidy > 0 {
println!(" {to_tidy} note{} to tidy — see `lunesync tidy`", if to_tidy == 1 { "" } else { "s" });
}
if !st.case_clashes.is_empty() {
println!(" Names differing only by case: {}", st.case_clashes.join(", "));
}
if !state::is_running(&v.git_dir) {
println!(" Not running — start `lunesync run` or `lunesync service install`");
}
}
fn ago(unix: i64) -> String {
let secs = (chrono::Utc::now().timestamp() - unix).max(0);
match secs {
0..=59 => "just now".into(),
60..=3599 => format!("{} min ago", secs / 60),
3600..=86399 => format!("{} h ago", secs / 3600),
_ => format!("{} days ago", secs / 86400),
}
}
/// Finds the vault and vault-relative path for a file given as absolute, relative to here, or relative to the vault.
fn locate<'a>(config: &'a Config, vault: Option<&str>, cwd: &Path, file: &Path) -> Result<(&'a VaultConfig, String)> {
let abs = if file.is_absolute() { file.to_path_buf() } else { cwd.join(file) };
let abs = match (abs.parent().and_then(|p| std::fs::canonicalize(p).ok()), abs.file_name()) {
(Some(dir), Some(name)) => dir.join(name),
_ => abs,
};
if let Some(cfg) = vault.map_or_else(|| config.containing(&abs), |n| config.find(n))
&& let Ok(root) = std::fs::canonicalize(&cfg.path)
&& let Ok(rel) = abs.strip_prefix(&root)
{
return Ok((cfg, rel.to_string_lossy().replace('\\', "/")));
}
let cfg = config.pick(vault, cwd)?;
Ok((cfg, file.to_string_lossy().replace('\\', "/")))
}

121
cli/src/service.rs Normal file
View File

@@ -0,0 +1,121 @@
//! `lunesync service install|uninstall`: keep `lunesync run` alive with launchd (macOS) or systemd (Linux).
use anyhow::{Context, Result, bail};
use std::path::PathBuf;
use std::process::Command;
const LABEL: &str = "com.lune.lunesync";
fn home() -> Result<PathBuf> {
std::env::var_os("HOME").map(PathBuf::from).context("can't find your home folder")
}
/// Environment the service needs to find the same config as this shell. SSH keys come from the
/// login agent (macOS) or ~/.ssh key files, not from this shell's possibly forwarded agent.
fn env_vars() -> Vec<(&'static str, String)> {
["LUNE_HOME"]
.into_iter()
.filter_map(|k| std::env::var(k).ok().map(|v| (k, v)))
.collect()
}
fn unit() -> Result<(PathBuf, String)> {
let exe = std::env::current_exe()?.canonicalize()?;
let exe = exe.display();
if cfg!(target_os = "macos") {
let path = home()?.join("Library/LaunchAgents").join(format!("{LABEL}.plist"));
let log = home()?.join("Library/Logs/lunesync.log");
let env: String = env_vars()
.iter()
.map(|(k, v)| format!(" <key>{k}</key><string>{}</string>\n", xml_escape(v)))
.collect();
let plist = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>{LABEL}</string>
<key>ProgramArguments</key><array><string>{exe}</string><string>run</string></array>
<key>EnvironmentVariables</key>
<dict>
{env} </dict>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>{log}</string>
<key>StandardErrorPath</key><string>{log}</string>
</dict>
</plist>
"#,
log = log.display()
);
Ok((path, plist))
} else if cfg!(target_os = "linux") {
let path = home()?.join(".config/systemd/user/lunesync.service");
let env: String = env_vars().iter().map(|(k, v)| format!("Environment=\"{k}={v}\"\n")).collect();
let service = format!(
"[Unit]\nDescription=Lune vault sync\nAfter=network-online.target\n\n\
[Service]\nExecStart={exe} run\n{env}Restart=always\nRestartSec=10\n\n\
[Install]\nWantedBy=default.target\n"
);
Ok((path, service))
} else {
bail!("background service isn't supported on this system yet — use `lunesync run`")
}
}
pub fn install(print: bool) -> Result<()> {
let (path, text) = unit()?;
if print {
println!("Would write {}:\n\n{text}", path.display());
return Ok(());
}
std::fs::create_dir_all(path.parent().unwrap())?;
std::fs::write(&path, text)?;
if cfg!(target_os = "macos") {
let domain = format!("gui/{}", uid()?);
let _ = Command::new("launchctl").args(["bootout", &domain, &path.to_string_lossy()]).output();
sh("launchctl", &["bootstrap", &domain, &path.to_string_lossy()])?;
println!("Running in the background. Log: ~/Library/Logs/lunesync.log");
} else {
sh("systemctl", &["--user", "daemon-reload"])?;
sh("systemctl", &["--user", "enable", "--now", "lunesync.service"])?;
let user = std::env::var("USER").unwrap_or_default();
if Command::new("loginctl").args(["enable-linger", &user]).status().map(|s| !s.success()).unwrap_or(true) {
println!("Tip: run `sudo loginctl enable-linger {user}` so it keeps running after you log out.");
}
println!("Running in the background. Log: journalctl --user -u lunesync -f");
}
Ok(())
}
pub fn uninstall() -> Result<()> {
let (path, _) = unit()?;
if cfg!(target_os = "macos") {
let domain = format!("gui/{}", uid()?);
let _ = Command::new("launchctl").args(["bootout", &domain, &path.to_string_lossy()]).output();
} else {
let _ = Command::new("systemctl").args(["--user", "disable", "--now", "lunesync.service"]).output();
}
if path.exists() {
std::fs::remove_file(&path)?;
}
println!("Background service removed. Your vault folders are untouched.");
Ok(())
}
fn uid() -> Result<String> {
let out = Command::new("id").arg("-u").output()?;
Ok(String::from_utf8(out.stdout)?.trim().to_string())
}
fn sh(cmd: &str, args: &[&str]) -> Result<()> {
let out = Command::new(cmd).args(args).output().with_context(|| format!("can't run {cmd}"))?;
if !out.status.success() {
bail!("{cmd} {} failed: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim());
}
Ok(())
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}