Files
lune/cli/src/main.rs
Adnan Zahir 62bc3db416 Milestone 2: secret check and runaway guard
Notes with a likely secret on a new line are held on the device (own
short rule list, per SPEC §8); `lunesync held pointer|not-secret`
resolves them. Bursts removing or rewriting a big part of the vault are
saved but not shared until `lunesync held share|undo`. Incoming edits
to a held note land in place with the held version kept beside it.
Adds `tidy show` and SPEC §6 detail for M2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:08:02 +07:00

489 lines
19 KiB
Rust

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::guard;
use lune_core::secrets;
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, global = true)]
vault: Option<String>,
},
/// What's held back on this device (secrets, big changes) and deciding about it
Held {
#[command(subcommand)]
action: Option<HeldCmd>,
#[arg(long, global = true)]
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 },
/// Compare the two kept versions line by line
Show { file: PathBuf },
}
#[derive(Subcommand)]
enum HeldCmd {
/// The big change was intended: share it anyway
Share,
/// The big change was a mistake: bring back everything it removed or rewrote
Undo,
/// Replace the secret in a note with a pointer to where it lives
Pointer {
file: PathBuf,
/// Where to get it, e.g. "search prod-deploy in Secrets Manager"
pointer: String,
#[arg(long)]
line: Option<usize>,
},
/// It isn't a secret; don't hold that exact line again on this device
NotSecret {
file: PathBuf,
#[arg(long)]
line: Option<usize>,
},
}
#[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::Tidy { action: Some(TidyCmd::Show { file }), vault } => {
let (cfg, rel) = locate(&config, vault.as_deref(), &cwd, &file)?;
let v = Vault::open(cfg, &config.device_label())?;
print!("{}", tidy::show(&v, &rel)?);
println!("Pick one with `lunesync tidy keep mine|theirs|both {rel}`.");
}
Command::Held { 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 h in guard::load(&v.git_dir) {
any = true;
println!(
"{}: big change held — \"{}\" removes {} and rewrites {} of {} notes.",
v.name, h.message, h.removed, h.rewritten, h.total
);
println!(" Send it: `lunesync held share` Bring everything back: `lunesync held undo`");
}
for n in v.secret_holds()? {
any = true;
for h in &n.hits {
println!("{}: {} line {} has a possible {}: {}", v.name, n.path, h.line, h.rule, h.hint);
}
println!(
" Replace it: `lunesync held pointer {} \"where to get it\"` Not a secret: `lunesync held not-secret {}`",
n.path, n.path
);
}
}
if !any {
println!("Nothing held back.");
}
}
Command::Held { action: Some(cmd), vault } => held(&config, &cwd, vault.as_deref(), cmd)?,
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 held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Result<()> {
let label = config.device_label();
match cmd {
HeldCmd::Share | HeldCmd::Undo => {
let cfg = config.pick(vault, cwd)?;
let v = Vault::open(cfg, &label)?;
let _op = state::op_lock(&v.git_dir)?;
if guard::load(&v.git_dir).is_empty() {
println!("No big change is held in {}.", v.name);
return Ok(());
}
if matches!(cmd, HeldCmd::Share) {
for h in v.share_held()? {
println!("Sharing \"{}\".", h.message);
}
} else {
let kept = v.undo_held()?;
println!("Brought everything back in {}.", v.name);
for (note, copy) in kept {
println!(" {note} was edited elsewhere meanwhile — kept both, the other version is \"{copy}\".");
}
}
share_now(&v);
}
HeldCmd::Pointer { file, pointer, line } => {
let (cfg, rel) = locate(config, vault, cwd, &file)?;
let v = Vault::open(cfg, &label)?;
let _op = state::op_lock(&v.git_dir)?;
let hits = held_hits(&v, &rel, line)?;
let path = v.root.join(&rel);
let text = std::fs::read_to_string(&path)?;
std::fs::write(&path, secrets::replace_with_pointer(&text, &hits, line, &pointer))?;
println!("Replaced {} secret{} in {rel} with \"{pointer}\".", hits.len(), if hits.len() == 1 { "" } else { "s" });
save_and_share(&v)?;
}
HeldCmd::NotSecret { file, line } => {
let (cfg, rel) = locate(config, vault, cwd, &file)?;
let v = Vault::open(cfg, &label)?;
let _op = state::op_lock(&v.git_dir)?;
for h in held_hits(&v, &rel, line)? {
secrets::allow(&v.git_dir, &h, &rel)?;
println!("OK — line {} of {rel} won't be held again on this device.", h.line);
}
save_and_share(&v)?;
}
}
Ok(())
}
fn held_hits(v: &Vault, rel: &str, line: Option<usize>) -> Result<Vec<secrets::Hit>> {
let note = v.secret_holds()?.into_iter().find(|n| n.path == rel);
let hits: Vec<secrets::Hit> = note
.map(|n| n.hits)
.unwrap_or_default()
.into_iter()
.filter(|h| line.is_none_or(|l| h.line == l))
.collect();
if hits.is_empty() {
bail!("nothing is held in {rel}{}", line.map(|l| format!(" on line {l}")).unwrap_or_default());
}
Ok(hits)
}
fn save_and_share(v: &Vault) -> Result<()> {
if v.save_changes(None, &Default::default())?.is_some_and(|s| s.held.is_some()) {
println!("That change is big enough to be held too — see `lunesync held`.");
}
if !v.secret_holds()?.is_empty() {
println!("Something else in this vault is still held — see `lunesync held`.");
}
share_now(v);
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));
}
for h in guard::load(&v.git_dir) {
println!(" Holding back a big change: \"{}\" — nothing from here is shared until you decide (`lunesync held`)", h.message);
}
let secret_notes = v.secret_holds().map(|l| l.len()).unwrap_or(0);
if secret_notes > 0 {
println!(
" {secret_notes} note{} not shared: looks like a secret (`lunesync held`)",
if secret_notes == 1 { "" } else { "s" }
);
}
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('\\', "/")))
}