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:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
target/
|
||||||
|
.claude/settings.local.json
|
||||||
25
CLAUDE.md
Normal file
25
CLAUDE.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Project guardrails
|
||||||
|
|
||||||
|
Read `docs/SPEC.md` before any work. It is the single source of truth.
|
||||||
|
|
||||||
|
## The one rule that matters
|
||||||
|
Build **only the current milestone** (see SPEC §5–6). Every feature must pass the north-star test: sync you can trust, access as a lifecycle, or approachable. If it passes none, it waits — even if it seems useful.
|
||||||
|
|
||||||
|
## Working with Sen
|
||||||
|
- Sen likes big steps. Plans are few, large, user-reviewable milestones — never deep trees of sub-tasks.
|
||||||
|
- A milestone is done when its story in SPEC works when Sen acts it out. Show him how to run it.
|
||||||
|
- Decisions in SPEC §3 are settled. To change one, ask Sen, then record it in SPEC §8 with the date. Never change direction silently.
|
||||||
|
- Implementation details not covered by SPEC (crates, file layout, internal APIs) are yours to choose; mention notable ones briefly.
|
||||||
|
|
||||||
|
## Keep it small
|
||||||
|
- Docs live in two files: this one and `docs/SPEC.md`. Don't create more planning documents, status reports or evidence folders.
|
||||||
|
- No security audits, CVE sweeps, multi-arch packaging or release evidence before Milestone 7.
|
||||||
|
- No microservices, CRDTs, custom VCS, plugin systems or agent integrations.
|
||||||
|
- Tests: cover sync correctness (no lost data, conflicts keep both, byte-exact round trips). Skip ceremony.
|
||||||
|
|
||||||
|
## Product rules that are easy to break
|
||||||
|
- Never lose user data. When unsure, keep both copies.
|
||||||
|
- Never block sync waiting for a human.
|
||||||
|
- Never store secrets; never grant infrastructure access.
|
||||||
|
- Never show Git words (commit, push, merge, branch) in user-facing text.
|
||||||
|
- Only delete folders the app created (marker in `.git/`).
|
||||||
1295
Cargo.lock
generated
Normal file
1295
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
3
Cargo.toml
Normal file
3
Cargo.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "3"
|
||||||
|
members = ["core", "cli"]
|
||||||
10
cli/Cargo.toml
Normal file
10
cli/Cargo.toml
Normal 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
333
cli/src/main.rs
Normal 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
121
cli/src/service.rs
Normal 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('&', "&").replace('<', "<").replace('>', ">")
|
||||||
|
}
|
||||||
18
core/Cargo.toml
Normal file
18
core/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
[package]
|
||||||
|
name = "lune-core"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.104"
|
||||||
|
chrono = "0.4.45"
|
||||||
|
dirs = "7.0.0"
|
||||||
|
gethostname = "1.1.0"
|
||||||
|
git2 = { version = "0.21.0", features = ["ssh", "https", "vendored-libgit2", "vendored-openssl"] }
|
||||||
|
notify = "8.2.1"
|
||||||
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
serde_json = "1.0.154"
|
||||||
|
toml = "1.1.8"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3.27.0"
|
||||||
99
core/src/config.rs
Normal file
99
core/src/config.rs
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
//! User config: device label and the list of vaults, stored as TOML in the OS config dir.
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
|
pub struct Config {
|
||||||
|
/// Label for this device, used to sign every history entry (S7).
|
||||||
|
#[serde(default)]
|
||||||
|
pub device_name: Option<String>,
|
||||||
|
/// How often to check the remote for new changes, in seconds.
|
||||||
|
#[serde(default)]
|
||||||
|
pub poll_seconds: Option<u64>,
|
||||||
|
#[serde(default, rename = "vault")]
|
||||||
|
pub vaults: Vec<VaultConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct VaultConfig {
|
||||||
|
pub name: String,
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub remote: String,
|
||||||
|
pub branch: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).
|
||||||
|
pub fn config_dir() -> Result<PathBuf> {
|
||||||
|
if let Some(home) = std::env::var_os("LUNE_HOME") {
|
||||||
|
return Ok(PathBuf::from(home));
|
||||||
|
}
|
||||||
|
let base = dirs::config_dir().context("can't find the config folder for this user")?;
|
||||||
|
Ok(base.join("lune"))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn path() -> Result<PathBuf> {
|
||||||
|
Ok(config_dir()?.join("config.toml"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load() -> Result<Config> {
|
||||||
|
let path = Self::path()?;
|
||||||
|
match std::fs::read_to_string(&path) {
|
||||||
|
Ok(text) => toml::from_str(&text).with_context(|| format!("can't read {}", path.display())),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
|
||||||
|
Err(e) => Err(e).with_context(|| format!("can't read {}", path.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self) -> Result<()> {
|
||||||
|
let path = Self::path()?;
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||||
|
let tmp = path.with_extension("toml.tmp");
|
||||||
|
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
|
||||||
|
std::fs::rename(&tmp, &path)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn device_label(&self) -> String {
|
||||||
|
self.device_name.clone().unwrap_or_else(default_device_name)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn poll_interval(&self) -> std::time::Duration {
|
||||||
|
std::time::Duration::from_secs(self.poll_seconds.unwrap_or(3).max(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find(&self, name: &str) -> Option<&VaultConfig> {
|
||||||
|
self.vaults.iter().find(|v| v.name.eq_ignore_ascii_case(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Picks a vault: by name if given, else the one containing `cwd`, else the only one.
|
||||||
|
pub fn pick(&self, name: Option<&str>, cwd: &Path) -> Result<&VaultConfig> {
|
||||||
|
if let Some(name) = name {
|
||||||
|
return self.find(name).with_context(|| format!("no vault named \"{name}\""));
|
||||||
|
}
|
||||||
|
if let Some(v) = self.containing(cwd) {
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
match self.vaults.as_slice() {
|
||||||
|
[] => bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>`"),
|
||||||
|
[only] => Ok(only),
|
||||||
|
_ => bail!("more than one vault — say which with --vault <name>"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The vault whose folder contains `path`, if any.
|
||||||
|
pub fn containing(&self, path: &Path) -> Option<&VaultConfig> {
|
||||||
|
let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
|
||||||
|
self.vaults.iter().find(|v| {
|
||||||
|
let root = std::fs::canonicalize(&v.path).unwrap_or_else(|_| v.path.clone());
|
||||||
|
path.starts_with(root)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn default_device_name() -> String {
|
||||||
|
let host = gethostname::gethostname().to_string_lossy().into_owned();
|
||||||
|
host.split('.').next().unwrap_or("this device").to_string()
|
||||||
|
}
|
||||||
11
core/src/lib.rs
Normal file
11
core/src/lib.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
//! Lune's sync engine: keeps every copy of a vault current through a plain Git remote.
|
||||||
|
|
||||||
|
pub use git2;
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
|
pub mod names;
|
||||||
|
pub mod remote;
|
||||||
|
pub mod runner;
|
||||||
|
pub mod state;
|
||||||
|
pub mod tidy;
|
||||||
|
pub mod vault;
|
||||||
83
core/src/names.rs
Normal file
83
core/src/names.rs
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
//! File-name helpers: "kept both" copies, case-clash renames, and path conversions.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// Vault-relative path with forward slashes, as Git stores it.
|
||||||
|
pub fn slash_path(p: &Path) -> String {
|
||||||
|
p.to_string_lossy().replace('\\', "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bytes_path(b: &[u8]) -> PathBuf {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
PathBuf::from(std::ffi::OsStr::from_bytes(b))
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
PathBuf::from(String::from_utf8_lossy(b).into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits `dir/name.ext` into (`dir/name`, `.ext`). Dotfiles like `.env` have no extension.
|
||||||
|
fn split_ext(path: &str) -> (&str, &str) {
|
||||||
|
let file_start = path.rfind('/').map_or(0, |i| i + 1);
|
||||||
|
match path[file_start..].rfind('.') {
|
||||||
|
Some(dot) if dot > 0 => path.split_at(file_start + dot),
|
||||||
|
_ => (path, ""),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `runbook.md` → `runbook (Codex's version).md`; n > 1 adds a number.
|
||||||
|
pub fn copy_name(path: &str, label: &str, n: usize) -> String {
|
||||||
|
let (stem, ext) = split_ext(path);
|
||||||
|
let num = if n > 1 { format!(" {n}") } else { String::new() };
|
||||||
|
format!("{stem} ({label}'s version{num}){ext}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Notes.md` → `Notes (name clash).md`; n > 1 adds a number.
|
||||||
|
pub fn clash_name(path: &str, n: usize) -> String {
|
||||||
|
let (stem, ext) = split_ext(path);
|
||||||
|
let num = if n > 1 { format!(" {n}") } else { String::new() };
|
||||||
|
format!("{stem} (name clash{num}){ext}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `runbook (from Codex).md`: what a copy becomes when both are kept for good.
|
||||||
|
pub fn kept_name(original: &str, label: &str, n: usize) -> String {
|
||||||
|
let (stem, ext) = split_ext(original);
|
||||||
|
let num = if n > 1 { format!(" {n}") } else { String::new() };
|
||||||
|
format!("{stem} (from {label}{num}){ext}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If `path` is a kept-both copy, returns (original path, device label).
|
||||||
|
pub fn parse_copy(path: &str) -> Option<(String, String)> {
|
||||||
|
const MARK: &str = "'s version";
|
||||||
|
let file_start = path.rfind('/').map_or(0, |i| i + 1);
|
||||||
|
let name = &path[file_start..];
|
||||||
|
let v = name.rfind(MARK)?;
|
||||||
|
let open = name[..v].rfind(" (")?;
|
||||||
|
let label = &name[open + 2..v];
|
||||||
|
let rest = &name[v + MARK.len()..];
|
||||||
|
let close = rest.find(')')?;
|
||||||
|
let num = &rest[..close];
|
||||||
|
let num_ok = num.is_empty() || (num.len() > 1 && num.starts_with(' ') && num[1..].bytes().all(|b| b.is_ascii_digit()));
|
||||||
|
let ext = &rest[close + 1..];
|
||||||
|
if label.is_empty() || !num_ok || !(ext.is_empty() || ext.starts_with('.')) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((format!("{}{}{}", &path[..file_start], &name[..open], ext), label.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn copy_names_round_trip() {
|
||||||
|
for (p, l, n) in [("runbook.md", "Codex", 1), ("ops/vm list.md", "Hermes", 2), (".env", "VPS", 1), ("a.tar.gz", "x", 1), ("README", "Mac", 3)] {
|
||||||
|
let c = copy_name(p, l, n);
|
||||||
|
assert_eq!(parse_copy(&c), Some((p.to_string(), l.to_string())), "{c}");
|
||||||
|
}
|
||||||
|
assert_eq!(copy_name("ops/runbook.md", "Codex", 1), "ops/runbook (Codex's version).md");
|
||||||
|
assert_eq!(parse_copy("notes/plain.md"), None);
|
||||||
|
assert_eq!(parse_copy("Sen's version.md"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
68
core/src/remote.rs
Normal file
68
core/src/remote.rs
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
//! Talking to the Git remote with whatever credentials the user already has (SSH agent, key files, credential helper).
|
||||||
|
|
||||||
|
use git2::{Cred, CredentialType, ErrorClass, ErrorCode, RemoteCallbacks};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
|
||||||
|
let mut tried_agent = false;
|
||||||
|
let mut keys = default_key_files().into_iter();
|
||||||
|
let mut tried_helper = false;
|
||||||
|
let mut cb = RemoteCallbacks::new();
|
||||||
|
cb.credentials(move |url, username, allowed| {
|
||||||
|
let user = username.unwrap_or("git");
|
||||||
|
if allowed.contains(CredentialType::USERNAME) {
|
||||||
|
return Cred::username(user);
|
||||||
|
}
|
||||||
|
if allowed.contains(CredentialType::SSH_KEY) {
|
||||||
|
if !tried_agent {
|
||||||
|
tried_agent = true;
|
||||||
|
if std::env::var_os("SSH_AUTH_SOCK").is_some() {
|
||||||
|
return Cred::ssh_key_from_agent(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(key) = keys.next() {
|
||||||
|
return Cred::ssh_key(user, None, &key, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if allowed.contains(CredentialType::USER_PASS_PLAINTEXT) && !tried_helper {
|
||||||
|
tried_helper = true;
|
||||||
|
if let Ok(config) = git2::Config::open_default() {
|
||||||
|
return Cred::credential_helper(&config, url, username);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if allowed.contains(CredentialType::DEFAULT) {
|
||||||
|
return Cred::default();
|
||||||
|
}
|
||||||
|
Err(git2::Error::from_str("no working credentials for the remote"))
|
||||||
|
});
|
||||||
|
cb
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_key_files() -> Vec<PathBuf> {
|
||||||
|
let Some(home) = dirs::home_dir() else { return vec![] };
|
||||||
|
["id_ed25519", "id_ecdsa", "id_rsa"]
|
||||||
|
.iter()
|
||||||
|
.map(|n| home.join(".ssh").join(n))
|
||||||
|
.filter(|p| p.exists())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turns a remote failure into plain words for `status` and the run log.
|
||||||
|
pub fn describe_error(e: &anyhow::Error) -> String {
|
||||||
|
if let Some(g) = e.downcast_ref::<git2::Error>() {
|
||||||
|
if g.code() == ErrorCode::Auth {
|
||||||
|
return "the remote didn't accept our sign-in (check your SSH key or Git credentials)".into();
|
||||||
|
}
|
||||||
|
if matches!(g.class(), ErrorClass::Net | ErrorClass::Ssh | ErrorClass::Http | ErrorClass::Os)
|
||||||
|
|| g.code() == ErrorCode::Eof
|
||||||
|
{
|
||||||
|
return format!("offline — can't reach the remote ({})", g.message());
|
||||||
|
}
|
||||||
|
return g.message().to_string();
|
||||||
|
}
|
||||||
|
format!("{e:#}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_offline(e: &anyhow::Error) -> bool {
|
||||||
|
describe_error(e).starts_with("offline")
|
||||||
|
}
|
||||||
228
core/src/runner.rs
Normal file
228
core/src/runner.rs
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
//! The background loop: watch → settle → save → sync, for one vault.
|
||||||
|
|
||||||
|
use crate::config::VaultConfig;
|
||||||
|
use crate::remote;
|
||||||
|
use crate::state::{self, SyncState};
|
||||||
|
use crate::vault::{SyncReport, Vault};
|
||||||
|
use anyhow::{Result, bail};
|
||||||
|
use notify::{EventKind, RecursiveMode, Watcher};
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::mpsc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// Timing for bursts of edits (S2).
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct Timing {
|
||||||
|
/// A burst ends after this much quiet...
|
||||||
|
pub quiet: Duration,
|
||||||
|
/// ...or at the latest this long after it started.
|
||||||
|
pub cap: Duration,
|
||||||
|
/// When a burst is cut at the cap, files changed more recently than this wait for the next one.
|
||||||
|
pub settle: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Timing {
|
||||||
|
fn default() -> Self {
|
||||||
|
Timing { quiet: Duration::from_secs(5), cap: Duration::from_secs(60), settle: Duration::from_secs(2) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tracks the current burst of edits.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct Burst {
|
||||||
|
started: Option<Instant>,
|
||||||
|
last: Option<Instant>,
|
||||||
|
touched: HashMap<String, Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Burst {
|
||||||
|
pub fn touch(&mut self, path: String, now: Instant) {
|
||||||
|
self.started.get_or_insert(now);
|
||||||
|
self.last = Some(now);
|
||||||
|
self.touched.insert(path, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_idle(&self) -> bool {
|
||||||
|
self.started.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn due(&self, now: Instant, t: &Timing) -> bool {
|
||||||
|
match (self.started, self.last) {
|
||||||
|
(Some(s), Some(l)) => now - l >= t.quiet || now - s >= t.cap,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends the burst. Returns files still changing, which must not be saved yet; they start the next burst.
|
||||||
|
pub fn take(&mut self, now: Instant, t: &Timing) -> HashSet<String> {
|
||||||
|
let unsettled: HashMap<String, Instant> =
|
||||||
|
self.touched.drain().filter(|(_, at)| now - *at < t.settle).collect();
|
||||||
|
let skip = unsettled.keys().cloned().collect();
|
||||||
|
*self = Burst::default();
|
||||||
|
if !unsettled.is_empty() {
|
||||||
|
self.started = Some(now);
|
||||||
|
self.last = unsettled.values().max().copied();
|
||||||
|
self.touched = unsettled;
|
||||||
|
}
|
||||||
|
skip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync);
|
||||||
|
|
||||||
|
/// Runs forever for one vault. `log(vault, message)` prints progress.
|
||||||
|
pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: Log) -> Result<()> {
|
||||||
|
let vault = Vault::open(cfg, label)?;
|
||||||
|
let Some(_running) = state::try_run_lock(&vault.git_dir)? else {
|
||||||
|
bail!("{} is already being synced by another lunesync run", cfg.name);
|
||||||
|
};
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
let mut watcher = notify::recommended_watcher(move |ev| {
|
||||||
|
let _ = tx.send(ev);
|
||||||
|
})?;
|
||||||
|
watcher.watch(&vault.root, RecursiveMode::Recursive)?;
|
||||||
|
|
||||||
|
let say = |m: &str| log(&vault.name, m);
|
||||||
|
say(&format!("watching {} as {}", vault.root.display(), label));
|
||||||
|
|
||||||
|
let mut burst = Burst::default();
|
||||||
|
let mut rescan_at = Instant::now(); // pick up anything changed while we weren't running
|
||||||
|
let mut sync_at = Instant::now();
|
||||||
|
let mut backoff = poll;
|
||||||
|
let mut was_waiting = false;
|
||||||
|
loop {
|
||||||
|
let first = rx.recv_timeout(Duration::from_millis(250));
|
||||||
|
for ev in first.into_iter().chain(rx.try_iter()) {
|
||||||
|
match ev {
|
||||||
|
Ok(ev) if !matches!(ev.kind, EventKind::Access(_)) => {
|
||||||
|
for p in ev.paths {
|
||||||
|
if let Some(rel) = relevant(&vault, &p) {
|
||||||
|
burst.touch(rel, Instant::now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(e) => say(&format!("file watcher hiccup: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = Instant::now();
|
||||||
|
let rescan = now >= rescan_at && burst.is_idle();
|
||||||
|
if rescan || burst.due(now, &timing) {
|
||||||
|
let skip = burst.take(now, &timing);
|
||||||
|
rescan_at = now + Duration::from_secs(60);
|
||||||
|
let _op = state::op_lock(&vault.git_dir)?;
|
||||||
|
match vault.save_changes(None, &skip) {
|
||||||
|
Ok(Some(saved)) => {
|
||||||
|
say(&format!("saved: {}", saved.message));
|
||||||
|
sync_at = now;
|
||||||
|
}
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(e) => say(&format!("couldn't save changes: {e:#}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if Instant::now() >= sync_at {
|
||||||
|
let _op = state::op_lock(&vault.git_dir)?;
|
||||||
|
let result = vault.sync();
|
||||||
|
let mut st = SyncState::load(&vault.git_dir);
|
||||||
|
st.last_attempt = Some(chrono::Utc::now().timestamp());
|
||||||
|
match result {
|
||||||
|
Ok(report) => {
|
||||||
|
st.last_error = None;
|
||||||
|
if !report.waiting_for_local_edits {
|
||||||
|
st.last_synced = st.last_attempt;
|
||||||
|
}
|
||||||
|
if report.waiting_for_local_edits && !was_waiting {
|
||||||
|
say("new changes are waiting until your current edits settle");
|
||||||
|
}
|
||||||
|
was_waiting = report.waiting_for_local_edits;
|
||||||
|
print_report(&report, &say);
|
||||||
|
backoff = poll;
|
||||||
|
sync_at = Instant::now() + poll;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let msg = remote::describe_error(&e);
|
||||||
|
if st.last_error.as_deref() != Some(msg.as_str()) {
|
||||||
|
say(&format!("{msg} — will keep trying"));
|
||||||
|
}
|
||||||
|
st.last_error = Some(msg);
|
||||||
|
backoff = (backoff * 2).min(Duration::from_secs(60));
|
||||||
|
sync_at = Instant::now() + backoff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Err(e) = st.save(&vault.git_dir) {
|
||||||
|
say(&format!("couldn't record sync status: {e:#}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Vault-relative path for a watcher event, or None for our own files and ignored ones.
|
||||||
|
fn relevant(vault: &Vault, p: &Path) -> Option<String> {
|
||||||
|
let rel = p.strip_prefix(&vault.root).ok()?;
|
||||||
|
if rel.as_os_str().is_empty() || rel.starts_with(".git") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if vault.is_ignored(rel) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(crate::names::slash_path(rel))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_report(r: &SyncReport, say: &dyn Fn(&str)) {
|
||||||
|
if !r.received.is_empty() {
|
||||||
|
let from: Vec<&str> = r.from.iter().map(String::as_str).collect();
|
||||||
|
let who = if from.is_empty() { String::new() } else { format!(" from {}", from.join(", ")) };
|
||||||
|
say(&format!("received {}{who}", count_notes(&r.received)));
|
||||||
|
}
|
||||||
|
for (note, copy) in &r.kept_both {
|
||||||
|
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
|
||||||
|
}
|
||||||
|
for (old, new) in &r.case_renamed {
|
||||||
|
say(&format!("{old} clashed with another name differing only by case — renamed to {new}"));
|
||||||
|
}
|
||||||
|
if r.shared > 0 {
|
||||||
|
say(&format!("shared {} change{}", r.shared, if r.shared == 1 { "" } else { "s" }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count_notes(files: &[String]) -> String {
|
||||||
|
match files {
|
||||||
|
[one] => one.clone(),
|
||||||
|
many => format!("{} notes", many.len()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn burst_ends_after_quiet_or_cap_and_holds_back_unsettled_files() {
|
||||||
|
let t = Timing::default();
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let s = Duration::from_secs;
|
||||||
|
let mut b = Burst::default();
|
||||||
|
assert!(!b.due(t0, &t));
|
||||||
|
|
||||||
|
b.touch("a.md".into(), t0);
|
||||||
|
b.touch("b.md".into(), t0 + s(3));
|
||||||
|
assert!(!b.due(t0 + s(7), &t));
|
||||||
|
assert!(b.due(t0 + s(8), &t));
|
||||||
|
assert!(b.take(t0 + s(8), &t).is_empty());
|
||||||
|
assert!(!b.due(t0 + s(100), &t));
|
||||||
|
|
||||||
|
// A file written every second never goes quiet: the cap ends the burst without it.
|
||||||
|
let mut b = Burst::default();
|
||||||
|
b.touch("done.md".into(), t0);
|
||||||
|
for i in 0..=60 {
|
||||||
|
b.touch("log.md".into(), t0 + s(i));
|
||||||
|
}
|
||||||
|
assert!(b.due(t0 + s(60), &t));
|
||||||
|
let skip = b.take(t0 + s(60), &t);
|
||||||
|
assert_eq!(skip, HashSet::from(["log.md".to_string()]));
|
||||||
|
assert!(b.due(t0 + s(65), &t), "the still-changing file starts the next burst");
|
||||||
|
}
|
||||||
|
}
|
||||||
113
core/src/state.rs
Normal file
113
core/src/state.rs
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
//! Per-vault bookkeeping inside `.git/lune/`: the app marker, process locks and the last sync outcome.
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs::{File, OpenOptions};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// Folder inside `.git/` that holds everything the app keeps per vault.
|
||||||
|
pub fn lune_dir(git_dir: &Path) -> PathBuf {
|
||||||
|
git_dir.join("lune")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marker proving the app manages this folder (A9). `created` is true only when the app made the folder itself.
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Marker {
|
||||||
|
pub managed_by: String,
|
||||||
|
pub vault: String,
|
||||||
|
pub created_folder: bool,
|
||||||
|
pub added_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_marker(git_dir: &Path, vault: &str, created_folder: bool) -> Result<()> {
|
||||||
|
let dir = lune_dir(git_dir);
|
||||||
|
std::fs::create_dir_all(&dir)?;
|
||||||
|
let marker = Marker {
|
||||||
|
managed_by: "lune".into(),
|
||||||
|
vault: vault.into(),
|
||||||
|
created_folder,
|
||||||
|
added_at: chrono::Utc::now().timestamp(),
|
||||||
|
};
|
||||||
|
std::fs::write(dir.join("vault.toml"), toml::to_string_pretty(&marker)?)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_marker(git_dir: &Path) -> Option<Marker> {
|
||||||
|
let text = std::fs::read_to_string(lune_dir(git_dir).join("vault.toml")).ok()?;
|
||||||
|
toml::from_str(&text).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Outcome of the last sync attempt, written by whoever ran it and read by `status`.
|
||||||
|
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||||
|
pub struct SyncState {
|
||||||
|
/// Unix time of the last fully successful sync.
|
||||||
|
pub last_synced: Option<i64>,
|
||||||
|
/// Unix time of the last attempt, successful or not.
|
||||||
|
pub last_attempt: Option<i64>,
|
||||||
|
/// Plain-words reason the last attempt failed, if it did.
|
||||||
|
pub last_error: Option<String>,
|
||||||
|
/// Paths that differed only by letter case and were renamed or reported.
|
||||||
|
#[serde(default)]
|
||||||
|
pub case_clashes: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SyncState {
|
||||||
|
pub fn load(git_dir: &Path) -> SyncState {
|
||||||
|
std::fs::read_to_string(lune_dir(git_dir).join("state.json"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| serde_json::from_str(&t).ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self, git_dir: &Path) -> Result<()> {
|
||||||
|
let dir = lune_dir(git_dir);
|
||||||
|
std::fs::create_dir_all(&dir)?;
|
||||||
|
let tmp = dir.join("state.json.tmp");
|
||||||
|
std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?;
|
||||||
|
std::fs::rename(&tmp, dir.join("state.json"))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An OS file lock that is released when dropped (or when the process dies).
|
||||||
|
pub struct Lock(#[allow(dead_code)] File);
|
||||||
|
|
||||||
|
fn open_lock(git_dir: &Path, name: &str) -> Result<File> {
|
||||||
|
let dir = lune_dir(git_dir);
|
||||||
|
std::fs::create_dir_all(&dir)?;
|
||||||
|
OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.write(true)
|
||||||
|
.open(dir.join(name))
|
||||||
|
.with_context(|| format!("can't open lock in {}", dir.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Held by `lunesync run` for its whole life: one watcher per vault, and lets `status` see it's running.
|
||||||
|
pub fn try_run_lock(git_dir: &Path) -> Result<Option<Lock>> {
|
||||||
|
let file = open_lock(git_dir, "run.lock")?;
|
||||||
|
match file.try_lock() {
|
||||||
|
Ok(()) => Ok(Some(Lock(file))),
|
||||||
|
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||||
|
Err(std::fs::TryLockError::Error(e)) => Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_running(git_dir: &Path) -> bool {
|
||||||
|
matches!(try_run_lock(git_dir), Ok(None))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serializes every change to the vault's history between the background runner and one-off commands.
|
||||||
|
pub fn op_lock(git_dir: &Path) -> Result<Lock> {
|
||||||
|
let file = open_lock(git_dir, "op.lock")?;
|
||||||
|
file.lock()?;
|
||||||
|
// We hold the only right to touch the history now, so an old index lock is from a killed run.
|
||||||
|
let stale = git_dir.join("index.lock");
|
||||||
|
let old = std::fs::metadata(&stale)
|
||||||
|
.and_then(|m| m.modified())
|
||||||
|
.is_ok_and(|t| t.elapsed().unwrap_or_default().as_secs() > 30);
|
||||||
|
if old {
|
||||||
|
let _ = std::fs::remove_file(stale);
|
||||||
|
}
|
||||||
|
Ok(Lock(file))
|
||||||
|
}
|
||||||
69
core/src/tidy.rs
Normal file
69
core/src/tidy.rs
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
//! Notes where both versions were kept, and resolving them (`lunesync tidy`).
|
||||||
|
|
||||||
|
use crate::names;
|
||||||
|
use crate::vault::{Saved, Vault};
|
||||||
|
use anyhow::{Result, bail};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct KeptBoth {
|
||||||
|
pub note: String,
|
||||||
|
pub copy: String,
|
||||||
|
/// Device whose version was saved beside the note.
|
||||||
|
pub label: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub enum Keep {
|
||||||
|
Mine,
|
||||||
|
Theirs,
|
||||||
|
Both,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list(vault: &Vault) -> Result<Vec<KeptBoth>> {
|
||||||
|
let mut out: Vec<KeptBoth> = vault
|
||||||
|
.tracked_files()?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|p| vault.root.join(p).exists())
|
||||||
|
.filter_map(|copy| names::parse_copy(©).map(|(note, label)| KeptBoth { note, copy, label }))
|
||||||
|
.collect();
|
||||||
|
out.sort_by(|a, b| (&a.note, &a.copy).cmp(&(&b.note, &b.copy)));
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves the pair for `file` (the note or its copy). "Mine" is this device's version.
|
||||||
|
/// The caller holds the vault's op lock.
|
||||||
|
pub fn keep(vault: &Vault, file: &str, choice: Keep) -> Result<Option<Saved>> {
|
||||||
|
let all = list(vault)?;
|
||||||
|
let pairs: Vec<&KeptBoth> = match all.iter().find(|k| k.copy == file) {
|
||||||
|
Some(k) => vec![k],
|
||||||
|
None => all.iter().filter(|k| k.note == file).collect(),
|
||||||
|
};
|
||||||
|
let note = match pairs.as_slice() {
|
||||||
|
[] => bail!("{file} has no kept-both versions to tidy"),
|
||||||
|
[one] => one.note.clone(),
|
||||||
|
many if choice == Keep::Both => many[0].note.clone(),
|
||||||
|
many => {
|
||||||
|
let copies: Vec<&str> = many.iter().map(|k| k.copy.as_str()).collect();
|
||||||
|
bail!("{file} has several kept versions — name the one you mean: {}", copies.join(", "))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for k in pairs {
|
||||||
|
let copy = vault.root.join(&k.copy);
|
||||||
|
let original = vault.root.join(&k.note);
|
||||||
|
let copy_is_mine = k.label.eq_ignore_ascii_case(&vault.label);
|
||||||
|
match choice {
|
||||||
|
Keep::Both => {
|
||||||
|
let new = (1..)
|
||||||
|
.map(|n| names::kept_name(&k.note, &k.label, n))
|
||||||
|
.find(|p| !vault.root.join(p).exists())
|
||||||
|
.unwrap();
|
||||||
|
std::fs::rename(©, vault.root.join(new))?;
|
||||||
|
}
|
||||||
|
Keep::Mine if copy_is_mine => std::fs::rename(©, &original)?,
|
||||||
|
Keep::Theirs if !copy_is_mine => std::fs::rename(©, &original)?,
|
||||||
|
_ => std::fs::remove_file(©)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vault.save_changes(Some(&format!("Tidied {note}")), &HashSet::new())
|
||||||
|
}
|
||||||
551
core/src/vault.rs
Normal file
551
core/src/vault.rs
Normal 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(¬e, &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(())
|
||||||
|
}
|
||||||
363
core/tests/sync.rs
Normal file
363
core/tests/sync.rs
Normal file
@@ -0,0 +1,363 @@
|
|||||||
|
//! Sync correctness: nothing lost, clashes keep both, bytes round-trip exactly.
|
||||||
|
|
||||||
|
use git2::Repository;
|
||||||
|
use lune_core::tidy::{self, Keep};
|
||||||
|
use lune_core::vault::{self, Added, Vault};
|
||||||
|
use std::collections::{BTreeMap, HashSet};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
struct World {
|
||||||
|
tmp: TempDir,
|
||||||
|
remote: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl World {
|
||||||
|
fn new() -> World {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let remote = tmp.path().join("remote.git");
|
||||||
|
Repository::init_bare(&remote).unwrap();
|
||||||
|
World { tmp, remote }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn folder(&self, name: &str) -> PathBuf {
|
||||||
|
self.tmp.path().join(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device(&self, label: &str) -> Vault {
|
||||||
|
self.device_at(label, &self.folder(label))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_at(&self, label: &str, folder: &Path) -> Vault {
|
||||||
|
let (cfg, _, err) = vault::add("Test", folder, self.remote.to_str().unwrap(), label).unwrap();
|
||||||
|
assert_eq!(err, None);
|
||||||
|
Vault::open(&cfg, label).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(v: &Vault, rel: &str, bytes: impl AsRef<[u8]>) {
|
||||||
|
let p = v.root.join(rel);
|
||||||
|
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
fs::write(p, bytes).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(v: &Vault, rel: &str) -> Vec<u8> {
|
||||||
|
fs::read(v.root.join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_and_sync(v: &Vault) -> vault::SyncReport {
|
||||||
|
v.save_changes(None, &HashSet::new()).unwrap();
|
||||||
|
v.sync().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every file under `root` (outside .git) with its bytes.
|
||||||
|
fn snapshot(root: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||||
|
fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||||
|
for e in fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
let rel = p.strip_prefix(root).unwrap().to_string_lossy().into_owned();
|
||||||
|
if rel == ".git" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(root, &p, out);
|
||||||
|
} else {
|
||||||
|
out.insert(rel, fs::read(&p).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ten_lines() -> String {
|
||||||
|
(1..=10).map(|i| format!("line {i}\n")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bytes_round_trip_exactly_and_ignored_files_stay_home() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
let binary: Vec<u8> = (0..=255u8).cycle().take(5000).collect();
|
||||||
|
write(&a, "vm-list.md", "web-1\r\nweb-2\r\n");
|
||||||
|
write(&a, "no-newline.md", "end");
|
||||||
|
write(&a, "attachments/diagram.png", &binary);
|
||||||
|
write(&a, "Ünïcode folder/note.md", "héllo\n");
|
||||||
|
write(&a, ".obsidian/app.json", "{}");
|
||||||
|
write(&a, ".obsidian/workspace.json", "{\"open\":1}");
|
||||||
|
write(&a, ".DS_Store", "junk");
|
||||||
|
write(&a, ".trash/old.md", "gone");
|
||||||
|
save_and_sync(&a);
|
||||||
|
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
assert_eq!(read(&b, "vm-list.md"), b"web-1\r\nweb-2\r\n");
|
||||||
|
assert_eq!(read(&b, "no-newline.md"), b"end");
|
||||||
|
assert_eq!(read(&b, "attachments/diagram.png"), binary);
|
||||||
|
assert_eq!(read(&b, "Ünïcode folder/note.md"), "héllo\n".as_bytes());
|
||||||
|
assert_eq!(read(&b, ".obsidian/app.json"), b"{}");
|
||||||
|
for ignored in [".obsidian/workspace.json", ".DS_Store", ".trash/old.md"] {
|
||||||
|
assert!(!b.root.join(ignored).exists(), "{ignored} should not sync");
|
||||||
|
}
|
||||||
|
|
||||||
|
// And back again, with an edit from the other side.
|
||||||
|
write(&b, "vm-list.md", "web-1\r\nweb-2\r\nweb-3\r\n");
|
||||||
|
let report = save_and_sync(&b);
|
||||||
|
assert_eq!(report.shared, 1);
|
||||||
|
let report = a.sync().unwrap();
|
||||||
|
assert_eq!(report.received, vec!["vm-list.md"]);
|
||||||
|
assert!(report.from.contains("Hermes"));
|
||||||
|
assert_eq!(read(&a, "vm-list.md"), b"web-1\r\nweb-2\r\nweb-3\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_burst_is_one_history_entry_labeled_with_the_device() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
for i in 0..14 {
|
||||||
|
write(&b, &format!("notes/{i}.md"), format!("note {i}\n"));
|
||||||
|
}
|
||||||
|
let saved = b.save_changes(None, &HashSet::new()).unwrap().unwrap();
|
||||||
|
assert_eq!(saved.files.len(), 14);
|
||||||
|
b.sync().unwrap();
|
||||||
|
a.sync().unwrap();
|
||||||
|
let head = a.head_commit().unwrap().unwrap();
|
||||||
|
assert_eq!(head.author().name().unwrap(), "Hermes");
|
||||||
|
assert_eq!(head.summary().unwrap().unwrap(), "Updated 14 notes");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsettled_files_wait_for_the_next_burst() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "done.md", "done\n");
|
||||||
|
write(&a, "still-writing.md", "half");
|
||||||
|
let skip = HashSet::from(["still-writing.md".to_string()]);
|
||||||
|
let saved = a.save_changes(None, &skip).unwrap().unwrap();
|
||||||
|
assert_eq!(saved.files, vec!["done.md"]);
|
||||||
|
let saved = a.save_changes(None, &HashSet::new()).unwrap().unwrap();
|
||||||
|
assert_eq!(saved.files, vec!["still-writing.md"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edits_to_different_lines_combine() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "runbook.md", ten_lines());
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
|
||||||
|
write(&a, "runbook.md", ten_lines().replace("line 2\n", "line 2 from Codex\n"));
|
||||||
|
write(&b, "runbook.md", ten_lines().replace("line 9\n", "line 9 from Hermes\n"));
|
||||||
|
save_and_sync(&a);
|
||||||
|
let report = save_and_sync(&b);
|
||||||
|
assert!(report.kept_both.is_empty());
|
||||||
|
a.sync().unwrap();
|
||||||
|
|
||||||
|
let expected = ten_lines().replace("line 2\n", "line 2 from Codex\n").replace("line 9\n", "line 9 from Hermes\n");
|
||||||
|
assert_eq!(read(&a, "runbook.md"), expected.as_bytes());
|
||||||
|
assert_eq!(read(&b, "runbook.md"), expected.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn same_lines_keep_both_and_tidy_cleans_up() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "runbook.md", ten_lines());
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
|
||||||
|
let codex = ten_lines().replace("line 2\n", "restart with systemctl\n");
|
||||||
|
let hermes = ten_lines().replace("line 2\n", "restart with docker\n");
|
||||||
|
write(&a, "runbook.md", &codex);
|
||||||
|
write(&b, "runbook.md", &hermes);
|
||||||
|
save_and_sync(&a);
|
||||||
|
let report = save_and_sync(&b);
|
||||||
|
|
||||||
|
// Incoming stays in place, the local version is saved beside it. No markers anywhere.
|
||||||
|
assert_eq!(report.kept_both, vec![("runbook.md".into(), "runbook (Hermes's version).md".into())]);
|
||||||
|
assert_eq!(read(&b, "runbook.md"), codex.as_bytes());
|
||||||
|
assert_eq!(read(&b, "runbook (Hermes's version).md"), hermes.as_bytes());
|
||||||
|
a.sync().unwrap();
|
||||||
|
assert_eq!(snapshot(&a.root), snapshot(&b.root));
|
||||||
|
assert!(!String::from_utf8(read(&a, "runbook.md")).unwrap().contains("<<<<<<<"));
|
||||||
|
|
||||||
|
// Sync keeps running: further edits still flow.
|
||||||
|
write(&a, "other.md", "still syncing\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
b.sync().unwrap();
|
||||||
|
assert_eq!(read(&b, "other.md"), b"still syncing\n");
|
||||||
|
|
||||||
|
// Hermes keeps its own version.
|
||||||
|
let listed = tidy::list(&b).unwrap();
|
||||||
|
assert_eq!(listed.len(), 1);
|
||||||
|
tidy::keep(&b, "runbook.md", Keep::Mine).unwrap().unwrap();
|
||||||
|
b.sync().unwrap();
|
||||||
|
a.sync().unwrap();
|
||||||
|
assert_eq!(read(&a, "runbook.md"), hermes.as_bytes());
|
||||||
|
assert!(!a.root.join("runbook (Hermes's version).md").exists());
|
||||||
|
assert!(tidy::list(&a).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tidy_theirs_and_both() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "x.md", "base\n");
|
||||||
|
write(&a, "y.md", "base\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
write(&a, "x.md", "codex\n");
|
||||||
|
write(&a, "y.md", "codex\n");
|
||||||
|
write(&b, "x.md", "hermes\n");
|
||||||
|
write(&b, "y.md", "hermes\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
save_and_sync(&b);
|
||||||
|
|
||||||
|
// From Codex's side, "theirs" is Hermes's version (the copy).
|
||||||
|
a.sync().unwrap();
|
||||||
|
tidy::keep(&a, "x.md", Keep::Theirs).unwrap();
|
||||||
|
assert_eq!(read(&a, "x.md"), b"hermes\n");
|
||||||
|
tidy::keep(&a, "y (Hermes's version).md", Keep::Both).unwrap();
|
||||||
|
assert_eq!(read(&a, "y.md"), b"codex\n");
|
||||||
|
assert_eq!(read(&a, "y (from Hermes).md"), b"hermes\n");
|
||||||
|
assert!(tidy::list(&a).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deleted_on_one_side_edited_on_the_other_keeps_the_edit() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "note.md", ten_lines());
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
fs::remove_file(a.root.join("note.md")).unwrap();
|
||||||
|
write(&b, "note.md", ten_lines().replace("line 5", "important"));
|
||||||
|
save_and_sync(&a);
|
||||||
|
save_and_sync(&b);
|
||||||
|
a.sync().unwrap();
|
||||||
|
for v in [&a, &b] {
|
||||||
|
assert!(String::from_utf8(read(v, "note.md")).unwrap().contains("important"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_changes_queue_and_catch_up() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "seed.md", "seed\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
|
||||||
|
let hidden = w.folder("remote-away.git");
|
||||||
|
fs::rename(&w.remote, &hidden).unwrap();
|
||||||
|
for n in ["one", "two", "three"] {
|
||||||
|
write(&a, &format!("{n}.md"), format!("{n}\n"));
|
||||||
|
a.save_changes(None, &HashSet::new()).unwrap();
|
||||||
|
assert!(a.sync().is_err());
|
||||||
|
}
|
||||||
|
assert_eq!(a.waiting_files().unwrap(), 3);
|
||||||
|
|
||||||
|
fs::rename(&hidden, &w.remote).unwrap();
|
||||||
|
let report = a.sync().unwrap();
|
||||||
|
assert_eq!(report.shared, 3);
|
||||||
|
assert_eq!(a.waiting_files().unwrap(), 0);
|
||||||
|
b.sync().unwrap();
|
||||||
|
for n in ["one", "two", "three"] {
|
||||||
|
assert_eq!(read(&b, &format!("{n}.md")), format!("{n}\n").as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incoming_changes_never_overwrite_unsaved_local_edits() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "note.md", "v1\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
let b = w.device("Hermes");
|
||||||
|
write(&a, "note.md", "v2 from codex\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
|
||||||
|
write(&b, "note.md", "being typed on hermes");
|
||||||
|
let report = b.sync().unwrap();
|
||||||
|
assert!(report.waiting_for_local_edits);
|
||||||
|
assert_eq!(read(&b, "note.md"), b"being typed on hermes");
|
||||||
|
|
||||||
|
// Once the edit is saved, both versions are kept.
|
||||||
|
let report = save_and_sync(&b);
|
||||||
|
assert_eq!(report.kept_both.len(), 1);
|
||||||
|
assert_eq!(read(&b, "note.md"), b"v2 from codex\n");
|
||||||
|
assert_eq!(read(&b, "note (Hermes's version).md"), b"being typed on hermes");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn adopting_an_existing_vault_preserves_every_byte() {
|
||||||
|
let w = World::new();
|
||||||
|
let folder = w.folder("existing");
|
||||||
|
fs::create_dir_all(folder.join(".obsidian/plugins/x")).unwrap();
|
||||||
|
fs::create_dir_all(folder.join("Daily/2026")).unwrap();
|
||||||
|
fs::create_dir_all(folder.join("empty-folder-is-fine")).unwrap();
|
||||||
|
fs::write(folder.join("Home.md"), "# Home\r\n[[Daily]]").unwrap();
|
||||||
|
fs::write(folder.join("Daily/2026/10-28.md"), "today\n").unwrap();
|
||||||
|
fs::write(folder.join(".obsidian/app.json"), "{\"x\":1}").unwrap();
|
||||||
|
fs::write(folder.join(".obsidian/plugins/x/main.js"), "console.log(1)\n").unwrap();
|
||||||
|
fs::write(folder.join("photo.jpg"), [0xFFu8, 0xD8, 0x00, 0x0D, 0x0A, 0x1A]).unwrap();
|
||||||
|
let before = snapshot(&folder);
|
||||||
|
|
||||||
|
let (cfg, added, err) = vault::add("DevOps", &folder, w.remote.to_str().unwrap(), "Codex").unwrap();
|
||||||
|
assert!(matches!(added, Added::Adopted(5)));
|
||||||
|
assert_eq!(err, None);
|
||||||
|
assert_eq!(snapshot(&folder), before);
|
||||||
|
assert!(lune_core::state::read_marker(&folder.join(".git")).is_some_and(|m| !m.created_folder));
|
||||||
|
|
||||||
|
// A second device with its own notes adopts into the same remote: everything from both survives.
|
||||||
|
let other = w.folder("other");
|
||||||
|
fs::create_dir_all(&other).unwrap();
|
||||||
|
fs::write(other.join("Home.md"), "# Other home\n").unwrap();
|
||||||
|
fs::write(other.join("vps.md"), "hermes notes\n").unwrap();
|
||||||
|
let b = w.device_at("Hermes", &other);
|
||||||
|
let a = Vault::open(&cfg, "Codex").unwrap();
|
||||||
|
a.sync().unwrap();
|
||||||
|
assert_eq!(read(&b, "Home.md"), b"# Home\r\n[[Daily]]");
|
||||||
|
assert_eq!(read(&b, "Home (Hermes's version).md"), b"# Other home\n");
|
||||||
|
assert_eq!(read(&a, "vps.md"), b"hermes notes\n");
|
||||||
|
assert_eq!(read(&a, "photo.jpg"), [0xFFu8, 0xD8, 0x00, 0x0D, 0x0A, 0x1A]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checkpoint_records_a_name_even_with_nothing_new() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "a.md", "a\n");
|
||||||
|
a.checkpoint("first pass").unwrap();
|
||||||
|
a.checkpoint("reviewed").unwrap();
|
||||||
|
let head = a.head_commit().unwrap().unwrap();
|
||||||
|
assert_eq!(head.summary().unwrap().unwrap(), "reviewed");
|
||||||
|
assert_eq!(head.parent(0).unwrap().summary().unwrap().unwrap(), "first pass");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn names_differing_only_by_case_are_renamed_not_overwritten() {
|
||||||
|
let w = World::new();
|
||||||
|
let a = w.device("Codex");
|
||||||
|
write(&a, "seed.md", "seed\n");
|
||||||
|
save_and_sync(&a);
|
||||||
|
|
||||||
|
// Someone on a case-sensitive system adds Notes.md and notes.md.
|
||||||
|
let remote = Repository::open_bare(&w.remote).unwrap();
|
||||||
|
let parent = remote.find_reference("refs/heads/main").unwrap().peel_to_commit().unwrap();
|
||||||
|
let mut tb = remote.treebuilder(Some(&parent.tree().unwrap())).unwrap();
|
||||||
|
tb.insert("Notes.md", remote.blob(b"upper\n").unwrap(), 0o100644).unwrap();
|
||||||
|
tb.insert("notes.md", remote.blob(b"lower\n").unwrap(), 0o100644).unwrap();
|
||||||
|
let tree = remote.find_tree(tb.write().unwrap()).unwrap();
|
||||||
|
let sig = git2::Signature::now("Linux box", "l@x").unwrap();
|
||||||
|
remote.commit(Some("refs/heads/main"), &sig, &sig, "case", &tree, &[&parent]).unwrap();
|
||||||
|
|
||||||
|
a.repo().config().unwrap().open_level(git2::ConfigLevel::Local).unwrap().set_bool("core.ignorecase", true).unwrap();
|
||||||
|
let report = a.sync().unwrap();
|
||||||
|
assert_eq!(report.case_renamed, vec![("notes.md".into(), "notes (name clash).md".into())]);
|
||||||
|
assert_eq!(read(&a, "Notes.md"), b"upper\n");
|
||||||
|
assert_eq!(read(&a, "notes (name clash).md"), b"lower\n");
|
||||||
|
}
|
||||||
209
docs/SPEC.md
Normal file
209
docs/SPEC.md
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
# Lune — Spec
|
||||||
|
|
||||||
|
Owner: Sen · Draft 1 · 28 Oct 2026
|
||||||
|
Product name: **Lune**. CLI: `lunesync` (the name `lune` is already taken by a Luau runtime in Homebrew and crates.io).
|
||||||
|
|
||||||
|
This is the single source of truth. If the code and this document disagree, one of them is wrong — raise it with Sen, don't silently pick one.
|
||||||
|
|
||||||
|
Visual companions (Sen's private links):
|
||||||
|
- Blueprint (journeys, decisions, milestones): https://claude.ai/artifact/SRS6qmUupZEBdAdi7NL6nc
|
||||||
|
- Clickable prototype (team canvas, menu-bar app, join flow): https://claude.ai/artifact/Fu42uR9nextfov7tTiXadS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Vision
|
||||||
|
|
||||||
|
**One vault. Every copy current. Access you can take back.**
|
||||||
|
|
||||||
|
People and their AI agents keep knowledge in ordinary Markdown vaults (Obsidian-compatible folders). This app keeps every copy of a shared vault in sync, makes access easy to grant and take back, and hides all the technical work (Git, merging, keys) behind a simple, playful interface.
|
||||||
|
|
||||||
|
It started from a real problem: a DevOps vault shared with a team through a Git repo. It worked, but only for people comfortable with Git, local work sometimes never reached the team, and there was no clean way to cut off someone who left. The same problem shows up with one person's own agents: Codex on a laptop and Hermes on a VPS drifting out of sync.
|
||||||
|
|
||||||
|
### North-star test
|
||||||
|
Every feature must serve at least one of:
|
||||||
|
1. **Sync you can trust** — work reaches everyone, nothing is lost, nothing blocks.
|
||||||
|
2. **Access as a lifecycle** — grant, change and take back access cleanly.
|
||||||
|
3. **Approachable** — someone who has never heard of a vault can use it.
|
||||||
|
|
||||||
|
If a feature serves none of these, it waits.
|
||||||
|
|
||||||
|
### v1 in one sentence
|
||||||
|
Me, my agents and a small team share vaults reliably.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. How it fits together
|
||||||
|
|
||||||
|
- **Hub** — a server Sen hosts (Docker on a VM). Holds each vault as a Git repo, plus accounts, memberships, devices and the access log. Serves the web canvas.
|
||||||
|
- **Sync app** — one Rust program installed on every machine. Two modes:
|
||||||
|
- *Desktop*: menu-bar app (Tauri) for macOS, Windows, Linux.
|
||||||
|
- *Headless*: CLI + background service for servers and agent hosts.
|
||||||
|
- **Plain folders in between** — every person and agent works in a normal local folder. Obsidian, Codex, Hermes or any editor just read and write files. No plugin or agent integration is required.
|
||||||
|
- **Web canvas** — where access is managed: grant, revoke, sync health, removing someone from the team.
|
||||||
|
|
||||||
|
Repo layout (one repo, one language for logic):
|
||||||
|
```
|
||||||
|
core/ sync engine, Git, conflicts, secret check, runaway guard, hub client (Rust)
|
||||||
|
cli/ thin command layer over core (Rust)
|
||||||
|
hub/ server: accounts, memberships, devices, repos, access log (Rust)
|
||||||
|
web/ canvas UI (React), also reused inside the desktop window
|
||||||
|
desktop/ Tauri shell: tray icon + small window, calls core
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Decisions
|
||||||
|
|
||||||
|
Settled. Changing one needs Sen's explicit OK, recorded here with the date.
|
||||||
|
|
||||||
|
### Sync
|
||||||
|
| # | Decision |
|
||||||
|
|---|---|
|
||||||
|
| S1 | Git is the version layer, bundled inside the app. Users never install or see Git. No custom VCS, no CRDT. |
|
||||||
|
| S2 | Edits are shared after ~5 s with no writes, never later than ~60 s even if writing never stops. Each burst becomes one history entry. Files are only picked up once they stop changing. |
|
||||||
|
| S3 | Optional named checkpoints (`lunesync checkpoint "msg"`). Agents can be told to use them. |
|
||||||
|
| S4 | Conflicts: merge line by line when possible. Same lines changed → keep both: the incoming version stays in place, the local one is saved beside it as `name (Label's version).md`. Sync never blocks waiting for a human. |
|
||||||
|
| S5 | Offline: changes queue as local commits and go out when the network is back. |
|
||||||
|
| S6 | Runaway guard: a burst that deletes or rewrites ~20% of a vault or ~50+ notes is held for the device owner to confirm (Share anyway / Undo). Applies to every device. |
|
||||||
|
| S7 | Each history entry is labeled with the device it came from. |
|
||||||
|
|
||||||
|
### Access
|
||||||
|
| # | Decision |
|
||||||
|
|---|---|
|
||||||
|
| A1 | Three layers: **account** (a person), **membership** (access to one vault, many per person), **device** (one key per device, removable on its own). |
|
||||||
|
| A2 | No separate agent concept. Agents run on devices; devices have labels the owner chooses (e.g. laptop "Codex", VPS "Hermes"). Every device gets its owner's role. A per-device read-only switch may come later. |
|
||||||
|
| A3 | Roles per membership: **Read**, **Edit**, **Manage**. A Read member's local edits stay local with a clear "not shared, you have read access" note; files are not locked on disk. |
|
||||||
|
| A4 | One invite per person (one-time link). They add their own devices by pairing code. |
|
||||||
|
| A5 | Removing someone from a vault affects that vault only. Their account and other vaults keep working. |
|
||||||
|
| A6 | On removal: the device makes the folder read-only, runs a **final sync** of unshared changes into a **handover area** (reviewed by a manager: Keep / Discard), and only after the hub confirms receipt does it delete the folder. Offline devices do this on reconnect. A manager can force "Delete without saving". |
|
||||||
|
| A7 | "Delete from their devices" is a per-vault setting, on by default. |
|
||||||
|
| A8 | **Remove from team** is a separate, deliberate flow: team owners only, ends every membership and device, account is disabled (restorable), history keeps their name. Permanent deletion is a later admin action. |
|
||||||
|
| A9 | The app only ever deletes folders it created, verified by a marker inside `.git/`, never following links out. |
|
||||||
|
| A10 | Every access change is logged automatically by the hub. No manual checklists for external tools. |
|
||||||
|
| A11 | Known limit, always stated honestly: copies made elsewhere, or content already given to other tools, can't be recalled. |
|
||||||
|
|
||||||
|
### Safety
|
||||||
|
| # | Decision |
|
||||||
|
|---|---|
|
||||||
|
| P1 | **Pointers, not secrets.** Vaults never store credentials. Notes say where to get access ("use tsh", "search X in Secrets Manager"). |
|
||||||
|
| P2 | Secret check runs on every change before it leaves a device. A hit holds the whole note's change locally. Options: Replace with a pointer / Not a secret (remembered for that exact line). |
|
||||||
|
| P3 | The hub runs the same check and rejects pushes containing secrets (catches edits made outside the app). |
|
||||||
|
| P4 | The app never grants SSH, cloud, repo or deployment access. That stays in Teleport, IAM, secret managers, etc. |
|
||||||
|
|
||||||
|
### Distribution and updates
|
||||||
|
| # | Decision |
|
||||||
|
|---|---|
|
||||||
|
| D1 | Laptops: native installers (`.dmg`, `.exe`/`.msi`, `.AppImage`/`.deb`), downloaded from the hub's website, paired automatically after sign-in. |
|
||||||
|
| D2 | Servers: one-line install script + `lunesync login --code … --name …` + `lunesync service install`. |
|
||||||
|
| D3 | The hub decides which app version to offer; updating the hub rolls out the matching client. Updates are always signed (Tauri updater). Hub supports at least one older client version. Too-old clients keep saving locally and show "Update to keep syncing". |
|
||||||
|
| D4 | Unsigned builds are fine for an internal pilot. OS code signing before wider rollout. |
|
||||||
|
| D5 | Uninstall removes the app's vault folders. On macOS the app has its own Uninstall menu item. |
|
||||||
|
|
||||||
|
### Experience (from the prototype round)
|
||||||
|
| # | Decision |
|
||||||
|
|---|---|
|
||||||
|
| X1 | The canvas is the page: full-screen, no page scroll. Controls float on top. The details panel appears only when something is selected and the canvas shrinks to make room (bottom sheet on phones). |
|
||||||
|
| X2 | **Gestures are symmetric.** Grant = drag a vault onto a person. Revoke = pull a ribbon until it pinches and snaps. No confirmation dialog for either; revoke shows a toast with **Undo** (~8 s) and nothing reaches the person's devices until the undo window passes. Only "Remove from team" asks for confirmation. |
|
||||||
|
| X3 | Every gesture has a button alternative in the panel. |
|
||||||
|
| X4 | Ribbons are real metaballs (SVG blur + alpha-threshold "goo" filter), drawn center to center under the nodes, so ribbons and node halos merge smoothly. |
|
||||||
|
| X5 | Each vault and person has an **identity color**; ribbons fade from vault color to person color. Identity colors avoid green, amber and grey. |
|
||||||
|
| X6 | **Status colors are reserved:** green = current, amber = behind / needs a decision, grey = offline. **Red = something sensitive almost leaked** (secret caught). Nothing else uses red. |
|
||||||
|
| X7 | Hover or selection focuses a node: its ribbons and connected nodes stay bright, the rest fades. Dimmed nodes use a veil, never transparency. |
|
||||||
|
| X8 | Float (gentle bobbing, all on one shared animation clock) and Dock (tidy grid). Reduced motion: no bobbing, instant transitions. |
|
||||||
|
| X9 | Plain words everywhere. Never "commit", "push", "merge", "branch" in the UI. |
|
||||||
|
| X10 | How-to instructions appear only as a first-run onboarding card, never as permanent panel text. |
|
||||||
|
| X11 | Panels have back navigation; each view remembers where it was opened from. |
|
||||||
|
| X12 | Mobile: no mobile app in v1. The web canvas stays usable on a phone for urgent actions (revoke, nudge, remove from team). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Non-goals
|
||||||
|
|
||||||
|
Never, by design:
|
||||||
|
- Storing or managing secrets.
|
||||||
|
- Granting SSH, cloud, repo or deployment access.
|
||||||
|
- Replacing Obsidian with our own editor.
|
||||||
|
- Our own version control system.
|
||||||
|
|
||||||
|
Not in v1 (later, maybe):
|
||||||
|
- Mobile sync; Obsidian plugin; MCP access for agents; browser-only read view.
|
||||||
|
- Time-limited access; folder-level access inside a vault; SSO.
|
||||||
|
- Installable PWA; vault templates; per-device read-only switch.
|
||||||
|
- Verifying removal in external tools (Teleport, GitHub).
|
||||||
|
|
||||||
|
Also not now: security audits, CVE sweeps, release evidence, multi-arch packaging. These belong right before a real release (Milestone 7), not during the MVP.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Milestones
|
||||||
|
|
||||||
|
Four targets, seven milestones. Each ends with a story Sen acts out as a user. A milestone is done when the story works, not when the code compiles.
|
||||||
|
|
||||||
|
| Target | Milestone | Story to act out |
|
||||||
|
|---|---|---|
|
||||||
|
| A · Core + CLI | **1. My machines share one vault** | Edit a note on the laptop; Hermes reads it on the VPS. Go offline, keep editing, reconnect, it catches up. Edit the same lines on both: both versions kept. Synced through a plain Git remote, no hub. |
|
||||||
|
| | **2. It catches my mistakes** | Paste a fake AWS key: held back, replace with a pointer. Script deletes half the vault: held for confirmation, undo. Tidy a conflict from the CLI. |
|
||||||
|
| B · Hub | **3. Shared with my team** | Run the hub in Docker, invite a teammate, they pair a device with a code, the vault arrives. Label the VPS "Hermes" and see its edits labeled. |
|
||||||
|
| | **4. Access I can take back** | Remove someone from a vault: their unshared work arrives as a handover, then their copy disappears, other vaults keep working. Remove someone from the team: everything stops. All via CLI admin commands. |
|
||||||
|
| C · Web | **5. Canvas for access** | Grant by drag, revoke by pinch with undo, button alternatives, invites, device labels, Float/Dock. |
|
||||||
|
| | **6. Canvas for health and leaving** | Freshness glow and Nudge, tidy a conflict side by side, review a handover, remove from team — also from a phone. |
|
||||||
|
| D · Desktop | **7. The app normal people install** | Download from the website, pair automatically, pick a folder, tray status, compare a conflict, receive an update, uninstall cleanly. |
|
||||||
|
|
||||||
|
Only the current milestone gets detailed below. The next one is detailed when the current one is accepted.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Milestone 1 — My machines share one vault
|
||||||
|
|
||||||
|
### Goal
|
||||||
|
Sen's laptop and VPS keep one vault in sync through an ordinary Git remote (e.g. a private GitHub repo or a bare repo on the VPS). No hub, no accounts yet. This alone fixes the Codex/Hermes drift and becomes a daily-use tool immediately.
|
||||||
|
|
||||||
|
### What Sen does
|
||||||
|
```bash
|
||||||
|
# on each machine
|
||||||
|
lunesync device name Codex # or Hermes on the VPS
|
||||||
|
lunesync add DevOps ~/Vaults/DevOps --remote git@github.com:sen/devops-vault.git
|
||||||
|
lunesync run # foreground, to watch it work
|
||||||
|
lunesync service install # later: keep it running (launchd / systemd)
|
||||||
|
|
||||||
|
# anytime
|
||||||
|
lunesync status
|
||||||
|
lunesync checkpoint "updated VM list"
|
||||||
|
lunesync tidy # list notes with kept-both versions
|
||||||
|
lunesync tidy keep mine|theirs|both <file>
|
||||||
|
```
|
||||||
|
`add` on an empty folder clones; on a folder that already holds a vault, it adopts it (initial commit, then sync). Existing vaults are never reorganized.
|
||||||
|
|
||||||
|
### Behavior
|
||||||
|
- **Watch → settle → commit → sync**: file watcher; a burst ends after ~5 s of quiet or at 60 s max; only settled files are included; one commit per burst, author = device label.
|
||||||
|
- **Sync** = fetch, merge, push. Retries with backoff. Offline: commits pile up locally, `status` shows "Waiting to sync · N changes".
|
||||||
|
- **Conflicts** (S4): never leave conflict markers in files; never stop syncing. `tidy` resolves.
|
||||||
|
- **Ignore by default**: `.obsidian/workspace*.json`, `.obsidian/cache`, `.trash/`, OS junk (`.DS_Store`, `Thumbs.db`). Everything else, including binaries and other `.obsidian/` files, syncs byte-for-byte.
|
||||||
|
- **No line-ending or case rewriting.** Bytes in = bytes out. Two paths differing only by case are reported, not silently merged.
|
||||||
|
- **Marker** inside `.git/` identifies folders the app manages (needed later for safe deletion, A9).
|
||||||
|
- `status` per vault: Synced just now / Waiting N / Offline / N notes to tidy, plus last sync time.
|
||||||
|
|
||||||
|
### Tech choices (implementation defaults — record changes)
|
||||||
|
- Rust. Git via `git2` with vendored libgit2 (mature merge support, no system Git needed). `notify` for file watching. TOML config in the OS config dir.
|
||||||
|
- Credentials for the Git remote in M1: whatever the user's SSH agent / Git credential setup already provides. The hub replaces this in M3.
|
||||||
|
|
||||||
|
### Acceptance — Sen acts this out
|
||||||
|
1. Laptop edits `vm-list.md`; within ~10 s the VPS folder has it and Hermes can read it.
|
||||||
|
2. Hermes (or a script) rewrites 14 notes in a burst; history shows one entry labeled Hermes.
|
||||||
|
3. Laptop goes offline, 3 notes edited; `status` shows waiting; reconnect; VPS catches up with no action.
|
||||||
|
4. Both edit the same lines of `runbook.md` while one is offline; after sync both versions exist, nothing is lost, sync kept running; `tidy keep both|mine|theirs` cleans it up.
|
||||||
|
5. Adopting an existing Obsidian vault preserves every file and folder exactly (compare checksums before/after).
|
||||||
|
6. Obsidian open on the vault the whole time: no churn from workspace files, no broken notes.
|
||||||
|
|
||||||
|
### Out of scope for M1
|
||||||
|
Secret check and runaway guard (M2), hub/accounts/devices (M3), any UI beyond the CLI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Open questions (not blocking M1)
|
||||||
|
- Hub storage for repos: plain bare repos on disk vs. something like Gitea underneath (decide at M3).
|
||||||
|
- Secret detection rules: embed a known ruleset (gitleaks-style) vs. our own short list (decide at M2).
|
||||||
|
|
||||||
|
## 8. Decision changes
|
||||||
|
Record here: date, what changed, why, which decision number. Example:
|
||||||
|
`2026-11-02 — S2 cap raised from 60 s to 90 s: VPS bursts too chatty. (Sen)`
|
||||||
Reference in New Issue
Block a user