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

551
core/src/vault.rs Normal file
View File

@@ -0,0 +1,551 @@
//! One vault on disk: setting it up, saving bursts of edits as history entries, and syncing with the remote.
use crate::config::VaultConfig;
use crate::names;
use crate::remote;
use crate::state;
use anyhow::{Context, Result, bail};
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
use git2::{
AutotagOption, Commit, ConfigLevel, Direction, ErrorCode, FetchOptions, FileMode, IndexAddOption,
IndexEntry, Oid, PushOptions, Repository, RepositoryInitOptions, Signature, Sort, StatusOptions, TreeWalkMode,
TreeWalkResult,
};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
/// Ignored on every device: per-device Obsidian state, trash and OS junk.
const DEFAULT_IGNORES: &str = "\
# lune defaults
/.obsidian/workspace*.json
/.obsidian/cache
/.trash/
.DS_Store
Thumbs.db
";
/// Bytes in = bytes out: no line-ending, encoding or filter rewriting, whatever the vault's own attributes say.
const BYTE_EXACT_ATTRIBUTES: &str = "* -text -eol -ident -filter -working-tree-encoding\n";
pub struct Vault {
pub name: String,
pub root: PathBuf,
pub git_dir: PathBuf,
pub branch: String,
pub label: String,
repo: Repository,
}
/// A burst of edits saved as one history entry.
#[derive(Debug)]
pub struct Saved {
pub id: Oid,
pub message: String,
pub files: Vec<String>,
}
/// What one sync round did, in terms the run log can print.
#[derive(Debug, Default)]
pub struct SyncReport {
/// Files that changed locally because of others' edits.
pub received: Vec<String>,
/// Device labels those edits came from.
pub from: BTreeSet<String>,
/// (note, copy saved beside it) for every same-lines clash.
pub kept_both: Vec<(String, String)>,
/// (old path, new path) for files renamed because their names differed only by case.
pub case_renamed: Vec<(String, String)>,
/// Number of local history entries that went out.
pub shared: usize,
/// Incoming changes touch a file that is still being edited here; they'll land after it settles.
pub waiting_for_local_edits: bool,
}
impl Vault {
pub fn open(cfg: &VaultConfig, label: &str) -> Result<Vault> {
let repo = Repository::open(&cfg.path)
.with_context(|| format!("can't open the vault folder {}", cfg.path.display()))?;
let root = repo.workdir().context("vault has no working folder")?.to_path_buf();
let root = std::fs::canonicalize(&root).unwrap_or(root);
Ok(Vault {
name: cfg.name.clone(),
git_dir: repo.path().to_path_buf(),
root,
branch: cfg.branch.clone(),
label: label.to_string(),
repo,
})
}
pub fn repo(&self) -> &Repository {
&self.repo
}
fn branch_ref(&self) -> String {
format!("refs/heads/{}", self.branch)
}
fn remote_ref(&self) -> String {
format!("refs/remotes/origin/{}", self.branch)
}
fn signature(&self) -> Result<Signature<'static>> {
let slug: String = self
.label
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
.collect();
Ok(Signature::now(&self.label, &format!("{slug}@lune.device"))?)
}
pub fn head_commit(&self) -> Result<Option<Commit<'_>>> {
match self.repo.find_reference(&self.branch_ref()) {
Ok(r) => Ok(Some(r.peel_to_commit()?)),
Err(e) if e.code() == ErrorCode::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn remote_commit(&self) -> Result<Option<Commit<'_>>> {
match self.repo.find_reference(&self.remote_ref()) {
Ok(r) => Ok(Some(r.peel_to_commit()?)),
Err(e) if e.code() == ErrorCode::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn is_ignored(&self, rel: &Path) -> bool {
self.repo.is_path_ignored(rel).unwrap_or(false)
}
/// Saves every changed file as one history entry, except paths in `skip` (still being written).
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
let mut index = self.repo.index()?;
index.read(false)?;
let mut filter = |p: &Path, _: &[u8]| -> i32 { if skip.contains(&names::slash_path(p)) { 1 } else { 0 } };
index.add_all(["*"], IndexAddOption::DEFAULT, Some(&mut filter))?;
index.update_all(["*"], Some(&mut filter))?;
index.write()?;
let tree = self.repo.find_tree(index.write_tree()?)?;
let parent = self.head_commit()?;
let old_tree = parent.as_ref().map(|c| c.tree()).transpose()?;
let diff = self.repo.diff_tree_to_tree(old_tree.as_ref(), Some(&tree), None)?;
let files: Vec<String> = diff
.deltas()
.filter_map(|d| d.new_file().path().or(d.old_file().path()).map(names::slash_path))
.collect();
if files.is_empty() {
return Ok(None);
}
let message = match message {
Some(m) => m.to_string(),
None => describe_files(&diff),
};
let sig = self.signature()?;
let parents: Vec<&Commit> = parent.iter().collect();
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
Ok(Some(Saved { id, message, files }))
}
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
pub fn checkpoint(&self, message: &str) -> Result<Oid> {
if let Some(saved) = self.save_changes(Some(message), &HashSet::new())? {
return Ok(saved.id);
}
let head = self.head_commit()?.context("the vault is empty — nothing to checkpoint yet")?;
let sig = self.signature()?;
Ok(self.repo.commit(Some(&self.branch_ref()), &sig, &sig, message, &head.tree()?, &[&head])?)
}
pub fn fetch(&self) -> Result<()> {
let mut remote = self.repo.find_remote("origin")?;
let mut opts = FetchOptions::new();
opts.remote_callbacks(remote::callbacks());
opts.download_tags(AutotagOption::None);
let spec = format!("+{}:{}", self.branch_ref(), self.remote_ref());
remote.fetch(&[spec], Some(&mut opts), None)?;
Ok(())
}
/// Pushes local history. Returns false if the remote moved on meanwhile (fetch and try again).
fn push(&self) -> Result<bool> {
let mut remote = self.repo.find_remote("origin")?;
let rejected = RefCell::new(None::<String>);
let mut cb = remote::callbacks();
cb.push_update_reference(|_, status| {
if let Some(s) = status {
*rejected.borrow_mut() = Some(s.to_string());
}
Ok(())
});
let mut opts = PushOptions::new();
opts.remote_callbacks(cb);
let spec = format!("{0}:{0}", self.branch_ref());
if let Err(e) = remote.push(&[spec], Some(&mut opts)) {
if e.code() == ErrorCode::NotFastForward || e.message().contains("fast") {
return Ok(false);
}
return Err(e.into());
}
drop(opts);
if rejected.borrow().is_some() {
return Ok(false);
}
if let Some(head) = self.head_commit()? {
self.repo.reference(&self.remote_ref(), head.id(), true, "lune: shared")?;
}
Ok(true)
}
/// One sync round: fetch, combine, write the result to disk, share local history.
pub fn sync(&self) -> Result<SyncReport> {
let mut report = SyncReport::default();
for _ in 0..3 {
self.fetch()?;
let local = self.head_commit()?;
let incoming = self.remote_commit()?;
let target = match (&local, &incoming) {
(_, None) => None,
(None, Some(r)) => Some(r.id()),
(Some(l), Some(r)) if l.id() == r.id() => None,
(Some(l), Some(r)) => {
let (ahead, behind) = self.repo.graph_ahead_behind(l.id(), r.id())?;
match (ahead, behind) {
(_, 0) => None,
(0, _) => Some(r.id()),
_ => Some(self.combine(l, r, &mut report)?),
}
}
};
if let Some(target) = target {
let target = self.fix_case_clashes(target, &mut report)?;
let incoming = incoming.as_ref().unwrap();
self.note_incoming(local.as_ref(), incoming, target, &mut report)?;
match self.move_to(target) {
Ok(()) => {}
Err(e) if e.code() == ErrorCode::Conflict => {
report.waiting_for_local_edits = true;
return Ok(report);
}
Err(e) => return Err(e.into()),
}
}
let Some(local) = self.head_commit()? else { return Ok(report) };
let ahead = match self.remote_commit()? {
Some(r) if r.id() == local.id() => 0,
Some(r) => self.repo.graph_ahead_behind(local.id(), r.id())?.0,
None => 1,
};
if ahead == 0 {
return Ok(report);
}
if self.push()? {
report.shared += ahead;
return Ok(report);
}
}
bail!("the remote kept changing while sharing; will try again shortly")
}
/// Combines two lines of history. Same-lines clashes keep both: incoming in place, ours beside it (S4).
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
let mut index = self.repo.merge_commits(local, incoming, None)?;
if index.has_conflicts() {
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
for c in conflicts {
for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() {
let _ = index.conflict_remove(&names::bytes_path(&e.path));
}
match (c.our, c.their) {
(Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => {
let note = String::from_utf8_lossy(&theirs.path).into_owned();
let copy = (1..)
.map(|n| names::copy_name(&note, &self.label, n))
.find(|p| index.get_path(Path::new(p), 0).is_none())
.unwrap();
index.add(&stage0(&theirs, None))?;
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
report.kept_both.push((note, copy));
}
// Different paths, or one side removed the note: keep whatever still exists.
(ours, theirs) => {
for e in [ours, theirs].into_iter().flatten() {
index.add(&stage0(&e, None))?;
}
}
}
}
}
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let from = incoming.author().name().unwrap_or("another device").to_string();
let mut message = format!("Combined changes from {from}");
if !report.kept_both.is_empty() {
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
}
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
}
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
/// nothing is overwritten; everywhere, report them.
fn fix_case_clashes(&self, target: Oid, report: &mut SyncReport) -> Result<Oid> {
let commit = self.repo.find_commit(target)?;
let tree = commit.tree()?;
let mut files: Vec<(String, Oid, i32)> = vec![];
tree.walk(TreeWalkMode::PreOrder, |dir, entry| {
if entry.kind() == Some(git2::ObjectType::Blob) {
files.push((format!("{dir}{}", entry.name().unwrap_or("")), entry.id(), entry.filemode()));
}
TreeWalkResult::Ok
})?;
let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (i, (p, _, _)) in files.iter().enumerate() {
groups.entry(p.to_lowercase()).or_default().push(i);
}
let clashes: Vec<Vec<usize>> = groups.into_values().filter(|g| g.len() > 1).collect();
if clashes.is_empty() {
return Ok(target);
}
let ignorecase = self.repo.config()?.get_bool("core.ignorecase").unwrap_or(false);
let mut st = state::SyncState::load(&self.git_dir);
st.case_clashes = clashes.iter().flatten().map(|&i| files[i].0.clone()).collect();
st.save(&self.git_dir)?;
if !ignorecase {
return Ok(target);
}
let mut taken: HashSet<String> = files.iter().map(|f| f.0.to_lowercase()).collect();
let mut update = TreeUpdateBuilder::new();
for group in clashes {
for &i in &group[1..] {
let (path, id, mode) = &files[i];
let new = (1..)
.map(|n| names::clash_name(path, n))
.find(|p| !taken.contains(&p.to_lowercase()))
.unwrap();
taken.insert(new.to_lowercase());
update.remove(path.as_str());
update.upsert(new.as_str(), *id, file_mode(*mode));
report.case_renamed.push((path.clone(), new));
}
}
let tree = self.repo.find_tree(update.create_updated(&self.repo, &tree)?)?;
let names: Vec<String> = report.case_renamed.iter().map(|(a, b)| format!("{a} → {b}")).collect();
let message = format!("Renamed notes whose names differed only by case: {}", names.join(", "));
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[&commit])?)
}
fn note_incoming(&self, local: Option<&Commit>, incoming: &Commit, target: Oid, report: &mut SyncReport) -> Result<()> {
let old_tree = local.map(|c| c.tree()).transpose()?;
let new_tree = self.repo.find_commit(target)?.tree()?;
let diff = self.repo.diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), None)?;
report.received = diff
.deltas()
.filter_map(|d| d.new_file().path().or(d.old_file().path()).map(names::slash_path))
.collect();
let mut walk = self.repo.revwalk()?;
walk.set_sorting(Sort::TOPOLOGICAL)?;
walk.push(incoming.id())?;
if let Some(l) = local {
walk.hide(l.id())?;
}
for id in walk {
let c = self.repo.find_commit(id?)?;
if let Ok(name) = c.author().name()
&& name != self.label
{
report.from.insert(name.to_string());
}
}
Ok(())
}
/// Writes `target` to the folder without touching anything that's still being edited, then makes it current.
fn move_to(&self, target: Oid) -> Result<(), git2::Error> {
let commit = self.repo.find_commit(target)?;
let mut co = CheckoutBuilder::new();
co.safe();
self.repo.checkout_tree(commit.as_object(), Some(&mut co))?;
self.repo.reference(&self.branch_ref(), target, true, "lune: synced")?;
Ok(())
}
/// Files changed here that haven't reached the remote yet (saved or not).
pub fn waiting_files(&self) -> Result<usize> {
let mut files: HashSet<String> = HashSet::new();
if let Some(head) = self.head_commit()? {
let base = match self.remote_commit()? {
Some(r) => match self.repo.merge_base(head.id(), r.id()) {
Ok(b) => Some(self.repo.find_commit(b)?.tree()?),
Err(_) => None,
},
None => None,
};
let diff = self.repo.diff_tree_to_tree(base.as_ref(), Some(&head.tree()?), None)?;
files.extend(diff.deltas().filter_map(|d| d.new_file().path().map(names::slash_path)));
}
let mut opts = StatusOptions::new();
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false);
for s in self.repo.statuses(Some(&mut opts))?.iter() {
if let Ok(p) = s.path() {
files.insert(p.to_string());
}
}
Ok(files.len())
}
/// Every tracked file name, for the tidy list.
pub fn tracked_files(&self) -> Result<Vec<String>> {
let mut index = self.repo.index()?;
index.read(false)?;
Ok(index.iter().map(|e| String::from_utf8_lossy(&e.path).into_owned()).collect())
}
}
fn stage0(e: &IndexEntry, path: Option<&[u8]>) -> IndexEntry {
let mut e = IndexEntry { path: e.path.clone(), ..*e };
e.flags = 0;
e.flags_extended = 0;
if let Some(p) = path {
e.path = p.to_vec();
}
e
}
fn file_mode(mode: i32) -> FileMode {
match mode {
0o100755 => FileMode::BlobExecutable,
0o120000 => FileMode::Link,
_ => FileMode::Blob,
}
}
fn describe_files(diff: &git2::Diff) -> String {
let deltas: Vec<_> = diff.deltas().collect();
if let [d] = deltas.as_slice() {
let path = d.new_file().path().or(d.old_file().path()).map(names::slash_path).unwrap_or_default();
let verb = match d.status() {
git2::Delta::Added | git2::Delta::Untracked => "Added",
git2::Delta::Deleted => "Removed",
git2::Delta::Renamed => "Renamed",
_ => "Updated",
};
return format!("{verb} {path}");
}
format!("Updated {} notes", deltas.len())
}
/// What `add` did with the folder.
pub enum Added {
Downloaded(usize),
Adopted(usize),
StartedEmpty,
}
/// Sets up `path` as a vault shared through `remote`: clones into an empty folder, adopts an existing one.
/// A failed first sync isn't fatal: the vault is set up and the runner will retry.
pub fn add(name: &str, path: &Path, remote_url: &str, label: &str) -> Result<(VaultConfig, Added, Option<String>)> {
let existed = path.exists();
if existed && !path.is_dir() {
bail!("{} is a file, not a folder", path.display());
}
let empty = !existed || std::fs::read_dir(path)?.next().is_none();
std::fs::create_dir_all(path)?;
let path = std::fs::canonicalize(path)?;
let repo = if path.join(".git").exists() {
let repo = Repository::open(&path)?;
match repo.find_remote("origin") {
Ok(r) if r.url().ok() != Some(remote_url) => {
bail!("this folder already syncs with {} — not changing that", r.url().unwrap_or("?"))
}
Ok(_) => {}
Err(_) => {
repo.remote("origin", remote_url)?;
}
}
repo
} else {
let mut opts = RepositoryInitOptions::new();
opts.no_reinit(true);
let repo = Repository::init_opts(&path, &opts)?;
repo.remote("origin", remote_url)?;
repo
};
let branch = match repo.head() {
Ok(h) if h.is_branch() => h.shorthand().unwrap_or("main").to_string(),
_ => {
let b = remote_default_branch(&repo)?.unwrap_or_else(|| "main".into());
repo.set_head(&format!("refs/heads/{b}"))?;
b
}
};
configure(&repo)?;
let git_dir = repo.path().to_path_buf();
state::write_marker(&git_dir, name, !existed)?;
drop(repo);
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch };
let vault = Vault::open(&cfg, label)?;
let _op = state::op_lock(&git_dir)?;
vault.save_changes(Some(&format!("Added the vault on {label}")), &HashSet::new())?;
let sync_error = vault.sync().err().map(|e| remote::describe_error(&e));
let count = vault.tracked_files()?.len();
let added = match empty {
true if count == 0 => Added::StartedEmpty,
true => Added::Downloaded(count),
false => Added::Adopted(count),
};
Ok((cfg, added, sync_error))
}
/// The remote's main line name, or None if the remote is empty. Fails if the remote can't be reached.
fn remote_default_branch(repo: &Repository) -> Result<Option<String>> {
let mut remote = repo.find_remote("origin")?;
let conn = remote
.connect_auth(Direction::Fetch, Some(remote::callbacks()), None)
.map_err(anyhow::Error::from)
.map_err(|e| anyhow::anyhow!("can't reach the remote: {}", remote::describe_error(&e)))?;
let name = conn
.default_branch()
.ok()
.and_then(|b| b.as_str().ok().and_then(|s| s.strip_prefix("refs/heads/")).map(String::from));
if name.is_some() {
return Ok(name);
}
// Some servers don't advertise HEAD; fall back to whatever line exists.
let heads: Vec<String> = conn
.list()?
.iter()
.filter_map(|h| h.name().strip_prefix("refs/heads/").map(String::from))
.collect();
Ok(["main", "master"]
.iter()
.find(|b| heads.iter().any(|h| h == *b))
.map(|b| b.to_string())
.or_else(|| heads.into_iter().next()))
}
/// Byte-exact settings and the default ignore list. Lives inside `.git/`, so the vault's files are untouched.
pub fn configure(repo: &Repository) -> Result<()> {
let mut cfg = repo.config()?.open_level(ConfigLevel::Local)?;
cfg.set_bool("core.autocrlf", false)?;
cfg.set_str("core.safecrlf", "false")?;
let info = repo.path().join("info");
std::fs::create_dir_all(&info)?;
std::fs::write(info.join("attributes"), BYTE_EXACT_ATTRIBUTES)?;
let exclude = info.join("exclude");
let current = std::fs::read_to_string(&exclude).unwrap_or_default();
if !current.contains("# lune defaults") {
let sep = if current.is_empty() || current.ends_with('\n') { "" } else { "\n" };
std::fs::write(&exclude, format!("{current}{sep}{DEFAULT_IGNORES}"))?;
}
Ok(())
}