Files
lune/core/tests/brain.rs
Adnan Zahir e6c3f008a0 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>
2026-11-16 22:55:18 +07:00

238 lines
11 KiB
Rust

//! 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;