0.1.6: GBrain brains — refreshed after sync, clashes never make a second page

- A vault has a kind on the hub: Obsidian (as before) or GBrain. Set it with
  `lunesync vault kind`, the canvas panel or the window; Lune suggests it when
  it finds gbrain.yml / .gbrain-source. Every change is in the access log.
- GBrain vaults: devices that have `gbrain` (looked for beyond PATH) are asked
  once whether to refresh it after sync. Lune then runs
  `gbrain sync --source <name> --no-pull` in the background after notes arrive
  or are saved; it never holds up syncing. A failed refresh turns the vault
  amber ("GBrain not refreshed") with Retry, also on the canvas.
- Clashes in GBrain vaults: lines both sides added are kept in the one note,
  incoming first. Same lines changed: the incoming version stays, this
  device's waits under Notes to tidy, stored in .git/lune/tidy (never a copy
  file GBrain would index). Applies to syncing, undo, held notes and
  handovers. Held notes moved aside stay red until decided.
- .gbrain-source is kept per device. Obsidian vaults are unchanged.
- SPEC: M8 section and decisions recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 22:55:18 +07:00
parent ac5dba46df
commit e6c3f008a0
30 changed files with 2169 additions and 101 deletions

250
core/src/brain.rs Normal file
View File

@@ -0,0 +1,250 @@
//! GBrain vaults (M8): after a sync brings notes in, tell this device's GBrain to re-read them.
//!
//! Lune does the pulling and committing; GBrain only reads committed files, so the refresh is
//! `gbrain sync --source <name> --no-pull` run in the vault folder, in the background, never holding up syncing.
use crate::config::{VaultConfig, VaultKind};
use crate::state;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
/// A refresh that runs longer than this is stopped and counts as failed (a big first index can be slow).
pub const TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// Files at a vault's root that say "this is a GBrain".
const MARKERS: [&str; 2] = ["gbrain.yml", ".gbrain-source"];
/// Folders that usually hold `gbrain`, on top of PATH: a Mac app opened from Finder and a systemd service
/// don't get the shell's PATH.
fn install_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
let env_dir = |var: &str, sub: &str| std::env::var_os(var).map(|v| PathBuf::from(v).join(sub));
if let Some(home) = dirs::home_dir() {
dirs.push(home.join(".bun/bin"));
dirs.push(home.join(".local/bin"));
dirs.push(home.join(".npm-global/bin"));
dirs.push(home.join(".volta/bin"));
dirs.push(home.join(".local/share/pnpm"));
// Node version managers put npm's global bin under the active version.
if let Ok(rd) = std::fs::read_dir(home.join(".nvm/versions/node")) {
dirs.extend(rd.flatten().map(|e| e.path().join("bin")));
}
}
dirs.extend(env_dir("BUN_INSTALL", "bin"));
dirs.extend(env_dir("npm_config_prefix", "bin"));
dirs.extend(["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin"].map(PathBuf::from));
dirs
}
/// The first `gbrain` found in `dirs`.
pub fn find_in(dirs: &[PathBuf]) -> Option<PathBuf> {
let names: &[&str] = if cfg!(windows) { &["gbrain.exe", "gbrain.cmd", "gbrain"] } else { &["gbrain"] };
dirs.iter().flat_map(|d| names.iter().map(move |n| d.join(n))).find(|p| p.is_file())
}
/// Where `gbrain` is on this device, if anywhere. `LUNE_GBRAIN` points at it explicitly (for odd installs and tests).
pub fn find_gbrain() -> Option<PathBuf> {
if let Some(p) = std::env::var_os("LUNE_GBRAIN").map(PathBuf::from).filter(|p| !p.as_os_str().is_empty()) {
return p.is_file().then_some(p);
}
find_in(&install_dirs())
}
/// The last refresh's outcome, kept in `.git/lune/gbrain.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Outcome {
pub ok: bool,
pub at: i64,
pub error: Option<String>,
}
pub fn last_outcome(git_dir: &Path) -> Option<Outcome> {
serde_json::from_str(&std::fs::read_to_string(state::lune_dir(git_dir).join("gbrain.json")).ok()?).ok()
}
fn record(git_dir: &Path, outcome: &Outcome) {
let dir = state::lune_dir(git_dir);
let _ = std::fs::create_dir_all(&dir);
if let Ok(json) = serde_json::to_vec(outcome) {
let _ = std::fs::write(dir.join("gbrain.json"), json);
}
}
pub fn is_refreshing(git_dir: &Path) -> bool {
matches!(state::gbrain_lock(git_dir, false), Ok(None))
}
/// Does the vault's root hold a file that says it's a GBrain?
pub fn looks_like_gbrain(root: &Path) -> bool {
MARKERS.iter().any(|m| root.join(m).exists())
}
fn dismissed_file(git_dir: &Path) -> PathBuf {
state::lune_dir(git_dir).join("gbrain-hint-dismissed")
}
/// Suggest marking this vault as a GBrain: it looks like one, isn't marked, and the person hasn't said no.
pub fn should_suggest(cfg: &VaultConfig, root: &Path, git_dir: &Path) -> bool {
cfg.kind == VaultKind::Obsidian && looks_like_gbrain(root) && !dismissed_file(git_dir).exists()
}
pub fn dismiss_suggestion(git_dir: &Path) -> Result<()> {
std::fs::create_dir_all(state::lune_dir(git_dir))?;
std::fs::write(dismissed_file(git_dir), "")?;
Ok(())
}
/// Runs `gbrain sync --source <name> --no-pull` once, in the vault folder, and records how it went.
/// `bin` None looks for gbrain. `wait` false gives up (returning Ok(false)) if another refresh is running.
pub fn refresh_now(cfg: &VaultConfig, bin: Option<&Path>, timeout: Duration, wait: bool) -> Result<bool> {
let git_dir = cfg.path.join(".git");
let Some(_lock) = state::gbrain_lock(&git_dir, wait)? else { return Ok(false) };
let result = run_gbrain(cfg, bin, timeout);
record(
&git_dir,
&Outcome {
ok: result.is_ok(),
at: chrono::Utc::now().timestamp(),
error: result.as_ref().err().map(|e| format!("{e:#}")),
},
);
result.map(|_| true)
}
fn run_gbrain(cfg: &VaultConfig, bin: Option<&Path>, timeout: Duration) -> Result<()> {
let bin = match bin {
Some(b) => b.to_path_buf(),
None => find_gbrain().context("the gbrain command wasn't found on this device")?,
};
let lune = state::lune_dir(&cfg.path.join(".git"));
std::fs::create_dir_all(&lune)?;
let log = std::fs::File::create(lune.join("gbrain.log"))?;
// GBrain is often a script that needs bun or node, which the app's own PATH may not include.
let mut path: Vec<PathBuf> = bin.parent().map(|p| vec![p.to_path_buf()]).unwrap_or_default();
path.extend(install_dirs());
let mut cmd = std::process::Command::new(&bin);
cmd.args(["sync", "--source", cfg.gbrain_source_name(), "--no-pull"])
.current_dir(&cfg.path)
.stdin(std::process::Stdio::null())
.stdout(log.try_clone()?)
.stderr(log);
if let Ok(joined) = std::env::join_paths(path) {
cmd.env("PATH", joined);
}
let mut child = cmd.spawn().with_context(|| format!("couldn't start {}", bin.display()))?;
let started = Instant::now();
let status = loop {
if let Some(s) = child.try_wait()? {
break s;
}
if started.elapsed() > timeout {
let _ = child.kill();
let _ = child.wait();
bail!("gbrain took too long (over {} min) and was stopped", (timeout.as_secs() / 60).max(1));
}
std::thread::sleep(Duration::from_millis(100));
};
if status.success() {
return Ok(());
}
let said = std::fs::read_to_string(lune.join("gbrain.log")).unwrap_or_default();
let last = said.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or("no message");
bail!("gbrain stopped with {status}: {}", last.chars().take(200).collect::<String>())
}
/// Vaults with a refresh running in this process; the flag means another was asked for meanwhile.
static JOBS: Mutex<Option<HashMap<PathBuf, bool>>> = Mutex::new(None);
/// Starts a refresh in the background and returns at once. If one is already running for this vault, it
/// runs once more when that finishes (no pile-up).
pub fn request(cfg: &VaultConfig) {
request_with(cfg, None, TIMEOUT)
}
pub fn request_with(cfg: &VaultConfig, bin: Option<PathBuf>, timeout: Duration) {
{
let mut jobs = JOBS.lock().unwrap_or_else(|e| e.into_inner());
let jobs = jobs.get_or_insert_with(HashMap::new);
if let Some(again) = jobs.get_mut(&cfg.path) {
*again = true;
return;
}
jobs.insert(cfg.path.clone(), false);
}
let cfg = cfg.clone();
std::thread::spawn(move || {
loop {
let _ = refresh_now(&cfg, bin.as_deref(), timeout, true);
let mut jobs = JOBS.lock().unwrap_or_else(|e| e.into_inner());
let jobs = jobs.get_or_insert_with(HashMap::new);
if jobs.get(&cfg.path) == Some(&true) {
jobs.insert(cfg.path.clone(), false);
} else {
jobs.remove(&cfg.path);
return;
}
}
});
}
/// Called after a sync brought changes in, or this device committed its own. Does nothing unless the vault is
/// a GBrain and this device turned refreshing on. Returns whether a refresh was started.
pub fn after_changes(cfg: &VaultConfig) -> bool {
if cfg.kind != VaultKind::Gbrain || cfg.gbrain_refresh != Some(true) {
return false;
}
request(cfg);
true
}
/// For the window and `lunesync status`: is the one-time question due? (GBrain vault, gbrain found, not answered.)
pub fn should_ask(cfg: &VaultConfig) -> bool {
cfg.kind == VaultKind::Gbrain && cfg.gbrain_refresh.is_none() && find_gbrain().is_some()
}
/// Sets a vault's kind on its hub (Manage or team owner) and on this device right away, so the ignore list and
/// the refresh follow without waiting for the next check-in. Only vaults on a hub have a kind to set.
pub fn set_kind(config: &mut crate::config::Config, vault: &str, kind: VaultKind) -> Result<String> {
let cfg = config.find(vault).with_context(|| format!("no vault named \"{vault}\""))?.clone();
let (Some(hub), Some(_)) = (config.hub_of(&cfg), cfg.hub_vault) else {
bail!("{} isn't on a team's hub yet — a vault's kind is kept there so every device agrees (`lunesync vault upload {}`)", cfg.name, cfg.name);
};
hub.vault_kind(&cfg.name, Some(kind), false)?;
if let Some(v) = config.vaults.iter_mut().find(|v| v.path == cfg.path) {
v.kind = kind;
}
config.save()?;
if let Ok(repo) = git2::Repository::open(&cfg.path) {
crate::vault::apply_kind_ignores(&repo, kind)?;
}
Ok(match kind {
VaultKind::Gbrain => format!("{} is now a GBrain vault.", cfg.name),
VaultKind::Obsidian => format!("{} is an Obsidian vault again.", cfg.name),
})
}
/// This device's GBrain settings for a vault: turn refreshing on or off, and/or name the source.
pub fn set_device_settings(
config: &mut crate::config::Config,
vault: &str,
refresh: Option<bool>,
source: Option<String>,
) -> Result<()> {
let name = config.find(vault).with_context(|| format!("no vault named \"{vault}\""))?.name.clone();
let v = config.vaults.iter_mut().find(|v| v.name == name).unwrap();
if v.kind != VaultKind::Gbrain {
bail!("{name} isn't a GBrain vault (`lunesync vault kind {name} gbrain`)");
}
if refresh.is_some() {
v.gbrain_refresh = refresh;
}
if let Some(s) = source {
let s = s.trim().to_string();
v.gbrain_source = (!s.is_empty() && s != v.name).then_some(s);
}
config.save()
}

View File

@@ -26,7 +26,37 @@ pub struct Config {
pub vaults: Vec<VaultConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// What a vault is for. Set on the hub so every device agrees (M8); Obsidian is how every vault behaved before.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VaultKind {
#[default]
Obsidian,
Gbrain,
}
impl VaultKind {
pub fn parse(s: &str) -> Option<VaultKind> {
match s.trim().to_ascii_lowercase().as_str() {
"obsidian" => Some(VaultKind::Obsidian),
"gbrain" => Some(VaultKind::Gbrain),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
VaultKind::Obsidian => "obsidian",
VaultKind::Gbrain => "gbrain",
}
}
pub fn is_default(&self) -> bool {
*self == VaultKind::Obsidian
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VaultConfig {
pub name: String,
pub path: PathBuf,
@@ -38,6 +68,21 @@ pub struct VaultConfig {
/// Which hub that is (ids are per hub).
#[serde(default)]
pub hub_url: Option<String>,
/// Obsidian or GBrain, as the hub last said.
#[serde(default, skip_serializing_if = "VaultKind::is_default")]
pub kind: VaultKind,
/// GBrain vaults: refresh GBrain on this device after a sync brought changes. None = not asked yet.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gbrain_refresh: Option<bool>,
/// This device's GBrain source name for the vault (default: the vault's name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gbrain_source: Option<String>,
}
impl VaultConfig {
pub fn gbrain_source_name(&self) -> &str {
self.gbrain_source.as_deref().filter(|s| !s.trim().is_empty()).unwrap_or(&self.name)
}
}
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).

View File

@@ -48,6 +48,11 @@ pub struct VaultHealth {
pub waiting: usize,
pub held_secrets: usize,
pub holding: bool,
/// GBrain vaults: the last refresh on this device failed.
pub gbrain_failed: bool,
/// GBrain vaults: notes whose version from this device waits under Notes to tidy.
#[serde(default)]
pub to_tidy: usize,
}
/// A vault this device has to hand over and leave (A6).
@@ -79,6 +84,9 @@ pub struct HubVault {
pub name: String,
pub role: String,
pub git_url: String,
/// obsidian (the default) or gbrain.
#[serde(default)]
pub kind: crate::config::VaultKind,
}
#[derive(Debug, Deserialize)]
@@ -255,6 +263,15 @@ impl HubLink {
Ok(())
}
/// Sets what a vault is for (Manage or team owner). `dismiss_suggestion` hides the "this looks like a GBrain" hint.
pub fn vault_kind(&self, vault: &str, kind: Option<crate::config::VaultKind>, dismiss_suggestion: bool) -> Result<()> {
let _: Value = self.post(
"/api/vaults/kind",
json!({"vault": vault, "kind": kind.map(|k| k.as_str()), "dismiss_suggestion": dismiss_suggestion}),
)?;
Ok(())
}
/// Tells the hub this device has handed over (`head`, if anything) and is leaving.
pub fn departure_done(&self, id: i64, head: Option<String>) -> Result<()> {
let _: Value = self.post("/api/departures/done", json!({"id": id, "head": head}))?;

View File

@@ -2,6 +2,7 @@
pub use git2;
pub mod brain;
pub mod config;
pub mod guard;
pub mod hub;

View File

@@ -1,7 +1,7 @@
//! Keeping this device in line with its hub memberships: vaults arrive, and vaults whose access ended
//! are handed over and leave (A6).
use crate::config::Config;
use crate::config::{Config, VaultKind};
use crate::hub::{self, Departure, HubLink};
use crate::secrets;
use crate::state;
@@ -94,6 +94,19 @@ fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
if let Some(vc) = config.vaults.iter().find(|v| mine(v, hv.id)) {
let v = Vault::open(vc, &label)?;
state::write_role(&v.git_dir, &hv.role)?;
vault::apply_kind_ignores(v.repo(), hv.kind)?;
if vc.kind != hv.kind {
// Re-read the settings first: the person may have changed one of this device's own meanwhile.
let mut fresh = Config::load()?;
if let Some(x) = fresh.vaults.iter_mut().find(|x| x.path == vc.path) {
x.kind = hv.kind;
fresh.save()?;
}
if let Some(x) = config.vaults.iter_mut().find(|x| mine(x, hv.id)) {
x.kind = hv.kind;
}
said.push(format!("{} is now a {} vault", hv.name, if hv.kind == VaultKind::Gbrain { "GBrain" } else { "Obsidian" }));
}
continue;
}
// A same-named vault here joins this one only when it's on this device alone and shares its history (it was
@@ -109,7 +122,9 @@ fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
let _op = state::op_lock(&v.git_dir)?;
v.relink(&hv.git_url)?;
state::write_role(&v.git_dir, &hv.role)?;
vault::apply_kind_ignores(v.repo(), hv.kind)?;
v.join_unrelated()?;
vc.kind = hv.kind;
vc.remote = hv.git_url.clone();
vc.hub_vault = Some(hv.id);
vc.hub_url = Some(h.url.clone());
@@ -131,7 +146,9 @@ fn arrive_from(config: &mut Config, h: &HubLink) -> Result<Vec<String>> {
let (mut cfg, _, err) = vault::add(&hv.name, &path, &hv.git_url, &label)?;
cfg.hub_vault = Some(hv.id);
cfg.hub_url = Some(h.url.clone());
cfg.kind = hv.kind;
state::write_role(&path.join(".git"), &hv.role)?;
vault::apply_kind_ignores(&git2::Repository::open(&path)?, hv.kind)?;
config.vaults.push(cfg);
config.save()?;
let note = if hub::can_edit(&hv.role) { String::new() } else { " (read access)".into() };
@@ -155,8 +172,12 @@ pub fn report(config: &Config) -> Result<()> {
vault_id: vc.hub_vault.unwrap(),
last_synced: state::SyncState::load(&v.git_dir).last_synced,
waiting: v.waiting_files().unwrap_or(0),
held_secrets: v.secret_holds().map(|n| n.len()).unwrap_or(0),
held_secrets: v.all_secret_holds().map(|n| n.len()).unwrap_or(0),
holding: !crate::guard::load(&v.git_dir).is_empty(),
to_tidy: crate::tidy::entries(&v.git_dir).len(),
gbrain_failed: vc.kind == VaultKind::Gbrain
&& vc.gbrain_refresh == Some(true)
&& crate::brain::last_outcome(&v.git_dir).is_some_and(|o| !o.ok),
});
}
if let Err(e) = h.report(&out) {

View File

@@ -98,6 +98,8 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
let mut was_holding = false;
let mut was_read_only = false;
let mut announced: HashSet<String> = HashSet::new();
// Set when notes changed here (this device's burst was saved, or others' arrived): GBrain vaults refresh.
let mut brain_due = false;
let leaving = state::lune_dir(&vault.git_dir).join("leaving");
let nudge = state::lune_dir(&vault.git_dir).join("nudge");
loop {
@@ -138,6 +140,7 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
match vault.save_changes(None, &skip) {
Ok(Some(saved)) => {
say(&format!("saved: {}", saved.message));
brain_due = true;
if let Some(d) = saved.held {
say(&format!(
"HELD: this change removes or rewrites {} of {} notes, so it stays on this device. \
@@ -196,6 +199,7 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
say("new changes are waiting until your current edits settle");
}
was_waiting = report.waiting_for_local_edits;
brain_due |= !report.received.is_empty();
print_report(&report, &say);
backoff = poll;
sync_at = Instant::now() + poll;
@@ -214,6 +218,18 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
say(&format!("couldn't record sync status: {e:#}"));
}
}
if brain_due {
brain_due = false;
// The settings are read fresh: the hub can change a vault's kind, and the person can turn refreshing on, while we run.
let current = crate::config::Config::load()
.ok()
.and_then(|c| c.vaults.into_iter().find(|v| v.path == cfg.path))
.unwrap_or_else(|| cfg.clone());
if crate::brain::after_changes(&current) {
say("refreshing GBrain in the background");
}
}
}
}
@@ -238,6 +254,15 @@ fn print_report(r: &SyncReport, say: &dyn Fn(&str)) {
for (note, copy) in &r.kept_both {
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
}
for note in &r.joined {
say(&format!("{note} was added to in two places — both kept, the other device's lines first"));
}
for note in &r.to_tidy {
say(&format!("{note} was changed in two places — the other version stays, yours waits under Notes to tidy"));
}
for note in &r.held_to_tidy {
say(&format!("{note} changed elsewhere while held here — your held version waits under Notes to tidy"));
}
for (note, copy) in &r.set_aside {
say(&format!("{note} changed elsewhere while held here — your held version is now \"{copy}\""));
}

View File

@@ -129,3 +129,18 @@ pub fn op_lock(git_dir: &Path) -> Result<Lock> {
}
Ok(Lock(file))
}
/// Held while GBrain is being refreshed for this vault, so two runs (the app and a command) never overlap.
/// `wait` false gives up at once if someone else holds it.
pub fn gbrain_lock(git_dir: &Path, wait: bool) -> Result<Option<Lock>> {
let file = open_lock(git_dir, "gbrain.lock")?;
if wait {
file.lock()?;
return Ok(Some(Lock(file)));
}
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()),
}
}

View File

@@ -25,6 +25,28 @@ pub struct VaultStatus {
pub secrets: Vec<HeldSecret>,
pub tidy: Vec<ToTidy>,
pub case_clashes: Vec<String>,
/// obsidian or gbrain, as the hub says.
pub kind: &'static str,
/// GBrain vaults: how keeping GBrain fresh is going on this device.
pub gbrain: Option<GbrainStatus>,
/// The vault looks like a GBrain but isn't marked as one (and the person hasn't said no).
pub suggest_gbrain: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct GbrainStatus {
/// "Refresh GBrain after sync" on this device; None = not asked yet.
pub refresh: Option<bool>,
pub source: String,
/// The gbrain command was found on this device.
pub found: bool,
/// Time to ask the one-time question.
pub ask: bool,
/// The last refresh failed: "GBrain not refreshed".
pub failed: bool,
pub error: Option<String>,
pub refreshing: bool,
pub last_refreshed: Option<i64>,
}
#[derive(Debug, Clone, Serialize)]
@@ -47,6 +69,10 @@ pub struct ToTidy {
pub note: String,
pub copy: String,
pub label: String,
/// Kept on this device only, outside the notes (GBrain vaults).
pub local: bool,
/// Kept aside because it looked like it held a secret.
pub held: bool,
}
/// The order status colours are worst-first in: one red dot outranks everything.
@@ -81,6 +107,9 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
secrets: vec![],
tidy: vec![],
case_clashes: vec![],
kind: cfg.kind.as_str(),
gbrain: None,
suggest_gbrain: false,
};
let v = match Vault::open(cfg, label) {
Ok(v) => v,
@@ -100,7 +129,7 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
.map(|h| HeldChange { message: h.message, removed: h.removed, rewritten: h.rewritten, total: h.total })
.collect();
out.secrets = v
.secret_holds()
.all_secret_holds()
.unwrap_or_default()
.into_iter()
.map(|n| HeldSecret {
@@ -111,9 +140,24 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
out.tidy = tidy::list(&v)
.unwrap_or_default()
.into_iter()
.map(|k| ToTidy { note: k.note, copy: k.copy, label: k.label })
.map(|k| ToTidy { note: k.note, copy: k.copy, label: k.label, local: k.local, held: k.held })
.collect();
out.suggest_gbrain = crate::brain::should_suggest(cfg, &v.root, &v.git_dir);
if cfg.kind == crate::config::VaultKind::Gbrain {
let last = crate::brain::last_outcome(&v.git_dir);
out.gbrain = Some(GbrainStatus {
refresh: cfg.gbrain_refresh,
source: cfg.gbrain_source_name().to_string(),
found: crate::brain::find_gbrain().is_some(),
ask: crate::brain::should_ask(cfg),
failed: cfg.gbrain_refresh == Some(true) && last.as_ref().is_some_and(|o| !o.ok),
error: last.as_ref().and_then(|o| o.error.clone()),
refreshing: crate::brain::is_refreshing(&v.git_dir),
last_refreshed: last.filter(|o| o.ok).map(|o| o.at),
});
}
let waiting = out.waiting;
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
let (level, headline) = match &st.last_error {
@@ -137,5 +181,11 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
level
};
out.headline = headline;
if out.gbrain.as_ref().is_some_and(|g| g.failed) {
if out.level == "current" {
out.level = "behind";
}
out.headline = format!("{} · GBrain not refreshed", out.headline);
}
out
}

View File

@@ -1,17 +1,103 @@
//! Notes where both versions were kept, and resolving them (`lunesync tidy`).
//!
//! Two sources. Obsidian vaults keep a clash as a copy beside the note (`name (Label's version).md`). GBrain vaults
//! never make a copy: this device's version waits in `.git/lune/tidy/<id>/` (GBrain never reads dot-folders):
//! `mine` holds its exact bytes, `meta.json` says which note, whose, when and where it came from.
use crate::names;
use crate::state;
use crate::vault::{Saved, Vault};
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// A version kept on this device only (`meta.json`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
pub id: String,
/// The note, vault-relative.
pub note: String,
/// The device whose version it is (this one).
pub label: String,
/// sync, undo, join or held.
pub source: String,
/// It's here because it looked like it held a secret (P2); it is never shared.
#[serde(default)]
pub held: bool,
/// Object ids (hex) of the note's common ancestor and of the incoming version, for reference.
pub base: Option<String>,
pub incoming: Option<String>,
pub at: i64,
}
fn store(git_dir: &Path) -> PathBuf {
state::lune_dir(git_dir).join("tidy")
}
/// Stable for the same note and the same two versions, so a round that is redone doesn't add a second entry.
pub fn entry_id(note: &str, mine: &str, incoming: &str) -> String {
let h = git2::Oid::hash_object(git2::ObjectType::Blob, format!("{note}\0{mine}\0{incoming}").as_bytes()).map(|o| o.to_string()).unwrap_or_default();
h.chars().take(16).collect()
}
/// Saves `bytes` (exactly) with its meta. The meta is written last, so a half-written entry is never listed.
pub fn put(git_dir: &Path, e: &Entry, bytes: &[u8]) -> Result<()> {
let dir = store(git_dir).join(&e.id);
std::fs::create_dir_all(&dir)?;
std::fs::write(dir.join("mine"), bytes)?;
let tmp = dir.join("meta.json.tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(e)?)?;
std::fs::rename(&tmp, dir.join("meta.json"))?;
Ok(())
}
pub fn entries(git_dir: &Path) -> Vec<Entry> {
let Ok(rd) = std::fs::read_dir(store(git_dir)) else { return vec![] };
let mut out: Vec<Entry> = rd
.flatten()
.filter_map(|d| serde_json::from_slice(&std::fs::read(d.path().join("meta.json")).ok()?).ok())
.collect();
out.sort_by(|a, b| (&a.note, a.at, &a.id).cmp(&(&b.note, b.at, &b.id)));
out
}
pub fn mine_bytes(git_dir: &Path, id: &str) -> Result<Vec<u8>> {
std::fs::read(store(git_dir).join(id).join("mine")).with_context(|| "that version isn't kept on this device any more")
}
pub fn remove(git_dir: &Path, id: &str) {
if id.is_empty() || id.contains(['/', '\\', '.']) {
return;
}
let _ = std::fs::remove_dir_all(store(git_dir).join(id));
}
#[derive(Debug, Clone, PartialEq)]
pub struct KeptBoth {
pub note: String,
/// Obsidian: the copy's path. GBrain: `.git/lune/tidy/<id>`, never a file in the vault.
pub copy: String,
/// Device whose version was saved beside the note.
pub label: String,
/// Kept on this device only, outside the vault's files (GBrain).
pub local: bool,
/// Kept because it looked like it held a secret.
pub held: bool,
}
impl KeptBoth {
/// The kept version is this device's.
pub fn is_mine(&self, vault: &Vault) -> bool {
self.local || self.label.eq_ignore_ascii_case(&vault.label)
}
fn id(&self) -> Option<&str> {
self.copy.strip_prefix(LOCAL_PREFIX).filter(|_| self.local)
}
}
const LOCAL_PREFIX: &str = ".git/lune/tidy/";
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Keep {
Mine,
@@ -24,8 +110,15 @@ pub fn list(vault: &Vault) -> Result<Vec<KeptBoth>> {
.tracked_files()?
.into_iter()
.filter(|p| vault.root.join(p).exists())
.filter_map(|copy| names::parse_copy(&copy).map(|(note, label)| KeptBoth { note, copy, label }))
.filter_map(|copy| names::parse_copy(&copy).map(|(note, label)| KeptBoth { note, copy, label, local: false, held: false }))
.collect();
out.extend(entries(&vault.git_dir).into_iter().map(|e| KeptBoth {
copy: format!("{LOCAL_PREFIX}{}", e.id),
note: e.note,
label: e.label,
local: true,
held: e.held,
}));
out.sort_by(|a, b| (&a.note, &a.copy).cmp(&(&b.note, &b.copy)));
Ok(out)
}
@@ -47,7 +140,44 @@ pub fn keep(vault: &Vault, file: &str, choice: Keep) -> Result<Option<Saved>> {
bail!("{file} has several kept versions — name the one you mean: {}", copies.join(", "))
}
};
if pairs.iter().any(|k| k.local) && choice != Keep::Theirs {
// Writing a version over the note must not cost anything typed since the last save, or a held change.
if vault.secret_holds()?.iter().any(|h| h.path == note) {
bail!("{note} has a change held back for a possible secret — decide that first (`lunesync held`)");
}
vault.save_unguarded(Some(&format!("Saved {note} before tidying")))?;
}
for k in pairs {
if let Some(id) = k.id() {
let mine = mine_bytes(&vault.git_dir, id)?;
let original = vault.root.join(&k.note);
match choice {
Keep::Theirs => {}
Keep::Mine => {
if let Some(dir) = original.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(&original, &mine)?;
}
Keep::Both => {
// This device's version goes after the one in place, clearly set apart, in the same note.
let mut text = std::fs::read(&original).unwrap_or_default();
if !text.is_empty() {
if !text.ends_with(b"\n") {
text.push(b'\n');
}
text.extend_from_slice(format!("\n---\n\n_Kept from {}'s version of this note:_\n\n", k.label).as_bytes());
}
text.extend_from_slice(&mine);
if let Some(dir) = original.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(&original, text)?;
}
}
remove(&vault.git_dir, id);
continue;
}
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);
@@ -67,6 +197,16 @@ pub fn keep(vault: &Vault, file: &str, choice: Keep) -> Result<Option<Saved>> {
vault.save_unguarded(Some(&format!("Tidied {note}")))
}
/// The two versions of one kept pair as bytes: (the note in place, the kept one).
pub fn versions(vault: &Vault, k: &KeptBoth) -> Result<(Option<Vec<u8>>, Vec<u8>)> {
let note = std::fs::read(vault.root.join(&k.note)).ok();
let kept = match k.id() {
Some(id) => mine_bytes(&vault.git_dir, id)?,
None => std::fs::read(vault.root.join(&k.copy))?,
};
Ok((note, kept))
}
/// Line-by-line comparison of a note and its kept copy: `-` only in the note, `+` only in the copy.
pub fn show(vault: &Vault, file: &str) -> Result<String> {
let all = list(vault)?;
@@ -76,12 +216,13 @@ pub fn show(vault: &Vault, file: &str) -> Result<String> {
bail!("{file} has no kept-both versions to compare");
}
for k in pairs {
let note = std::fs::read(vault.root.join(&k.note)).unwrap_or_default();
let copy = std::fs::read(vault.root.join(&k.copy))?;
let (note, copy) = versions(vault, k)?;
let (note, copy) = (note.unwrap_or_default(), copy);
let whose = |copy_side: bool| {
if k.label.eq_ignore_ascii_case(&vault.label) == copy_side { "yours" } else { "theirs" }
if k.is_mine(vault) == copy_side { "yours" } else { "theirs" }
};
out.push_str(&format!("- {} ({})\n+ {} ({})\n", k.note, whose(false), k.copy, whose(true)));
let kept_name = if k.local { "this device's version, kept aside".to_string() } else { k.copy.clone() };
out.push_str(&format!("- {} ({})\n+ {} ({})\n", k.note, whose(false), kept_name, whose(true)));
let patch = git2::Patch::from_buffers(&note, None, &copy, None, None)?;
if patch.num_hunks() == 0 {
out.push_str(" (identical)\n");
@@ -101,3 +242,37 @@ pub fn show(vault: &Vault, file: &str) -> Result<String> {
}
Ok(out)
}
/// A held version kept aside (GBrain): the entry and the lines that look like secrets, if `path` has one.
pub fn held_aside_hits(vault: &Vault, path: &str, line: Option<usize>) -> Result<Option<(Entry, Vec<crate::secrets::Hit>)>> {
let allowed = crate::secrets::load_allowed(&vault.git_dir);
for e in entries(&vault.git_dir).into_iter().filter(|e| e.held && e.note == path) {
let bytes = mine_bytes(&vault.git_dir, &e.id)?;
let hits: Vec<_> = crate::secrets::scan_bytes(&bytes, None, &allowed).into_iter().filter(|h| line.is_none_or(|l| h.line == l)).collect();
if !hits.is_empty() {
return Ok(Some((e, hits)));
}
}
Ok(None)
}
/// "Replace with a pointer" for a held version kept aside: the secret goes from the stored copy. It then waits as an
/// ordinary note to tidy (nothing in it is held any more).
pub fn replace_held_aside(vault: &Vault, entry: &Entry, hits: &[crate::secrets::Hit], line: Option<usize>, pointer: &str) -> Result<()> {
let text = String::from_utf8(mine_bytes(&vault.git_dir, &entry.id)?)?;
let new = crate::secrets::replace_with_pointer(&text, hits, line, pointer);
let mut e = entry.clone();
e.held = crate::secrets::scan_bytes(new.as_bytes(), None, &crate::secrets::load_allowed(&vault.git_dir)).iter().any(|_| true);
put(&vault.git_dir, &e, new.as_bytes())
}
/// "Not a secret" for a held version kept aside: the lines are remembered, and it waits as an ordinary note to tidy.
pub fn allow_held_aside(vault: &Vault, entry: &Entry, hits: &[crate::secrets::Hit]) -> Result<()> {
for h in hits {
crate::secrets::allow(&vault.git_dir, h, &entry.note)?;
}
let bytes = mine_bytes(&vault.git_dir, &entry.id)?;
let mut e = entry.clone();
e.held = !crate::secrets::scan_bytes(&bytes, None, &crate::secrets::load_allowed(&vault.git_dir)).is_empty();
put(&vault.git_dir, &e, &bytes)
}

View File

@@ -1,6 +1,6 @@
//! 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::config::{VaultConfig, VaultKind};
use crate::guard::{self, Damage, HeldBurst};
use crate::names;
use crate::remote;
@@ -9,9 +9,9 @@ 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,
AutotagOption, Commit, ConfigLevel, Direction, ErrorCode, FetchOptions, FileFavor, FileMode, IndexAddOption,
IndexEntry, MergeFileInput, MergeFileOptions, Oid, PushOptions, Repository, RepositoryInitOptions, Signature, Sort,
StatusOptions, TreeWalkMode, TreeWalkResult,
};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashSet};
@@ -27,6 +27,12 @@ const DEFAULT_IGNORES: &str = "\
Thumbs.db
";
/// Added for GBrain vaults only: GBrain's per-device source pin must not be shared.
const GBRAIN_IGNORES: &str = "\
# lune gbrain
.gbrain-source
";
/// 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";
@@ -36,6 +42,8 @@ pub struct Vault {
pub git_dir: PathBuf,
pub branch: String,
pub label: String,
/// The kind from the settings this vault was opened with; `kind()` also looks at what the hub last said.
cfg_kind: VaultKind,
repo: Repository,
last_refusal: RefCell<Option<String>>,
}
@@ -66,6 +74,15 @@ pub struct SyncReport {
pub from: BTreeSet<String>,
/// (note, copy saved beside it) for every same-lines clash.
pub kept_both: Vec<(String, String)>,
/// GBrain vaults: notes both sides added lines to in the same spot; both kept, incoming first.
pub joined: Vec<String>,
/// GBrain vaults: notes changed in the same lines on both sides. The incoming one stays; this device's version
/// waits under Notes to tidy.
pub to_tidy: Vec<String>,
/// GBrain vaults: held notes whose held version moved to Notes to tidy so an update could land.
pub held_to_tidy: Vec<String>,
/// Tidy-store entries this round wrote, so a round that didn't land can take them back.
tidy_ids: Vec<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.
@@ -92,11 +109,21 @@ impl Vault {
root,
branch: cfg.branch.clone(),
label: label.to_string(),
cfg_kind: cfg.kind,
repo,
last_refusal: RefCell::new(None),
})
}
/// Obsidian or GBrain, read fresh each time: the hub can change it while a runner is going, and the answer
/// decides whether a clash makes a second note (Obsidian) or never does (GBrain).
pub fn kind(&self) -> VaultKind {
std::fs::read_to_string(state::lune_dir(&self.git_dir).join("kind"))
.ok()
.and_then(|s| VaultKind::parse(&s))
.unwrap_or(self.cfg_kind)
}
pub fn repo(&self) -> &Repository {
&self.repo
}
@@ -243,6 +270,32 @@ impl Vault {
Ok(out)
}
/// GBrain vaults: held notes whose held version waits on this device (outside the folder) because an update had
/// to land. They are still held (P2): never shared, and they count wherever a held note counts.
pub fn held_aside(&self) -> Result<Vec<SecretNote>> {
let allowed = secrets::load_allowed(&self.git_dir);
let mut out: Vec<SecretNote> = vec![];
for e in crate::tidy::entries(&self.git_dir).into_iter().filter(|e| e.held) {
let bytes = crate::tidy::mine_bytes(&self.git_dir, &e.id)?;
let hits = secrets::scan_bytes(&bytes, None, &allowed);
if !hits.is_empty() && !out.iter().any(|n| n.path == e.note) {
out.push(SecretNote { path: e.note, hits });
}
}
Ok(out)
}
/// Every note held for a possible secret on this device: in the folder, or kept aside.
pub fn all_secret_holds(&self) -> Result<Vec<SecretNote>> {
let mut out = self.secret_holds()?;
for n in self.held_aside()? {
if !out.iter().any(|o| o.path == n.path) {
out.push(n);
}
}
Ok(out)
}
/// Owner says the held big change was intended: share it.
pub fn share_held(&self) -> Result<Vec<HeldBurst>> {
let held = guard::load(&self.git_dir);
@@ -252,14 +305,14 @@ impl Vault {
/// Owner says the held big change was a mistake: bring back exactly what it removed or rewrote.
/// Notes edited elsewhere meanwhile keep both versions. The caller holds the op lock.
pub fn undo_held(&self) -> Result<Vec<(String, String)>> {
pub fn undo_held(&self) -> Result<Clashes> {
let held = guard::load(&self.git_dir);
let mut kept_both = vec![];
let mut clashes = Clashes::default();
for h in held.iter().rev() {
let burst = self.repo.find_commit(Oid::from_str(&h.id)?)?;
let head = self.head_commit()?.context("nothing to undo")?;
let mut index = self.repo.revert_commit(&burst, &head, 0, None)?;
self.keep_both(&mut index, &mut kept_both)?;
clashes.absorb(self.keep_both(&mut index, "undo")?);
let reverted = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
// Notes the burst added stay: undo only brings back what it removed or rewrote.
let added = self.repo.diff_tree_to_tree(Some(&burst.parent(0)?.tree()?), Some(&burst.tree()?), None)?;
@@ -287,7 +340,7 @@ impl Vault {
})?;
}
guard::save(&self.git_dir, &[])?;
Ok(kept_both)
Ok(clashes)
}
/// Points the vault at a new remote (e.g. moving onto the hub). Its next sync shares everything there.
@@ -376,8 +429,7 @@ impl Vault {
return Ok(false);
}
let mut index = self.repo.merge_commits(&local, &remote, None)?;
let mut kept = vec![];
self.keep_both(&mut index, &mut kept)?;
self.keep_both(&mut index, "join")?;
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, &format!("Joined the shared copy from {}", self.label), &tree, &[&remote])?;
@@ -540,6 +592,13 @@ impl Vault {
match self.move_to(target) {
Ok(()) => {}
Err(e) if e.code() == ErrorCode::Conflict => {
// Nothing landed, so the next round combines again; take back what this one kept aside.
for id in report.tidy_ids.drain(..) {
crate::tidy::remove(&self.git_dir, &id);
}
report.to_tidy.clear();
report.joined.clear();
report.kept_both.clear();
report.waiting_for_local_edits = true;
return Ok(report);
}
@@ -579,24 +638,68 @@ impl Vault {
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).
/// Combines two lines of history. Same-lines clashes keep both (S4): Obsidian vaults put the incoming one in place
/// and ours beside it; GBrain vaults never make a second note (see `keep_both`).
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
let mut index = self.repo.merge_commits(local, incoming, None)?;
self.keep_both(&mut index, &mut report.kept_both)?;
let c = self.keep_both(&mut index, "sync")?;
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();
if !c.copies.is_empty() {
let notes: Vec<&str> = c.copies.iter().map(|(n, _)| n.as_str()).collect();
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
}
if !c.joined.is_empty() {
message.push_str(&format!(" · lines added in both places to {}", c.joined.join(", ")));
}
if !c.to_tidy.is_empty() {
message.push_str(&format!(" · changed in both places: {}", c.to_tidy.join(", ")));
}
report.kept_both.extend(c.copies);
report.joined.extend(c.joined);
report.to_tidy.extend(c.to_tidy);
report.tidy_ids.extend(c.tidy_ids);
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
}
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it (S4).
fn keep_both(&self, index: &mut git2::Index, kept_both: &mut Vec<(String, String)>) -> Result<()> {
keep_both(index, &self.label, kept_both)
/// Resolves every clash in `index` without markers. `source` says where it came from (sync, undo, join).
/// Obsidian: their version in place, ours beside it (S4). GBrain: see the free `keep_both`; versions that
/// wait go into this device's tidy store before anything is written to the folder.
fn keep_both(&self, index: &mut git2::Index, source: &str) -> Result<Clashes> {
let style = match self.kind() {
VaultKind::Gbrain => ClashStyle::Gbrain,
VaultKind::Obsidian => ClashStyle::Copies { label: &self.label },
};
let mut out = Clashes::default();
for k in keep_both(&self.repo, index, style)? {
match k {
Kept::Copied { note, copy } => out.copies.push((note, copy)),
Kept::Joined { note } => out.joined.push(note),
Kept::Aside { note, ours, theirs, base } => {
let bytes = self.repo.find_blob(ours)?.content().to_vec();
let id = crate::tidy::entry_id(&note, &ours.to_string(), &theirs.to_string());
crate::tidy::put(
&self.git_dir,
&crate::tidy::Entry {
id: id.clone(),
note: note.clone(),
label: self.label.clone(),
source: source.into(),
held: false,
base: base.map(|b| b.to_string()),
incoming: Some(theirs.to_string()),
at: chrono::Utc::now().timestamp(),
},
&bytes,
)?;
out.tidy_ids.push(id);
out.to_tidy.push(note);
}
}
}
Ok(out)
}
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
@@ -689,6 +792,32 @@ impl Vault {
if current == incoming {
continue;
}
if self.kind() == VaultKind::Gbrain {
// No second note in a GBrain vault: the held version waits on this device, outside the folder. It
// isn't shared; "keep mine" in Notes to tidy puts it back and the secret check holds it again.
let bytes = std::fs::read(self.root.join(p))?;
let id = crate::tidy::entry_id(&note.path, &Oid::hash_object(git2::ObjectType::Blob, &bytes)?.to_string(), &incoming.map(|i| i.to_string()).unwrap_or_default());
crate::tidy::put(
&self.git_dir,
&crate::tidy::Entry {
id,
note: note.path.clone(),
label: self.label.clone(),
source: "held".into(),
held: true,
base: current.map(|c| c.to_string()),
incoming: incoming.map(|i| i.to_string()),
at: chrono::Utc::now().timestamp(),
},
&bytes,
)?;
match current {
Some(id) => std::fs::write(self.root.join(p), self.repo.find_blob(id)?.content())?,
None => std::fs::remove_file(self.root.join(p))?,
}
report.held_to_tidy.push(note.path);
continue;
}
let copy = (1..)
.map(|n| names::copy_name(&note.path, &self.label, n))
.find(|c| !self.root.join(c).exists() && target_tree.get_path(Path::new(c)).is_err())
@@ -744,36 +873,185 @@ impl Vault {
}
}
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it labeled
/// with `label` (S4). Used for syncing, undo, and keeping handovers on the hub.
pub fn keep_both(index: &mut git2::Index, label: &str, kept_both: &mut Vec<(String, String)>) -> Result<()> {
if index.has_conflicts() {
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
for c in conflicts {
for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() {
let _ = index.conflict_remove(&names::bytes_path(&e.path));
}
match (c.our, c.their) {
(Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => {
let note = String::from_utf8_lossy(&theirs.path).into_owned();
let copy = (1..)
.map(|n| names::copy_name(&note, 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())))?;
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))?;
/// How a clash is resolved.
#[derive(Clone, Copy)]
pub enum ClashStyle<'a> {
/// Obsidian: their version in place, ours beside it labeled with this device (S4).
Copies { label: &'a str },
/// GBrain: never a second note. Lines both sides added in the same spot are all kept, theirs first; a file
/// where the same lines changed keeps their version in place and reports ours as `Aside`.
Gbrain,
}
/// What `keep_both` did with one clash.
#[derive(Debug, Clone)]
pub enum Kept {
Copied { note: String, copy: String },
Joined { note: String },
/// Ours was not written to the index; the caller keeps it (the blob `ours`) somewhere outside the vault's files.
Aside { note: String, ours: Oid, theirs: Oid, base: Option<Oid> },
}
/// What a resolution did, for the sync report and the undo result.
#[derive(Debug, Default)]
pub struct Clashes {
/// (note, copy beside it): Obsidian vaults.
pub copies: Vec<(String, String)>,
pub joined: Vec<String>,
pub to_tidy: Vec<String>,
tidy_ids: Vec<String>,
}
impl Clashes {
pub fn len(&self) -> usize {
self.copies.len() + self.joined.len() + self.to_tidy.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn absorb(&mut self, o: Clashes) {
self.copies.extend(o.copies);
self.joined.extend(o.joined);
self.to_tidy.extend(o.to_tidy);
self.tidy_ids.extend(o.tidy_ids);
}
}
/// Resolves every clash in `index` without markers (S4). Used for syncing, undo, joining, and keeping handovers
/// on the hub. In a conflict "ours" is this side, "theirs" the incoming one.
///
/// GBrain, per file (not per hunk, so the result is predictable): if every conflicting hunk is insert-only on both
/// sides, all lines are kept, incoming first. If any hunk changed existing lines, or the note was made on both
/// sides, or isn't text, the whole file follows "same lines changed": incoming in place, ours returned as `Aside`.
pub fn keep_both(repo: &Repository, index: &mut git2::Index, style: ClashStyle) -> Result<Vec<Kept>> {
let mut out = vec![];
if !index.has_conflicts() {
return Ok(out);
}
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.ancestor, c.our, c.their) {
(base, Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => {
let note = String::from_utf8_lossy(&theirs.path).into_owned();
match style {
ClashStyle::Copies { label } => {
let copy = (1..)
.map(|n| names::copy_name(&note, 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())))?;
out.push(Kept::Copied { note, copy });
}
ClashStyle::Gbrain => {
let joined = match &base {
Some(b) => join_insertions(
repo.find_blob(b.id)?.content(),
repo.find_blob(theirs.id)?.content(),
repo.find_blob(ours.id)?.content(),
),
None => None,
};
match joined {
Some(bytes) => {
let mut e = stage0(&theirs, None);
e.id = repo.blob(&bytes)?;
e.file_size = bytes.len() as u32;
index.add(&e)?;
out.push(Kept::Joined { note });
}
None => {
index.add(&stage0(&theirs, None))?;
out.push(Kept::Aside { note, ours: ours.id, theirs: theirs.id, base: base.map(|b| b.id) });
}
}
}
}
}
// 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))?;
}
}
}
}
Ok(())
Ok(out)
}
/// All lines both sides added in the same spots, kept: `incoming` first, then `local`. None if any hunk changed
/// existing lines (or the text isn't text), so the caller treats the file as "same lines changed".
fn join_insertions(base: &[u8], incoming: &[u8], local: &[u8]) -> Option<Vec<u8>> {
if [base, incoming, local].iter().any(|b| b.contains(&0)) {
return None;
}
// A missing last newline would make "appended a line" look like "changed the last line".
let norm = |b: &[u8]| {
let mut v = b.to_vec();
if !v.is_empty() && !v.ends_with(b"\n") {
v.push(b'\n');
}
v
};
let no_eol = |b: &[u8]| !b.ends_with(b"\n");
let strip = no_eol(base) && no_eol(incoming) && no_eol(local);
let (b, i, l) = (norm(base), norm(incoming), norm(local));
fn input(bytes: &[u8]) -> MergeFileInput<'_> {
let mut x = MergeFileInput::new();
x.content(bytes);
x
}
const MARK: usize = 40;
let mut opts = MergeFileOptions::new();
opts.style_diff3(true).marker_size(MARK as u16);
let first = git2::merge_file(&input(&b), &input(&i), &input(&l), Some(&mut opts)).ok()?;
if !first.is_automergeable() {
// diff3 style: <<<<<<< ours · ||||||| base · ======= theirs · >>>>>>>. A block with nothing between the
// base marker and the divider is insert-only on both sides.
let m = |c: char| c.to_string().repeat(MARK);
let (open, bar, mid, close) = (m('<'), m('|'), m('='), m('>'));
let mut state = 0; // 0 outside, 1 ours, 2 base, 3 theirs
let mut base_lines = 0;
for line in first.content().split_inclusive(|&c| c == b'\n') {
let line = String::from_utf8_lossy(line);
let at = |marker: &String| line.starts_with(marker.as_str()) && line[marker.len()..].chars().next().is_none_or(|c| c == ' ' || c == '\n' || c == '\r');
if state == 0 && at(&open) {
state = 1;
base_lines = 0;
} else if state == 1 && at(&bar) {
state = 2;
} else if (state == 1 || state == 2) && at(&mid) {
if state == 2 && base_lines > 0 {
return None;
}
state = 3;
} else if state == 3 && at(&close) {
state = 0;
} else if state == 2 {
base_lines += 1;
}
}
if state != 0 {
return None;
}
// A block with no base section at all (not even the marker) can't happen in diff3 style, but be safe.
if !first.content().windows(MARK + 1).any(|w| w[..MARK].iter().all(|&c| c == b'|')) {
return None;
}
}
let mut opts = MergeFileOptions::new();
opts.favor(FileFavor::Union);
let merged = git2::merge_file(&input(&b), &input(&i), &input(&l), Some(&mut opts)).ok()?;
let mut bytes = merged.content().to_vec();
if strip && bytes.ends_with(b"\n") {
bytes.pop();
}
Some(bytes)
}
fn blob_ids(tree: Option<&git2::Tree>) -> HashSet<Oid> {
@@ -876,7 +1154,7 @@ pub fn add(name: &str, path: &Path, remote_url: &str, label: &str) -> Result<(Va
state::write_marker(&git_dir, name, !existed)?;
drop(repo);
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None, hub_url: None };
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None, hub_url: None, ..Default::default() };
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())?;
@@ -933,3 +1211,27 @@ pub fn configure(repo: &Repository) -> Result<()> {
}
Ok(())
}
/// Makes the vault's default ignore list match its kind: GBrain vaults also leave out `.gbrain-source` (a
/// per-device pin; `gbrain.yml` stays shared). Safe to call as often as you like.
pub fn apply_kind_ignores(repo: &Repository, kind: crate::config::VaultKind) -> Result<()> {
// Read at clash time by `Vault::kind`, so a change the hub made while a runner is going still counts.
let lune = state::lune_dir(repo.path());
std::fs::create_dir_all(&lune)?;
if std::fs::read_to_string(lune.join("kind")).ok().as_deref() != Some(kind.as_str()) {
std::fs::write(lune.join("kind"), kind.as_str())?;
}
let info = repo.path().join("info");
std::fs::create_dir_all(&info)?;
let exclude = info.join("exclude");
let current = std::fs::read_to_string(&exclude).unwrap_or_default();
let has = current.contains(GBRAIN_IGNORES);
let gbrain = kind == crate::config::VaultKind::Gbrain;
if gbrain && !has {
let sep = if current.is_empty() || current.ends_with('\n') { "" } else { "\n" };
std::fs::write(&exclude, format!("{current}{sep}{GBRAIN_IGNORES}"))?;
} else if !gbrain && has {
std::fs::write(&exclude, current.replace(GBRAIN_IGNORES, ""))?;
}
Ok(())
}

237
core/tests/brain.rs Normal file
View File

@@ -0,0 +1,237 @@
//! GBrain vaults (M8): the refresh after sync, with a fake `gbrain` that records what it was asked and can fail or hang.
use lune_core::brain;
use lune_core::config::{Config, VaultConfig, VaultKind};
use lune_core::runner::{self, Timing};
use lune_core::vault::{self, Vault};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tempfile::TempDir;
/// A `gbrain` that logs "<folder> <args>" and fails if `fail` exists beside it, or hangs if `hang` does.
fn fake_gbrain(dir: &Path) -> (PathBuf, PathBuf) {
fs::create_dir_all(dir).unwrap();
let (bin, log) = (dir.join("gbrain"), dir.join("calls.log"));
fs::write(
&bin,
format!(
"#!/bin/sh\necho \"$PWD $*\" >> '{log}'\n[ -e '{d}/hang' ] && exec sleep 30\n[ -e '{d}/fail' ] && {{ echo 'database is locked' >&2; exit 3; }}\nexit 0\n",
log = log.display(),
d = dir.display()
),
)
.unwrap();
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap();
(bin, log)
}
fn calls(log: &Path) -> Vec<String> {
fs::read_to_string(log).unwrap_or_default().lines().map(String::from).collect()
}
fn wait_for(what: &str, secs: u64, mut ok: impl FnMut() -> bool) {
let until = Instant::now() + Duration::from_secs(secs);
while !ok() {
assert!(Instant::now() < until, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(50));
}
}
fn add(remote: &Path, folder: &Path, label: &str, kind: VaultKind) -> VaultConfig {
let (mut cfg, _, err) = vault::add("Brain", folder, remote.to_str().unwrap(), label).unwrap();
assert_eq!(err, None);
cfg.kind = kind;
vault::apply_kind_ignores(&git2::Repository::open(&cfg.path).unwrap(), kind).unwrap();
cfg
}
fn bare(dir: &Path, name: &str) -> PathBuf {
let p = dir.join(name);
git2::Repository::init_bare(&p).unwrap();
p
}
#[test]
fn pin_file_stays_home_and_the_shared_file_travels() {
let tmp = TempDir::new().unwrap();
let remote = bare(tmp.path(), "r.git");
let gb = add(&remote, &tmp.path().join("gb"), "Codex", VaultKind::Gbrain);
let v = Vault::open(&gb, "Codex").unwrap();
fs::write(v.root.join(".gbrain-source"), "brain\n").unwrap();
fs::write(v.root.join("gbrain.yml"), "database: x\n").unwrap();
assert!(brain::looks_like_gbrain(&v.root));
v.save_changes(None, &HashSet::new()).unwrap();
assert_eq!(v.tracked_files().unwrap(), vec!["gbrain.yml".to_string()]);
// An Obsidian vault is untouched: the file is shared like any other, and Lune suggests marking it.
let remote2 = bare(tmp.path(), "r2.git");
let ob = add(&remote2, &tmp.path().join("ob"), "Codex", VaultKind::Obsidian);
let o = Vault::open(&ob, "Codex").unwrap();
fs::write(o.root.join(".gbrain-source"), "brain\n").unwrap();
o.save_changes(None, &HashSet::new()).unwrap();
assert_eq!(o.tracked_files().unwrap(), vec![".gbrain-source".to_string()]);
assert!(brain::should_suggest(&ob, &o.root, &o.git_dir));
brain::dismiss_suggestion(&o.git_dir).unwrap();
assert!(!brain::should_suggest(&ob, &o.root, &o.git_dir));
assert!(!brain::should_suggest(&gb, &v.root, &v.git_dir), "already marked");
}
#[test]
fn gbrain_is_found_beyond_the_shell_path() {
let tmp = TempDir::new().unwrap();
let (bin, _) = fake_gbrain(&tmp.path().join("bun/bin"));
let dirs = vec![tmp.path().join("nothing"), tmp.path().join("bun/bin")];
assert_eq!(brain::find_in(&dirs), Some(bin));
assert_eq!(brain::find_in(&dirs[..1]), None);
}
#[test]
fn kind_and_device_settings_live_in_the_config_file() {
let c: Config = toml::from_str("[[vault]]\nname = \"Old\"\npath = \"/x\"\nremote = \"\"\nbranch = \"main\"\n").unwrap();
assert_eq!(c.vaults[0].kind, VaultKind::Obsidian, "vaults from before stay Obsidian");
let mut v = c.vaults[0].clone();
v.kind = VaultKind::Gbrain;
v.gbrain_refresh = Some(true);
v.gbrain_source = Some("brain-vps".into());
let text = toml::to_string_pretty(&Config { vaults: vec![v], ..Default::default() }).unwrap();
let back: Config = toml::from_str(&text).unwrap();
assert_eq!(back.vaults[0].kind, VaultKind::Gbrain);
assert_eq!(back.vaults[0].gbrain_refresh, Some(true));
assert_eq!(back.vaults[0].gbrain_source_name(), "brain-vps");
assert_eq!(c.vaults[0].gbrain_source_name(), "Old");
}
#[test]
fn refresh_uses_the_source_and_no_pull_fails_plainly_and_retry_clears_it() {
let tmp = TempDir::new().unwrap();
let remote = bare(tmp.path(), "r.git");
let mut cfg = add(&remote, &tmp.path().join("brain"), "Hermes", VaultKind::Gbrain);
cfg.gbrain_refresh = Some(true);
cfg.gbrain_source = Some("hermes-brain".into());
let (bin, log) = fake_gbrain(&tmp.path().join("bin"));
let secs = Duration::from_secs(20);
assert!(brain::refresh_now(&cfg, Some(&bin), secs, true).unwrap());
let said = calls(&log);
assert_eq!(said.len(), 1);
let (folder, args) = said[0].split_once(' ').unwrap();
assert_eq!(fs::canonicalize(folder).unwrap(), fs::canonicalize(&cfg.path).unwrap(), "runs in the vault folder");
assert_eq!(args, "sync --source hermes-brain --no-pull");
let st = lune_core::status::of(&cfg, "Hermes");
assert!(!st.gbrain.unwrap().failed);
// It breaks: amber with the plain words, and the reason.
fs::write(tmp.path().join("bin/fail"), "").unwrap();
assert!(brain::refresh_now(&cfg, Some(&bin), secs, true).is_err());
let st = lune_core::status::of(&cfg, "Hermes");
assert_eq!(st.level, "behind");
assert!(st.headline.contains("GBrain not refreshed"), "{}", st.headline);
let g = st.gbrain.unwrap();
assert!(g.failed && g.error.unwrap().contains("database is locked"));
// Retry once it's fixed clears it.
fs::remove_file(tmp.path().join("bin/fail")).unwrap();
assert!(brain::refresh_now(&cfg, Some(&bin), secs, true).unwrap());
let st = lune_core::status::of(&cfg, "Hermes");
assert!(!st.gbrain.unwrap().failed && !st.headline.contains("GBrain not refreshed"));
// A hang is stopped at the timeout and counts as a failure.
fs::write(tmp.path().join("bin/hang"), "").unwrap();
let began = Instant::now();
let err = brain::refresh_now(&cfg, Some(&bin), Duration::from_secs(1), true).unwrap_err();
assert!(format!("{err:#}").contains("too long") && began.elapsed() < Duration::from_secs(10));
}
/// The whole path through the background runner: which syncs refresh, and that a bad gbrain never holds one up.
#[test]
fn the_runner_refreshes_only_gbrain_vaults_after_changes_and_never_waits_for_it() {
let tmp = TempDir::new().unwrap();
let (bin, log) = fake_gbrain(&tmp.path().join("bin"));
unsafe {
std::env::set_var("LUNE_HOME", tmp.path().join("home"));
std::env::set_var("LUNE_GBRAIN", &bin);
}
// Brain (GBrain, refresh on) and Plain (Obsidian) each have another device, A, writing to the same remote.
let (r_brain, r_plain) = (bare(tmp.path(), "brain.git"), bare(tmp.path(), "plain.git"));
let (a_brain, a_plain) = (add(&r_brain, &tmp.path().join("a-brain"), "A", VaultKind::Gbrain), add(&r_plain, &tmp.path().join("a-plain"), "A", VaultKind::Obsidian));
let mut mine = add(&r_brain, &tmp.path().join("my-brain"), "Mine", VaultKind::Gbrain);
mine.name = "Brain".into();
mine.gbrain_refresh = Some(true);
let (mut plain, _, _) = vault::add("Plain", &tmp.path().join("my-plain"), r_plain.to_str().unwrap(), "Mine").unwrap();
plain.gbrain_refresh = Some(true); // even if it were set, an Obsidian vault never runs it
let cfg = Config { device_name: Some("Mine".into()), vaults_dir: Some(tmp.path().join("vaults")), vaults: vec![mine.clone(), plain.clone()], ..Default::default() };
cfg.save().unwrap();
runner::STOP.store(false, Ordering::Relaxed);
let timing = Timing { quiet: Duration::from_millis(300), cap: Duration::from_secs(2), settle: Duration::from_millis(100) };
let quiet_log: lune_core::runner::Log<'static> = &|_, _| {};
let threads: Vec<_> = [mine.clone(), plain.clone()]
.into_iter()
.map(|c| std::thread::spawn(move || runner::run(&c, "Mine", Duration::from_millis(200), timing, quiet_log)))
.collect();
let a = Vault::open(&a_brain, "A").unwrap();
let ap = Vault::open(&a_plain, "A").unwrap();
let write_sync = |v: &Vault, f: &str, t: &str| {
fs::write(v.root.join(f), t).unwrap();
v.save_changes(None, &HashSet::new()).unwrap();
v.sync().unwrap();
};
// Nothing has changed anywhere: nothing runs.
std::thread::sleep(Duration::from_millis(1500));
assert!(calls(&log).is_empty(), "{:?}", calls(&log));
// Notes arrive in both vaults: only the GBrain one refreshes, with its source and --no-pull.
write_sync(&a, "one.md", "one\n");
write_sync(&ap, "one.md", "one\n");
wait_for("the first refresh", 10, || !calls(&log).is_empty());
std::thread::sleep(Duration::from_millis(1200));
let said = calls(&log);
assert_eq!(said.len(), 1, "{said:?}");
assert!(said[0].ends_with("sync --source Brain --no-pull") && said[0].contains("my-brain"), "{said:?}");
assert!(fs::read(tmp.path().join("my-plain/one.md")).is_ok(), "the Obsidian vault synced too");
// Idle: no more runs. This device's own saved edit refreshes once it's committed.
std::thread::sleep(Duration::from_millis(1000));
assert_eq!(calls(&log).len(), 1);
fs::write(tmp.path().join("my-brain/mine.md"), "mine\n").unwrap();
wait_for("a refresh after this device's own edit", 10, || calls(&log).len() == 2);
// GBrain breaks: the vault turns amber, and notes keep arriving.
fs::write(tmp.path().join("bin/fail"), "").unwrap();
write_sync(&a, "two.md", "two\n");
wait_for("the failed refresh", 10, || lune_core::status::of(&mine, "Mine").headline.contains("GBrain not refreshed"));
assert_eq!(lune_core::status::of(&mine, "Mine").level, "behind");
assert_eq!(fs::read(tmp.path().join("my-brain/two.md")).unwrap(), b"two\n");
// Retry (what the window's button and `lunesync gbrain --retry` do) once it's fixed.
fs::remove_file(tmp.path().join("bin/fail")).unwrap();
assert!(brain::refresh_now(&mine, None, Duration::from_secs(20), false).unwrap());
assert!(!lune_core::status::of(&mine, "Mine").headline.contains("GBrain not refreshed"));
// GBrain hangs: the next notes still arrive, and several changes in a row queue just one more run.
fs::write(tmp.path().join("bin/hang"), "").unwrap();
let before = calls(&log).len();
write_sync(&a, "three.md", "three\n");
wait_for("a refresh to start", 10, || calls(&log).len() == before + 1);
for i in 4..7 {
write_sync(&a, &format!("n{i}.md"), "later\n");
}
wait_for("notes to arrive while gbrain hangs", 10, || tmp.path().join("my-brain/n6.md").exists());
std::thread::sleep(Duration::from_millis(500));
assert_eq!(calls(&log).len(), before + 1, "no second copy running at once");
assert!(brain::is_refreshing(&tmp.path().join("my-brain/.git")));
runner::STOP.store(true, Ordering::Relaxed);
for t in threads {
t.join().unwrap().unwrap();
}
assert!(!calls(&log).iter().any(|c| c.contains("my-plain")), "Obsidian vaults never run gbrain");
}
use std::sync::atomic::Ordering;

359
core/tests/clash.rs Normal file
View File

@@ -0,0 +1,359 @@
//! M8 step 2: in a GBrain vault a clash never makes a second page. Lines both sides added are all kept (incoming
//! first); a rewrite of the same lines keeps the incoming one in place and this device's version waits in
//! `.git/lune/tidy/`. Obsidian vaults keep making `(Label's version).md` copies, as before.
use git2::{ObjectType, Repository, TreeWalkMode, TreeWalkResult};
use lune_core::config::VaultKind;
use lune_core::names;
use lune_core::tidy::{self, Keep};
use lune_core::vault::{self, Vault};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use tempfile::TempDir;
struct World {
tmp: TempDir,
remote: PathBuf,
kind: VaultKind,
}
impl World {
fn new(kind: VaultKind) -> World {
let tmp = TempDir::new().unwrap();
let remote = tmp.path().join("remote.git");
Repository::init_bare(&remote).unwrap();
World { tmp, remote, kind }
}
fn device(&self, label: &str) -> Vault {
let (mut cfg, _, err) = vault::add("Brain", &self.tmp.path().join(label), self.remote.to_str().unwrap(), label).unwrap();
assert_eq!(err, None);
cfg.kind = self.kind;
vault::apply_kind_ignores(&Repository::open(&cfg.path).unwrap(), self.kind).unwrap();
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()
}
fn files(root: &Path) -> Vec<String> {
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
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.push(rel);
}
}
}
let mut out = vec![];
walk(root, root, &mut out);
out.sort();
out
}
/// True if any commit reachable from any ref in `repo` has a tree holding a kept-both copy path.
fn copy_anywhere_in_history(repo: &Repository) -> bool {
let mut walk = repo.revwalk().unwrap();
for r in repo.references().unwrap() {
if let Ok(oid) = r.unwrap().peel_to_commit().map(|c| c.id()) {
walk.push(oid).unwrap();
}
}
walk.any(|id| {
let tree = repo.find_commit(id.unwrap()).unwrap().tree().unwrap();
let mut found = false;
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
if e.kind() == Some(ObjectType::Blob) {
found |= names::parse_copy(&format!("{dir}{}", e.name().unwrap())).is_some();
}
TreeWalkResult::Ok
})
.unwrap();
found
})
}
const PAGE: &str = "# Ada\n\nShe builds engines.\n\n## Timeline\n- 2020: joined\n";
fn two(w: &World) -> (Vault, Vault) {
let a = w.device("Codex");
write(&a, "people/ada.md", PAGE);
save_and_sync(&a);
let b = w.device("Hermes");
(a, b)
}
#[test]
fn both_append_to_the_same_page_and_both_entries_stay_incoming_first() {
let w = World::new(VaultKind::Gbrain);
let (a, b) = two(&w);
write(&a, "people/ada.md", format!("{PAGE}- 2021: Codex met her\n"));
write(&b, "people/ada.md", format!("{PAGE}- 2021: Hermes read her paper\n"));
save_and_sync(&a);
let report = save_and_sync(&b);
assert_eq!(report.joined, vec!["people/ada.md".to_string()]);
assert!(report.kept_both.is_empty() && report.to_tidy.is_empty());
let want = format!("{PAGE}- 2021: Codex met her\n- 2021: Hermes read her paper\n");
assert_eq!(read(&b, "people/ada.md"), want.as_bytes(), "incoming (Codex) first, then this device's");
a.sync().unwrap();
assert_eq!(read(&a, "people/ada.md"), want.as_bytes());
assert_eq!(files(&a.root), ["people/ada.md"]);
assert_eq!(files(&b.root), ["people/ada.md"]);
assert!(tidy::list(&a).unwrap().is_empty() && tidy::list(&b).unwrap().is_empty());
assert!(!copy_anywhere_in_history(a.repo()) && !copy_anywhere_in_history(b.repo()));
assert!(!copy_anywhere_in_history(&Repository::open(&w.remote).unwrap()));
}
#[test]
fn appending_to_a_page_without_a_final_newline_still_joins() {
let w = World::new(VaultKind::Gbrain);
let a = w.device("Codex");
write(&a, "p.md", "title\nlast");
save_and_sync(&a);
let b = w.device("Hermes");
write(&a, "p.md", "title\nlast\ncodex");
write(&b, "p.md", "title\nlast\nhermes");
save_and_sync(&a);
let r = save_and_sync(&b);
assert_eq!(r.joined.len(), 1, "{r:?}");
assert_eq!(read(&b, "p.md"), b"title\nlast\ncodex\nhermes");
}
#[test]
fn rewriting_the_same_paragraph_keeps_the_incoming_one_and_tidies_ours() {
let w = World::new(VaultKind::Gbrain);
let (a, b) = two(&w);
let codex = PAGE.replace("She builds engines.", "She builds steam engines.");
let hermes = PAGE.replace("She builds engines.", "She designs analytical engines.");
write(&a, "people/ada.md", &codex);
write(&b, "people/ada.md", &hermes);
save_and_sync(&a);
let report = save_and_sync(&b);
assert_eq!(report.to_tidy, vec!["people/ada.md".to_string()]);
assert_eq!(read(&b, "people/ada.md"), codex.as_bytes(), "incoming stays in place");
assert_eq!(files(&b.root), ["people/ada.md"], "no copy in the folder");
a.sync().unwrap();
assert_eq!(files(&a.root), ["people/ada.md"]);
assert_eq!(read(&a, "people/ada.md"), codex.as_bytes());
assert!(!copy_anywhere_in_history(a.repo()) && !copy_anywhere_in_history(b.repo()));
assert!(!copy_anywhere_in_history(&Repository::open(&w.remote).unwrap()));
// Hermes's version is kept byte-exact on its device only, inside .git/lune/tidy.
let entries = tidy::entries(&b.git_dir);
assert_eq!(entries.len(), 1);
assert_eq!((entries[0].note.as_str(), entries[0].label.as_str(), entries[0].source.as_str()), ("people/ada.md", "Hermes", "sync"));
assert_eq!(tidy::mine_bytes(&b.git_dir, &entries[0].id).unwrap(), hermes.as_bytes());
assert!(tidy::entries(&a.git_dir).is_empty());
// This device's own entries stay in history, as for Obsidian; only the folder has to stay clean.
// And it shows under Notes to tidy, not as a file.
let listed = tidy::list(&b).unwrap();
assert_eq!(listed.len(), 1);
assert!(listed[0].local && listed[0].copy.starts_with(".git/"));
// Sync keeps working with it waiting.
write(&a, "other.md", "still syncing\n");
save_and_sync(&a);
b.sync().unwrap();
assert_eq!(read(&b, "other.md"), b"still syncing\n");
assert_eq!(tidy::list(&b).unwrap().len(), 1);
}
fn clash(w: &World) -> (Vault, Vault, String, String) {
let (a, b) = two(w);
let codex = PAGE.replace("She builds engines.", "She builds steam engines.");
let hermes = PAGE.replace("She builds engines.", "She designs analytical engines.");
write(&a, "people/ada.md", &codex);
write(&b, "people/ada.md", &hermes);
save_and_sync(&a);
save_and_sync(&b);
a.sync().unwrap();
(a, b, codex, hermes)
}
#[test]
fn tidy_keep_mine_reaches_the_other_device() {
let w = World::new(VaultKind::Gbrain);
let (a, b, _, hermes) = clash(&w);
tidy::keep(&b, "people/ada.md", Keep::Mine).unwrap().unwrap();
assert!(tidy::entries(&b.git_dir).is_empty() && tidy::list(&b).unwrap().is_empty());
b.sync().unwrap();
a.sync().unwrap();
assert_eq!(read(&a, "people/ada.md"), hermes.as_bytes());
assert_eq!(files(&a.root), ["people/ada.md"]);
}
#[test]
fn tidy_keep_theirs_drops_ours_and_changes_nothing_elsewhere() {
let w = World::new(VaultKind::Gbrain);
let (a, b, codex, _) = clash(&w);
let saved = tidy::keep(&b, "people/ada.md", Keep::Theirs).unwrap();
assert!(saved.is_none());
assert!(tidy::list(&b).unwrap().is_empty());
assert_eq!(read(&b, "people/ada.md"), codex.as_bytes());
b.sync().unwrap();
a.sync().unwrap();
assert_eq!(read(&a, "people/ada.md"), codex.as_bytes());
}
#[test]
fn tidy_keep_both_writes_both_into_the_one_note() {
let w = World::new(VaultKind::Gbrain);
let (a, b, codex, hermes) = clash(&w);
tidy::keep(&b, "people/ada.md", Keep::Both).unwrap().unwrap();
assert_eq!(files(&b.root), ["people/ada.md"]);
let text = String::from_utf8(read(&b, "people/ada.md")).unwrap();
assert!(text.starts_with(&codex), "the one in place comes first");
assert!(text.ends_with(&hermes), "this device's version follows, exact");
assert!(text.contains("Kept from Hermes's version"), "{text}");
assert!(tidy::entries(&b.git_dir).is_empty());
b.sync().unwrap();
a.sync().unwrap();
assert_eq!(read(&a, "people/ada.md"), text.as_bytes());
assert_eq!(files(&a.root), ["people/ada.md"]);
}
const FAKE_KEY: &str = "AWS_KEY=AKIAIOSFODNN7EXAMPLE\n";
#[test]
fn a_held_note_in_a_gbrain_vault_is_kept_aside_not_copied_and_stays_held() {
let w = World::new(VaultKind::Gbrain);
let a = w.device("Codex");
write(&a, "ops.md", "ops\n");
save_and_sync(&a);
let b = w.device("Hermes");
let held = format!("ops\n{FAKE_KEY}");
write(&a, "ops.md", &held);
a.save_changes(None, &HashSet::new()).unwrap();
assert_eq!(a.secret_holds().unwrap().len(), 1);
write(&b, "ops.md", "ops\nnew runbook link\n");
save_and_sync(&b);
let report = a.sync().unwrap();
assert_eq!(report.held_to_tidy, vec!["ops.md".to_string()]);
assert!(report.set_aside.is_empty());
assert_eq!(read(&a, "ops.md"), b"ops\nnew runbook link\n");
assert_eq!(files(&a.root), ["ops.md"], "no copy in the folder");
assert!(a.secret_holds().unwrap().is_empty(), "the working note is the plain incoming one");
// Still held (P2, X6): counts as a held secret everywhere a held note does, so the vault is red, not just amber.
let held_notes: Vec<String> = a.all_secret_holds().unwrap().into_iter().map(|n| n.path).collect();
assert_eq!(held_notes, ["ops.md"]);
let cfg = lune_core::config::VaultConfig {
name: "Brain".into(),
path: a.root.clone(),
remote: w.remote.to_str().unwrap().into(),
branch: "main".into(),
kind: VaultKind::Gbrain,
..Default::default()
};
let st = lune_core::status::of(&cfg, "Codex");
assert_eq!(st.level, "secret");
assert_eq!(st.secrets.len(), 1);
assert_eq!(st.secrets[0].path, "ops.md");
let entries = tidy::entries(&a.git_dir);
assert_eq!(entries.len(), 1);
assert!(entries[0].held);
assert_eq!(tidy::mine_bytes(&a.git_dir, &entries[0].id).unwrap(), held.as_bytes());
// "Not a secret" / "Replace with a pointer" work on the kept-aside version too.
let (entry, hits) = tidy::held_aside_hits(&a, "ops.md", None).unwrap().unwrap();
tidy::replace_held_aside(&a, &entry, &hits, None, "search prod in Secrets Manager").unwrap();
assert!(a.all_secret_holds().unwrap().is_empty(), "no longer held once the secret is replaced");
assert!(String::from_utf8(tidy::mine_bytes(&a.git_dir, &entry.id).unwrap()).unwrap().contains("Secrets Manager"));
// Put the original back for the next check.
tidy::put(&a.git_dir, &entry, held.as_bytes()).unwrap();
assert_eq!(a.all_secret_holds().unwrap().len(), 1);
// Putting it back brings the secret check back with it: held, not shared.
tidy::keep(&a, "ops.md", Keep::Mine).unwrap();
assert_eq!(read(&a, "ops.md"), held.as_bytes());
let holds: Vec<String> = a.secret_holds().unwrap().into_iter().map(|n| n.path).collect();
assert_eq!(holds, ["ops.md"]);
a.sync().unwrap();
b.sync().unwrap();
assert!(!String::from_utf8(read(&b, "ops.md")).unwrap().contains("AKIA"), "the key never travelled");
assert!(!copy_anywhere_in_history(a.repo()));
}
#[test]
fn undo_in_a_gbrain_vault_keeps_the_brought_back_version_and_tidies_the_other() {
let w = World::new(VaultKind::Gbrain);
let a = w.device("Codex");
for i in 0..20 {
write(&a, &format!("notes/{i:02}.md"), format!("note {i}\nline two\n"));
}
save_and_sync(&a);
let b = w.device("Hermes");
for i in 0..10 {
fs::remove_file(a.root.join(format!("notes/{i:02}.md"))).unwrap();
}
a.save_changes(None, &HashSet::new()).unwrap();
write(&b, "notes/03.md", "note 3\nline two\nedited on hermes\n");
save_and_sync(&b);
a.sync().unwrap();
let clashes = a.undo_held().unwrap();
assert_eq!(clashes.to_tidy, vec!["notes/03.md".to_string()]);
assert!(clashes.copies.is_empty());
assert_eq!(files(&a.root).len(), 20, "no extra note");
assert_eq!(read(&a, "notes/03.md"), b"note 3\nline two\n", "what the undo brought back is in place");
let entries = tidy::entries(&a.git_dir);
assert_eq!(entries.len(), 1);
assert_eq!(tidy::mine_bytes(&a.git_dir, &entries[0].id).unwrap(), b"note 3\nline two\nedited on hermes\n");
assert!(!copy_anywhere_in_history(a.repo()));
}
#[test]
fn obsidian_vaults_still_make_version_copies() {
let w = World::new(VaultKind::Obsidian);
let (a, b, codex, hermes) = clash(&w);
assert_eq!(read(&b, "people/ada.md"), codex.as_bytes());
assert_eq!(read(&b, "people/ada (Hermes's version).md"), hermes.as_bytes());
assert!(tidy::entries(&b.git_dir).is_empty());
assert_eq!(tidy::list(&b).unwrap().len(), 1);
assert!(!tidy::list(&b).unwrap()[0].local);
assert_eq!(read(&a, "people/ada (Hermes's version).md"), hermes.as_bytes());
// Both appended: still a copy for Obsidian (as today).
let w = World::new(VaultKind::Obsidian);
let (a, b) = two(&w);
write(&a, "people/ada.md", format!("{PAGE}- codex\n"));
write(&b, "people/ada.md", format!("{PAGE}- hermes\n"));
save_and_sync(&a);
let r = save_and_sync(&b);
assert_eq!(r.kept_both.len(), 1);
assert!(r.joined.is_empty() && r.to_tidy.is_empty());
}
#[test]
fn the_kind_is_read_when_the_clash_happens() {
// A vault opened as Obsidian, then marked GBrain while it runs: the next clash makes no copy.
let w = World::new(VaultKind::Obsidian);
let (a, b) = two(&w);
vault::apply_kind_ignores(b.repo(), VaultKind::Gbrain).unwrap();
write(&a, "people/ada.md", PAGE.replace("engines", "steam engines"));
write(&b, "people/ada.md", PAGE.replace("engines", "analytical engines"));
save_and_sync(&a);
let r = save_and_sync(&b);
assert_eq!(r.to_tidy.len(), 1);
assert_eq!(files(&b.root), ["people/ada.md"]);
}

View File

@@ -583,5 +583,6 @@ fn made_cfg(w: &World) -> lune_core::config::VaultConfig {
branch: "main".into(),
hub_vault: None,
hub_url: None,
..Default::default()
}
}