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:
8
Cargo.lock
generated
8
Cargo.lock
generated
@@ -2581,7 +2581,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "lune-core"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.23.1",
|
||||
@@ -2601,7 +2601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lune-desktop"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
@@ -2621,7 +2621,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lunehub"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
@@ -2642,7 +2642,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lunesync"
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
||||
@@ -4,5 +4,5 @@ members = ["core", "cli", "hub", "desktop"]
|
||||
|
||||
# One version for every part: the hub offers clients by it (D3).
|
||||
[workspace.package]
|
||||
version = "0.1.5"
|
||||
version = "0.1.6"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
@@ -32,6 +32,7 @@ Lune works on **plain folders**. Obsidian, VS Code, an AI agent or a shell scrip
|
||||
| **Roles** | Each person has **Read**, **Edit** or **Manage** on each vault. A Read member can edit their own copy, but those edits stay on their device. |
|
||||
| **Taking access back** | Remove someone from a vault: their device makes the folder read-only, hands over anything unshared for a manager to **Keep** or **Discard**, then deletes its copy. Devices that are offline do this when they come back. |
|
||||
| **Team canvas** | A web page on your hub showing vaults, people and devices. Drag to grant, pull a ribbon to revoke (with Undo), and see who is current, behind, offline, or holding a secret. **Nudge** a device to share now. Works on a phone too. |
|
||||
| **GBrain brains** | Mark a vault as a [GBrain](https://github.com/garrytan/gbrain) brain and every device that has `gbrain` refreshes it after notes arrive, so agents answer from the latest notes. Clashes never become a second page: lines both sides added are kept in the one note, and if the same lines changed, the other version waits on its own device under **Notes to tidy** instead of as a copy file. |
|
||||
| **Several teams** | One device can belong to more than one team's hub, such as your own and your workplace's, each with its own vaults. |
|
||||
| **Signed updates** | The Mac app updates itself from your hub. Every update is signed by your hub and checked before it's installed. |
|
||||
|
||||
@@ -125,6 +126,7 @@ Lists each vault with its status, and anything that needs you:
|
||||
- **A big change is waiting:** **Undo** brings back everything it removed or rewrote; **Share anyway** sends it.
|
||||
- **A note may contain a secret:** type where the secret really lives and click **Replace**, or click **Not a secret**.
|
||||
- **A note was changed in two places:** **Compare** shows both versions with the differences highlighted. Keep one, or keep both as separate notes.
|
||||
- **GBrain:** **Mark as GBrain** makes the vault a GBrain brain for the whole team (Lune suggests it when it sees `gbrain.yml`). Where `gbrain` is installed, Lune asks once whether to refresh GBrain after each sync; if a refresh fails, the vault turns amber with **Retry**.
|
||||
- **Upload:** put a vault that's only on this Mac onto a team, history included. The button shows for the team owner and anyone who manages a vault there. A vault that syncs with its own remote (GitHub, GitLab, Gitea…) is **detached** from it first, so its notes don't end up in two places; that remote keeps its copy as it was. Before anything is made on the team, Lune checks the notes the way the team's hub will: a line that looks like a secret turns red to decide (replace it with where to find it, or mark it not a secret), and if older history has one, you can upload just the current notes (the full history stays on your Mac).
|
||||
- **Join another team:** add a second hub, such as your workplace's. **Leave** next to a team removes this Mac from it (anything unshared is handed over first).
|
||||
|
||||
@@ -146,6 +148,7 @@ lunesync checkpoint "Before the migration" # a named point in history, shared
|
||||
lunesync held # what's held back here, and how to decide
|
||||
lunesync tidy # notes kept in two versions
|
||||
lunesync tidy keep mine notes/plan.md # or: theirs, both
|
||||
lunesync gbrain --vault Brain --refresh on # refresh GBrain after sync on this device (--source <name>, --retry)
|
||||
lunesync history # recent changes and which device made them
|
||||
lunesync open # the team canvas, already signed in
|
||||
lunesync pair # a one-time code to add another device
|
||||
@@ -155,6 +158,7 @@ Team management from the terminal:
|
||||
|
||||
```sh
|
||||
lunesync vault new DevOps # the team owner, or anyone who manages a vault
|
||||
lunesync vault kind Brain gbrain # a GBrain brain for the whole team (or: obsidian)
|
||||
lunesync vault detach Brain # stop syncing with its own remote (GitHub, GitLab…); stays on this device
|
||||
lunesync vault upload Brain # put a vault that's only on this device onto the team
|
||||
lunesync invite Alice --vault DevOps:edit --vault Notes:read
|
||||
@@ -191,6 +195,7 @@ Such a vault still shows in the Lune app with its status, but not on a team canv
|
||||
| Setting | Default | |
|
||||
|---|---|---|
|
||||
| Delete from their devices | on | When someone is removed, their copy is deleted after their unshared work is handed over. Off: their copy stays, read-only and no longer synced. `lunesync vault set DevOps --delete-from-devices off` |
|
||||
| Kind | Obsidian | **GBrain** changes how clashes are kept (no copy files, see above) and lets devices refresh GBrain after sync. `lunesync vault kind Brain gbrain` |
|
||||
|
||||
### Per device
|
||||
|
||||
|
||||
105
cli/src/main.rs
105
cli/src/main.rs
@@ -144,6 +144,20 @@ enum Command {
|
||||
#[command(subcommand)]
|
||||
action: HubCmd,
|
||||
},
|
||||
/// GBrain vaults: refresh GBrain on this device after notes arrive, and bring it up to date again after a failure
|
||||
Gbrain {
|
||||
#[arg(long)]
|
||||
vault: Option<String>,
|
||||
/// Refresh GBrain after notes arrive on this device: on or off
|
||||
#[arg(long)]
|
||||
refresh: Option<OnOff>,
|
||||
/// The name of this vault's source in GBrain on this device (default: the vault's name)
|
||||
#[arg(long)]
|
||||
source: Option<String>,
|
||||
/// Refresh GBrain now, even if nothing new arrived
|
||||
#[arg(long)]
|
||||
retry: bool,
|
||||
},
|
||||
/// Recent history entries and which device made them
|
||||
History {
|
||||
#[arg(long)]
|
||||
@@ -196,6 +210,11 @@ enum VaultCmd {
|
||||
#[arg(long)]
|
||||
yes: bool,
|
||||
},
|
||||
/// Say what a vault is for: gbrain (Lune refreshes GBrain after notes arrive) or obsidian (the default). Needs Manage
|
||||
Kind {
|
||||
name: String,
|
||||
kind: String,
|
||||
},
|
||||
/// Stop syncing a vault with its own remote (GitHub, GitLab…): it stays on this device only, ready to upload
|
||||
Detach { name: String },
|
||||
/// Move a vault that's only on this device onto the hub (detach it from any other remote first)
|
||||
@@ -333,6 +352,41 @@ fn run_cli(cli: Cli) -> Result<()> {
|
||||
}
|
||||
Command::Vault { action: VaultCmd::New { name } } => team::vault_new(&mut config, &name)?,
|
||||
Command::Vault { action: VaultCmd::Upload { name, fresh } } => team::vault_upload(&mut config, &name, fresh)?,
|
||||
Command::Vault { action: VaultCmd::Kind { name, kind } } => {
|
||||
let kind = lune_core::config::VaultKind::parse(&kind).context("a vault's kind is gbrain or obsidian")?;
|
||||
println!("{}", lune_core::brain::set_kind(&mut config, &name, kind)?);
|
||||
if kind == lune_core::config::VaultKind::Gbrain {
|
||||
println!("Other devices learn it within a minute. Next: `lunesync gbrain --vault {name} --refresh on` to refresh GBrain here after notes arrive.");
|
||||
}
|
||||
}
|
||||
Command::Gbrain { vault, refresh, source, retry } => {
|
||||
let name = config.pick(vault.as_deref(), &cwd)?.name.clone();
|
||||
let changed = refresh.is_some() || source.is_some();
|
||||
lune_core::brain::set_device_settings(
|
||||
&mut config,
|
||||
&name,
|
||||
refresh.map(|r| matches!(r, OnOff::On)),
|
||||
source,
|
||||
)?;
|
||||
let cfg = config.find(&name).unwrap().clone();
|
||||
if changed {
|
||||
println!("Saved.");
|
||||
}
|
||||
if retry {
|
||||
if lune_core::brain::refresh_now(&cfg, None, lune_core::brain::TIMEOUT, false)? {
|
||||
println!("GBrain is up to date for {name}.");
|
||||
} else {
|
||||
println!("GBrain is already being refreshed for {name}.");
|
||||
}
|
||||
} else {
|
||||
match (cfg.gbrain_refresh, lune_core::brain::find_gbrain()) {
|
||||
(Some(true), _) => println!("{name}: refreshing GBrain after sync is on (source \"{}\"). Turn off: `lunesync gbrain --vault {name} --refresh off`", cfg.gbrain_source_name()),
|
||||
(Some(false), _) => println!("{name}: refreshing GBrain after sync is off. Turn on: `lunesync gbrain --vault {name} --refresh on`"),
|
||||
(None, Some(p)) => println!("{name}: found gbrain at {}. Turn on refreshing GBrain after sync: `lunesync gbrain --vault {name} --refresh on` (or --refresh off to stop being asked).", p.display()),
|
||||
(None, None) => println!("{name}: the gbrain command wasn't found on this device, so nothing is refreshed."),
|
||||
}
|
||||
}
|
||||
}
|
||||
Command::Vault { action: VaultCmd::Detach { name } } => team::vault_detach(&mut config, &name)?,
|
||||
Command::Invite { person, vaults } => team::invite(&config, &person, &vaults)?,
|
||||
Command::Grant { person, vault, role } => team::grant(&config, &person, &vault, &role)?,
|
||||
@@ -407,10 +461,15 @@ fn run_cli(cli: Cli) -> Result<()> {
|
||||
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):");
|
||||
println!("Notes changed in two places (both versions kept; a GBrain vault keeps yours on this device):");
|
||||
}
|
||||
any = true;
|
||||
println!(" {:<12} {} ← {}", v.name, k.note, k.copy);
|
||||
if k.local {
|
||||
let why = if k.held { "kept on this device (it looked like a secret)" } else { "kept on this device" };
|
||||
println!(" {:<12} {} ← your version, {why}", v.name, k.note);
|
||||
} else {
|
||||
println!(" {:<12} {} ← {}", v.name, k.note, k.copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
if any {
|
||||
@@ -430,7 +489,7 @@ fn run_cli(cli: Cli) -> Result<()> {
|
||||
};
|
||||
match tidy::keep(&v, &rel, choice)? {
|
||||
Some(saved) => println!("{}.", saved.message),
|
||||
None => println!("Nothing changed."),
|
||||
None => println!("Tidied."),
|
||||
}
|
||||
share_now(&v);
|
||||
}
|
||||
@@ -456,7 +515,7 @@ fn run_cli(cli: Cli) -> Result<()> {
|
||||
);
|
||||
println!(" Send it: `lunesync held share` Bring everything back: `lunesync held undo`");
|
||||
}
|
||||
for n in v.secret_holds()? {
|
||||
for n in v.all_secret_holds()? {
|
||||
any = true;
|
||||
for h in &n.hits {
|
||||
println!("{}: {} line {} has a possible {}: {}", v.name, n.path, h.line, h.rule, h.hint);
|
||||
@@ -516,9 +575,15 @@ fn held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Resul
|
||||
} else {
|
||||
let kept = v.undo_held()?;
|
||||
println!("Brought everything back in {}.", v.name);
|
||||
for (note, copy) in kept {
|
||||
for (note, copy) in kept.copies {
|
||||
println!(" {note} was edited elsewhere meanwhile — kept both, the other version is \"{copy}\".");
|
||||
}
|
||||
for note in kept.joined {
|
||||
println!(" {note} had lines added elsewhere meanwhile — both sets of lines are kept.");
|
||||
}
|
||||
for note in kept.to_tidy {
|
||||
println!(" {note} was edited elsewhere meanwhile — the version from this device waits under `lunesync tidy`.");
|
||||
}
|
||||
}
|
||||
share_now(&v);
|
||||
}
|
||||
@@ -526,6 +591,13 @@ fn held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Resul
|
||||
let (cfg, rel) = locate(config, vault, cwd, &file)?;
|
||||
let v = Vault::open(cfg, &label)?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
if v.secret_holds()?.iter().all(|n| n.path != rel)
|
||||
&& let Some((entry, hits)) = tidy::held_aside_hits(&v, &rel, line)?
|
||||
{
|
||||
tidy::replace_held_aside(&v, &entry, &hits, line, &pointer)?;
|
||||
println!("Replaced {} secret{} in your held version of {rel} with \"{pointer}\"; it waits in `lunesync tidy`.", hits.len(), if hits.len() == 1 { "" } else { "s" });
|
||||
return Ok(());
|
||||
}
|
||||
let hits = held_hits(&v, &rel, line)?;
|
||||
let path = v.root.join(&rel);
|
||||
let text = std::fs::read_to_string(&path)?;
|
||||
@@ -537,6 +609,18 @@ fn held(config: &Config, cwd: &Path, vault: Option<&str>, cmd: HeldCmd) -> Resul
|
||||
let (cfg, rel) = locate(config, vault, cwd, &file)?;
|
||||
let v = Vault::open(cfg, &label)?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
if v.secret_holds()?.iter().all(|n| n.path != rel)
|
||||
&& let Some((entry, hits)) = tidy::held_aside_hits(&v, &rel, line)?
|
||||
{
|
||||
tidy::allow_held_aside(&v, &entry, &hits)?;
|
||||
if let (Some(hub), Some(id)) = (config.hub_of(cfg), cfg.hub_vault) {
|
||||
for h in &hits {
|
||||
hub.not_a_secret(id, &h.line_hash)?;
|
||||
}
|
||||
}
|
||||
println!("OK — those lines won't be held again on this device; your version waits in `lunesync tidy`.");
|
||||
return Ok(());
|
||||
}
|
||||
for h in held_hits(&v, &rel, line)? {
|
||||
secrets::allow(&v.git_dir, &h, &rel)?;
|
||||
if let (Some(hub), Some(id)) = (config.hub_of(cfg), cfg.hub_vault) {
|
||||
@@ -652,6 +736,17 @@ fn print_status(cfg: &VaultConfig, label: &str) {
|
||||
if to_tidy > 0 {
|
||||
println!(" {to_tidy} note{} to tidy — see `lunesync tidy`", if to_tidy == 1 { "" } else { "s" });
|
||||
}
|
||||
if let Some(g) = &st.gbrain {
|
||||
match g.refresh {
|
||||
_ if g.failed => println!(" GBrain not refreshed{} — fix it, then `lunesync gbrain --vault {} --retry`", g.error.as_ref().map(|e| format!(" ({e})")).unwrap_or_default(), st.name),
|
||||
Some(true) => println!(" GBrain vault · refreshed after sync (source \"{}\")", g.source),
|
||||
Some(false) => println!(" GBrain vault · refreshing after sync is off"),
|
||||
None if g.ask => println!(" GBrain vault · found gbrain here — turn on refreshing after sync: `lunesync gbrain --vault {} --refresh on`", st.name),
|
||||
None => println!(" GBrain vault · the gbrain command wasn't found on this device"),
|
||||
}
|
||||
} else if st.suggest_gbrain {
|
||||
println!(" This looks like a GBrain — mark it with `lunesync vault kind {} gbrain`", st.name);
|
||||
}
|
||||
if !st.case_clashes.is_empty() {
|
||||
println!(" Names differing only by case: {}", st.case_clashes.join(", "));
|
||||
}
|
||||
|
||||
250
core/src/brain.rs
Normal file
250
core/src/brain.rs
Normal 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()
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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}))?;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pub use git2;
|
||||
|
||||
pub mod brain;
|
||||
pub mod config;
|
||||
pub mod guard;
|
||||
pub mod hub;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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(¤t) {
|
||||
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}\""));
|
||||
}
|
||||
|
||||
@@ -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()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
187
core/src/tidy.rs
187
core/src/tidy.rs
@@ -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(©).map(|(note, label)| KeptBoth { note, copy, label }))
|
||||
.filter_map(|copy| names::parse_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(¬e, None, ©, 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)
|
||||
}
|
||||
|
||||
@@ -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(¬e, &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(¬e.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(¬e.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(¬e, 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(¬e, 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
237
core/tests/brain.rs
Normal 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
359
core/tests/clash.rs
Normal 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"]);
|
||||
}
|
||||
@@ -583,5 +583,6 @@ fn made_cfg(w: &World) -> lune_core::config::VaultConfig {
|
||||
branch: "main".into(),
|
||||
hub_vault: None,
|
||||
hub_url: None,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +204,11 @@ pub fn secret_pointer(vault: String, path: String, pointer: String) -> Answer<()
|
||||
return Err("say where to get it, e.g. \"search prod-deploy in Secrets Manager\"".into());
|
||||
}
|
||||
with_vault(&vault, |_, v| {
|
||||
if v.secret_holds()?.iter().all(|n| n.path != path)
|
||||
&& let Some((entry, hits)) = tidy::held_aside_hits(v, &path, None)?
|
||||
{
|
||||
return tidy::replace_held_aside(v, &entry, &hits, None, pointer.trim());
|
||||
}
|
||||
let hits = held_hits(v, &path)?;
|
||||
let file = v.root.join(&path);
|
||||
let text = std::fs::read_to_string(&file)?;
|
||||
@@ -216,6 +221,17 @@ pub fn secret_pointer(vault: String, path: String, pointer: String) -> Answer<()
|
||||
pub fn not_a_secret(vault: String, path: String) -> Answer<()> {
|
||||
with_vault(&vault, |config, v| {
|
||||
let cfg = config.find(&vault).unwrap();
|
||||
if v.secret_holds()?.iter().all(|n| n.path != path)
|
||||
&& let Some((entry, hits)) = tidy::held_aside_hits(v, &path, None)?
|
||||
{
|
||||
tidy::allow_held_aside(v, &entry, &hits)?;
|
||||
if let (Some(hub), Some(id)) = (config.hub_of(cfg), cfg.hub_vault) {
|
||||
for h in &hits {
|
||||
hub.not_a_secret(id, &h.line_hash)?;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for h in held_hits(v, &path)? {
|
||||
secrets::allow(&v.git_dir, &h, &path)?;
|
||||
if let (Some(hub), Some(id)) = (config.hub_of(cfg), cfg.hub_vault) {
|
||||
@@ -247,10 +263,11 @@ pub fn compare(vault: String, copy: String) -> Answer<Comparison> {
|
||||
let cfg = config.find(&vault).ok_or(format!("no vault named {vault}"))?;
|
||||
let v = Vault::open(cfg, &config.device_label()).map_err(plain)?;
|
||||
let k = tidy::list(&v).map_err(plain)?.into_iter().find(|k| k.copy == copy).ok_or("that was tidied already")?;
|
||||
let (note_bytes, copy_bytes) = tidy::versions(&v, &k).map_err(plain)?;
|
||||
Ok(Comparison {
|
||||
note_text: as_text(std::fs::read(v.root.join(&k.note)).ok()),
|
||||
copy_text: as_text(std::fs::read(v.root.join(&k.copy)).ok()),
|
||||
copy_is_mine: k.label.eq_ignore_ascii_case(&v.label),
|
||||
note_text: as_text(note_bytes),
|
||||
copy_text: as_text(Some(copy_bytes)),
|
||||
copy_is_mine: k.is_mine(&v),
|
||||
note: k.note,
|
||||
copy: k.copy,
|
||||
label: k.label,
|
||||
@@ -262,7 +279,7 @@ pub fn compare(vault: String, copy: String) -> Answer<Comparison> {
|
||||
pub fn tidy(vault: String, copy: String, keep: String) -> Answer<()> {
|
||||
with_vault(&vault, |_, v| {
|
||||
let k = tidy::list(v)?.into_iter().find(|k| k.copy == copy).ok_or_else(|| anyhow::anyhow!("that was tidied already"))?;
|
||||
let copy_is_mine = k.label.eq_ignore_ascii_case(&v.label);
|
||||
let copy_is_mine = k.is_mine(v);
|
||||
let choice = match (keep.as_str(), copy_is_mine) {
|
||||
("both", _) => Keep::Both,
|
||||
("copy", true) | ("note", false) => Keep::Mine,
|
||||
@@ -272,6 +289,46 @@ pub fn tidy(vault: String, copy: String, keep: String) -> Answer<()> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Marks a vault as a GBrain (or back to Obsidian) on its team's hub; every device follows.
|
||||
#[tauri::command(async)]
|
||||
pub fn set_vault_kind(vault: String, kind: String) -> Answer<String> {
|
||||
let kind = lune_core::config::VaultKind::parse(&kind).ok_or("a vault is a GBrain or an Obsidian vault")?;
|
||||
let mut config = Config::load().map_err(plain)?;
|
||||
config.use_hub_credentials();
|
||||
lune_core::brain::set_kind(&mut config, &vault, kind).map_err(plain)
|
||||
}
|
||||
|
||||
/// This Mac's answer to "Refresh GBrain after sync", and its GBrain source name.
|
||||
#[tauri::command(async)]
|
||||
pub fn gbrain_settings(vault: String, refresh: Option<bool>, source: Option<String>) -> Answer<()> {
|
||||
let mut config = Config::load().map_err(plain)?;
|
||||
lune_core::brain::set_device_settings(&mut config, &vault, refresh, source).map_err(plain)?;
|
||||
if refresh == Some(true) {
|
||||
// Bring GBrain up to date once now, so turning it on is visibly working.
|
||||
if let Some(cfg) = config.find(&vault) {
|
||||
lune_core::brain::request(cfg);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tries refreshing GBrain again after "GBrain not refreshed".
|
||||
#[tauri::command(async)]
|
||||
pub fn gbrain_retry(vault: String) -> Answer<()> {
|
||||
let config = Config::load().map_err(plain)?;
|
||||
let cfg = config.find(&vault).ok_or(format!("no vault named {vault}"))?;
|
||||
lune_core::brain::request(cfg);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// "Not now" on the suggestion to mark a vault as a GBrain.
|
||||
#[tauri::command(async)]
|
||||
pub fn dismiss_gbrain_hint(vault: String) -> Answer<()> {
|
||||
let config = Config::load().map_err(plain)?;
|
||||
let cfg = config.find(&vault).ok_or(format!("no vault named {vault}"))?;
|
||||
lune_core::brain::dismiss_suggestion(&cfg.path.join(".git")).map_err(plain)
|
||||
}
|
||||
|
||||
/// Leaves a team on this Mac. `forget` drops a hub that can't be reached (its folders stay).
|
||||
#[tauri::command(async)]
|
||||
pub fn leave_team(team: String, forget: bool) -> Answer<String> {
|
||||
|
||||
@@ -359,6 +359,10 @@ fn main() {
|
||||
commands::tidy,
|
||||
commands::open_canvas,
|
||||
commands::leave_team,
|
||||
commands::set_vault_kind,
|
||||
commands::gbrain_settings,
|
||||
commands::gbrain_retry,
|
||||
commands::dismiss_gbrain_hint,
|
||||
commands::open_folder,
|
||||
commands::restart,
|
||||
])
|
||||
|
||||
40
docs/SPEC.md
40
docs/SPEC.md
@@ -148,6 +148,7 @@ Four targets, seven milestones. Each ends with a story Sen acts out as a user. A
|
||||
| C · Web | **5. Canvas for access** | Grant by drag, revoke by pinch with undo, button alternatives, invites, device labels, Float/Dock. |
|
||||
| | **6. Canvas for health and leaving** | Freshness glow and Nudge, tidy a conflict side by side, review a handover, remove from team — also from a phone. |
|
||||
| D · Desktop | **7. The app normal people install** | Download from the website, pair automatically, pick a folder, tray status, compare a conflict, receive an update, uninstall cleanly. |
|
||||
| E · Agents' brains | **8. My agents share one GBrain** *(draft, after M7)* | Codex adds a page on the laptop; Hermes's GBrain finds it on the VPS a minute later without anyone running anything. Both write the same page at once: GBrain still sees one page, not two. |
|
||||
|
||||
Only the current milestone gets detailed below. The next one is detailed when the current one is accepted.
|
||||
|
||||
@@ -192,8 +193,43 @@ This milestone ships **macOS (Apple silicon) only** (§8). The code stays portab
|
||||
### Out of scope for M7
|
||||
Windows and Linux installers, Intel Macs, server install script (D2), OS code signing (D4), security audit and release evidence (before a wider rollout, not the pilot).
|
||||
|
||||
## 6b. Milestone 8 — My agents share one GBrain *(draft, queued after M7)*
|
||||
|
||||
### Goal
|
||||
A vault that GBrain (https://github.com/garrytan/gbrain) uses as its brain syncs through Lune without making that brain messy. Every device's agent answers from the latest notes, and a clash never shows up in GBrain as a second copy of a page.
|
||||
|
||||
Why: GBrain indexes every Markdown file, so S4's `name (Label's version).md` becomes a duplicate page; and no device refreshes its GBrain index after notes arrive.
|
||||
|
||||
### What a person does
|
||||
- Marks a vault as a GBrain brain, in the canvas or the window (`lunesync vault kind <vault> gbrain`). Lune suggests it when it finds `gbrain.yml` or `.gbrain-source` in the vault. The vault shows a "GBrain" badge.
|
||||
- On each device where the `gbrain` command is found, the vault shows "Refresh GBrain after sync: on" (asked once). After that the person never runs GBrain commands themselves.
|
||||
|
||||
### Behavior
|
||||
GBrain vaults only; Obsidian vaults behave exactly as before.
|
||||
- **Refresh after sync.** After a sync that brought changes, Lune runs `gbrain sync --source <name> --no-pull` in the background (Lune does the pulling; GBrain only reads committed files by default, and Lune commits every burst). The source name is per device and defaults to the vault name. Lune looks for `gbrain` in the usual install places, not only the shell's PATH. It never holds up syncing. If it fails, the vault shows amber "GBrain not refreshed" with **Retry**.
|
||||
- **Both sides added lines in the same spot** → keep both, incoming first, then this device's. No clash copy.
|
||||
- **Same lines changed on both sides** → the incoming version stays in place. This device's version is not written into the vault folder; it is kept on this device, outside the vault's files (inside `.git/`, which GBrain never reads), under **Notes to tidy** (window, canvas, `lunesync tidy`) until resolved. This applies everywhere Lune would otherwise keep both copies (syncing, undo, handovers, held notes).
|
||||
- **The vault's kind is set on the hub**, so every device agrees. A GBrain vault therefore has to live on a Lune hub, not a plain Git remote.
|
||||
- **Ignore defaults**: `.gbrain-source` (a per-device source pin). `gbrain.yml` is shared.
|
||||
- The secret check (P2) and the runaway guard (S6) apply as before.
|
||||
|
||||
### Acceptance — Sen acts this out
|
||||
1. Mark Brain as a GBrain brain. Laptop "Codex" and VPS "Hermes" both point GBrain at their copy.
|
||||
2. Codex adds a page. Within about a minute `gbrain query` on the VPS finds it, with nothing run by hand.
|
||||
3. Both agents append to the same page's timeline at once: the page has both entries, and there is no copy file.
|
||||
4. Both rewrite the same paragraph: one stays, the other waits under Notes to tidy on its own device. `gbrain query` on either device returns one page. Tidy it and the result reaches both.
|
||||
5. Break GBrain on the VPS (rename the binary): the vault turns amber, notes keep syncing, and Retry works after fixing it.
|
||||
6. An Obsidian vault next to it behaves as before, including `(Label's version).md` copies.
|
||||
|
||||
### Out of scope for M8
|
||||
Installing or running GBrain for people, MCP through Lune, hosted gbrain.io, a shared Supabase database, parsing GBrain page sections.
|
||||
|
||||
### Open questions for M8
|
||||
1. Whether GBrain's upkeep (dream cycle, `gbrain maintain`) trips the runaway guard and needs a per-vault "trust big rewrites from this device" switch. Decide after a real GBrain run on Brain.
|
||||
2. GBrain can write into the vault itself: it edits a managed block in `.gitignore` after each sync, and its default (mixed) mode can create and commit pages. Lune would share those like any edit. Confirm that's fine on a real run, or suggest `GBRAIN_NO_GITIGNORE=1`.
|
||||
|
||||
## 7. Open questions
|
||||
None open.
|
||||
None open for M7. M8's are in §6b.
|
||||
|
||||
## 8. Decision changes
|
||||
Record here: date, what changed, why, which decision number. Example:
|
||||
@@ -212,3 +248,5 @@ Record here: date, what changed, why, which decision number. Example:
|
||||
- 2026-10-29 — A vault's settings decide where it shares: a folder found pointing elsewhere is set back. A leaving device whose older history has a possible secret hands over its current notes as one entry with those lines replaced, instead of never finishing (A6, P3). (Sen, after the Brain mix-up)
|
||||
- 2026-10-29 — Uploading checks everything first, the way the hub will: a vault on one device only holds every line that looks like a secret for a decision; "not a secret" marks travel to the team; history with one goes up as a fresh start. Nothing is made on the team until it passes. A vault on one device joins a same-named team vault only if they share history; otherwise the team's arrives beside it (P2, P3). (Sen, after the Brain upload)
|
||||
- 2026-10-29 — Community release without Apple signing, under AGPL-3.0-only; the public repo stays at git.senkensha.space. (Sen)
|
||||
- 2026-11-16 — For GBrain vaults, S4 changes: the losing version of a same-lines clash is kept only on its own device under Notes to tidy, never written into the vault folder; lines both sides added are kept, incoming first (S4, M8). (Sen)
|
||||
- 2026-11-16 — A vault's kind (Obsidian / GBrain) is a hub setting, so a GBrain vault must be on a hub; Brain moves from Gitea to the hub before M8's acceptance (M8). (Sen)
|
||||
|
||||
@@ -246,13 +246,15 @@ pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
})));
|
||||
}
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT v.id, v.name, m.role FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
|
||||
"SELECT v.id, v.name, m.role, v.kind FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
|
||||
)?;
|
||||
let vaults: Vec<Value> = stmt
|
||||
.query_map([caller.account_id], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?
|
||||
.query_map([caller.account_id], |r| {
|
||||
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?))
|
||||
})?
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.into_iter()
|
||||
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) }))
|
||||
.map(|(id, name, role, kind)| json!({ "id": id, "name": name, "role": role, "kind": kind, "git_url": hub.git_url(id) }))
|
||||
.collect();
|
||||
// A Nudge is delivered once: the device shares at once, and the flag clears.
|
||||
let nudge: bool = conn
|
||||
|
||||
@@ -106,6 +106,11 @@ pub fn open(data: &Path) -> Result<Connection> {
|
||||
("devices", "last_seen INTEGER"),
|
||||
("devices", "nudge INTEGER NOT NULL DEFAULT 0"),
|
||||
("vaults", "archived INTEGER"),
|
||||
// M8: what a vault is for (existing vaults stay Obsidian), and whether the GBrain hint was dismissed.
|
||||
("vaults", "kind TEXT NOT NULL DEFAULT 'obsidian'"),
|
||||
("vaults", "hint_dismissed INTEGER NOT NULL DEFAULT 0"),
|
||||
("device_status", "gbrain_failed INTEGER NOT NULL DEFAULT 0"),
|
||||
("device_status", "to_tidy INTEGER NOT NULL DEFAULT 0"),
|
||||
] {
|
||||
let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ pub struct VaultReport {
|
||||
waiting: i64,
|
||||
held_secrets: i64,
|
||||
holding: bool,
|
||||
/// GBrain vaults: this device's last refresh failed.
|
||||
#[serde(default)]
|
||||
gbrain_failed: bool,
|
||||
/// GBrain vaults: notes whose version from this device waits under Notes to tidy (older clients send none).
|
||||
#[serde(default)]
|
||||
to_tidy: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -47,8 +53,8 @@ pub async fn report(State(hub): State<Shared>, headers: HeaderMap, Json(req): Js
|
||||
continue;
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO device_status (device_id, vault_id, last_synced, waiting, held_secrets, holding) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
params![caller.device_id, v.vault_id, v.last_synced, v.waiting, v.held_secrets, v.holding],
|
||||
"INSERT INTO device_status (device_id, vault_id, last_synced, waiting, held_secrets, holding, gbrain_failed, to_tidy) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
params![caller.device_id, v.vault_id, v.last_synced, v.waiting, v.held_secrets, v.holding, v.gbrain_failed, v.to_tidy],
|
||||
)?;
|
||||
}
|
||||
Ok(Json(json!({})))
|
||||
@@ -57,23 +63,24 @@ pub async fn report(State(hub): State<Shared>, headers: HeaderMap, Json(req): Js
|
||||
/// A device's freshness for the canvas, from its last report.
|
||||
pub fn device_health(conn: &Connection, device_id: &str) -> Result<Value> {
|
||||
let last_seen: Option<i64> = conn.query_row("SELECT last_seen FROM devices WHERE id = ?1", [device_id], |r| r.get(0))?;
|
||||
let (oldest_sync, waiting, held_secrets, holding): (Option<i64>, i64, i64, bool) = conn.query_row(
|
||||
"SELECT MIN(last_synced), COALESCE(SUM(waiting), 0), COALESCE(SUM(held_secrets), 0), COALESCE(MAX(holding), 0)
|
||||
let (oldest_sync, waiting, held_secrets, holding, gbrain_failed): (Option<i64>, i64, i64, bool, bool) = conn.query_row(
|
||||
"SELECT MIN(last_synced), COALESCE(SUM(waiting), 0), COALESCE(SUM(held_secrets), 0), COALESCE(MAX(holding), 0),
|
||||
COALESCE(MAX(gbrain_failed), 0)
|
||||
FROM device_status WHERE device_id = ?1",
|
||||
[device_id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
|
||||
)?;
|
||||
let online = last_seen.is_some_and(|t| db::now() - t <= OFFLINE_AFTER);
|
||||
let status = if !online {
|
||||
"offline"
|
||||
} else if waiting > 0 || holding || held_secrets > 0 {
|
||||
} else if waiting > 0 || holding || held_secrets > 0 || gbrain_failed {
|
||||
"behind"
|
||||
} else {
|
||||
"current"
|
||||
};
|
||||
Ok(json!({
|
||||
"status": status, "last_seen": last_seen, "last_synced": oldest_sync,
|
||||
"waiting": waiting, "held_secrets": held_secrets, "holding": holding
|
||||
"waiting": waiting, "held_secrets": held_secrets, "holding": holding, "gbrain_failed": gbrain_failed
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -103,6 +110,32 @@ pub async fn nudge(State(hub): State<Shared>, headers: HeaderMap, Json(req): Jso
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
/// Labels of the devices whose last GBrain refresh failed, for one vault.
|
||||
pub fn gbrain_stale(conn: &Connection, vault_id: i64) -> Result<Vec<String>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT d.label FROM device_status s JOIN devices d ON d.id = s.device_id
|
||||
WHERE s.vault_id = ?1 AND s.gbrain_failed = 1 AND d.removed = 0 ORDER BY d.label",
|
||||
)?;
|
||||
Ok(stmt.query_map([vault_id], |r| r.get(0))?.collect::<Result<_, _>>()?)
|
||||
}
|
||||
|
||||
/// Devices holding notes to tidy for one vault: (device label, count). The versions themselves stay on the device.
|
||||
pub fn tidy_on_devices(conn: &Connection, vault_id: i64) -> Result<Vec<(String, i64)>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT d.label, s.to_tidy FROM device_status s JOIN devices d ON d.id = s.device_id
|
||||
WHERE s.vault_id = ?1 AND s.to_tidy > 0 AND d.removed = 0 ORDER BY d.label",
|
||||
)?;
|
||||
Ok(stmt.query_map([vault_id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<Result<_, _>>()?)
|
||||
}
|
||||
|
||||
/// Does the vault's shared copy hold a file at its root that says "this is a GBrain"?
|
||||
pub fn has_gbrain_marker(repo_path: &Path) -> bool {
|
||||
let Ok(repo) = Repository::open_bare(repo_path) else { return false };
|
||||
let Ok(Some(main)) = main_ref(&repo) else { return false };
|
||||
let Ok(tree) = repo.find_reference(&main).and_then(|r| r.peel_to_tree()) else { return false };
|
||||
["gbrain.yml", ".gbrain-source"].iter().any(|m| tree.get_name(m).is_some())
|
||||
}
|
||||
|
||||
/// Notes kept in two versions in a vault's shared copy: (note, copy, device label).
|
||||
pub fn kept_both(repo_path: &Path) -> Result<Vec<(String, String, String)>> {
|
||||
let repo = Repository::open_bare(repo_path)?;
|
||||
|
||||
167
hub/src/leave.rs
167
hub/src/leave.rs
@@ -289,6 +289,36 @@ pub async fn vault_settings(State(hub): State<Shared>, headers: HeaderMap, Json(
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct KindReq {
|
||||
vault: String,
|
||||
/// obsidian or gbrain; leave out to change nothing.
|
||||
kind: Option<String>,
|
||||
/// Hide the "this looks like a GBrain" suggestion.
|
||||
#[serde(default)]
|
||||
dismiss_suggestion: bool,
|
||||
}
|
||||
|
||||
/// What a vault is for (M8): Obsidian by default, or a GBrain brain. Set here so every device agrees.
|
||||
pub async fn vault_kind(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<KindReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (id, name) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
|
||||
if !can_manage(&conn, &caller, id)? {
|
||||
return Err(denied(format!("you need Manage on {name}")));
|
||||
}
|
||||
if let Some(kind) = &req.kind {
|
||||
let kind = lune_core::config::VaultKind::parse(kind).ok_or_else(|| bad("a vault's kind is obsidian or gbrain"))?;
|
||||
conn.execute("UPDATE vaults SET kind = ?1 WHERE id = ?2", params![kind.as_str(), id])?;
|
||||
let word = if kind == lune_core::config::VaultKind::Gbrain { "GBrain" } else { "Obsidian" };
|
||||
db::log(&conn, &caller.who(), "vault setting", &format!("{name}: kind set to {word}"))?;
|
||||
}
|
||||
if req.dismiss_suggestion {
|
||||
conn.execute("UPDATE vaults SET hint_dismissed = 1 WHERE id = ?1", [id])?;
|
||||
}
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DoneReq {
|
||||
id: i64,
|
||||
@@ -361,23 +391,45 @@ fn already_shared(repo: &Repository, head: Oid) -> Result<bool> {
|
||||
Ok(tip == head || repo.graph_descendant_of(tip, head)?)
|
||||
}
|
||||
|
||||
/// Combines a handover into the vault's main line; same-lines clashes keep both, labeled with `label`.
|
||||
fn keep_handover(repo_path: &Path, id: i64, label: &str) -> Result<usize> {
|
||||
/// What keeping a handover did with notes both sides changed: (copies made, notes where both sides' added lines
|
||||
/// were kept, notes where the handover's version went in place of the team's earlier one).
|
||||
#[derive(Default)]
|
||||
pub struct HandoverClashes {
|
||||
pub copies: usize,
|
||||
pub joined: usize,
|
||||
pub replaced: usize,
|
||||
}
|
||||
|
||||
/// Combines a handover into the vault's main line. Obsidian vaults: same-lines clashes keep both, labeled with
|
||||
/// `label`. GBrain vaults never get a copy: lines both added are all kept, and where the same lines changed the
|
||||
/// handover's version goes in place (the manager chose Keep); the team's earlier version stays in the vault's
|
||||
/// history, so nothing is lost.
|
||||
pub fn keep_handover(repo_path: &Path, id: i64, label: &str, kind: lune_core::config::VaultKind) -> Result<HandoverClashes> {
|
||||
let repo = Repository::open_bare(repo_path)?;
|
||||
let mut handover_ref = repo.find_reference(&format!("refs/handover/{id}"))?;
|
||||
let handover = handover_ref.peel_to_commit()?;
|
||||
let Some(main) = main_ref(&repo)? else {
|
||||
repo.reference("refs/heads/main", handover.id(), false, "lune: kept handover")?;
|
||||
handover_ref.delete()?;
|
||||
return Ok(0);
|
||||
return Ok(HandoverClashes::default());
|
||||
};
|
||||
let tip = repo.find_reference(&main)?.peel_to_commit()?;
|
||||
let mut kept = vec![];
|
||||
let mut out = HandoverClashes::default();
|
||||
if repo.graph_descendant_of(handover.id(), tip.id())? {
|
||||
repo.reference_matching(&main, handover.id(), true, tip.id(), "lune: kept handover")?;
|
||||
} else if !repo.graph_descendant_of(tip.id(), handover.id())? {
|
||||
let mut index = repo.merge_commits(&tip, &handover, None)?;
|
||||
lune_core::vault::keep_both(&mut index, label, &mut kept)?;
|
||||
let style = match kind {
|
||||
lune_core::config::VaultKind::Gbrain => lune_core::vault::ClashStyle::Gbrain,
|
||||
lune_core::config::VaultKind::Obsidian => lune_core::vault::ClashStyle::Copies { label },
|
||||
};
|
||||
for k in lune_core::vault::keep_both(&repo, &mut index, style)? {
|
||||
match k {
|
||||
lune_core::vault::Kept::Copied { .. } => out.copies += 1,
|
||||
lune_core::vault::Kept::Joined { .. } => out.joined += 1,
|
||||
lune_core::vault::Kept::Aside { .. } => out.replaced += 1,
|
||||
}
|
||||
}
|
||||
let tree = repo.find_tree(index.write_tree_to(&repo)?)?;
|
||||
let sig = Signature::now(label, "handover@lune.device")?;
|
||||
let msg = format!("Kept the handover from {label}");
|
||||
@@ -385,7 +437,7 @@ fn keep_handover(repo_path: &Path, id: i64, label: &str) -> Result<usize> {
|
||||
repo.reference_matching(&main, id, true, tip.id(), "lune: kept handover")?;
|
||||
}
|
||||
handover_ref.delete()?;
|
||||
Ok(kept.len())
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Departures in vaults the caller manages (all of them for the owner), newest first.
|
||||
@@ -479,8 +531,19 @@ pub async fn handover_decide(State(hub): State<Shared>, headers: HeaderMap, Json
|
||||
let (vault_id, vault, device, state) = departure_for(&conn, &caller, req.id)?;
|
||||
let (new_state, message) = match (req.decision.as_str(), state.as_str()) {
|
||||
("keep", "received") => {
|
||||
let clashes = keep_handover(&hub.repo_path(vault_id), req.id, &device)?;
|
||||
let extra = if clashes > 0 { format!(" ({clashes} note(s) changed in two places: both versions kept)") } else { String::new() };
|
||||
let kind: String = conn.query_row("SELECT kind FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0))?;
|
||||
let kind = lune_core::config::VaultKind::parse(&kind).unwrap_or_default();
|
||||
let c = keep_handover(&hub.repo_path(vault_id), req.id, &device, kind)?;
|
||||
let mut extra = String::new();
|
||||
if c.copies > 0 {
|
||||
extra.push_str(&format!(" ({} note(s) changed in two places: both versions kept)", c.copies));
|
||||
}
|
||||
if c.joined > 0 {
|
||||
extra.push_str(&format!(" ({} note(s) had lines added in both places: all kept)", c.joined));
|
||||
}
|
||||
if c.replaced > 0 {
|
||||
extra.push_str(&format!(" ({} note(s) changed in the same lines in both places: {device}'s version is in place, the earlier one stays in the vault's history)", c.replaced));
|
||||
}
|
||||
("kept", format!("Kept {device}'s handover in {vault}{extra}. It reaches every device on its next sync."))
|
||||
}
|
||||
("discard", "received") => {
|
||||
@@ -503,3 +566,91 @@ pub async fn handover_decide(State(hub): State<Shared>, headers: HeaderMap, Json
|
||||
db::log(&conn, &caller.who(), &format!("handover {new_state}"), &format!("{device} in {vault}"))?;
|
||||
Ok(Json(json!({ "message": message })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lune_core::config::VaultKind;
|
||||
use lune_core::git2::{TreeWalkMode, TreeWalkResult};
|
||||
use lune_core::names;
|
||||
|
||||
/// A bare vault with main at "base", plus a handover from a device that changed the same note.
|
||||
fn setup(base: &str, team: &str, away: &str) -> (tempfile::TempDir, std::path::PathBuf) {
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let path = tmp.path().join("v.git");
|
||||
let repo = Repository::init_bare(&path).unwrap();
|
||||
let sig = Signature::now("t", "t@lune.device").unwrap();
|
||||
let commit = |text: &str, parent: Option<&lune_core::git2::Commit>, update: Option<&str>| {
|
||||
let blob = repo.blob(text.as_bytes()).unwrap();
|
||||
let mut tb = repo.treebuilder(None).unwrap();
|
||||
tb.insert("page.md", blob, 0o100644).unwrap();
|
||||
let tree = repo.find_tree(tb.write().unwrap()).unwrap();
|
||||
let parents: Vec<_> = parent.into_iter().collect();
|
||||
repo.commit(update, &sig, &sig, "x", &tree, &parents).unwrap()
|
||||
};
|
||||
let root = commit(base, None, Some("refs/heads/main"));
|
||||
let root = repo.find_commit(root).unwrap();
|
||||
commit(team, Some(&root), Some("refs/heads/main"));
|
||||
let h = commit(away, Some(&root), None);
|
||||
repo.reference("refs/handover/7", h, true, "test").unwrap();
|
||||
repo.set_head("refs/heads/main").unwrap();
|
||||
(tmp, path)
|
||||
}
|
||||
|
||||
fn main_files(path: &Path) -> Vec<(String, String)> {
|
||||
let repo = Repository::open_bare(path).unwrap();
|
||||
let tree = repo.find_reference("refs/heads/main").unwrap().peel_to_tree().unwrap();
|
||||
let mut out = vec![];
|
||||
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
|
||||
let b = e.to_object(&repo).unwrap().peel_to_blob().unwrap();
|
||||
out.push((format!("{dir}{}", e.name().unwrap()), String::from_utf8_lossy(b.content()).into_owned()));
|
||||
TreeWalkResult::Ok
|
||||
})
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
fn any_copy_in_history(path: &Path) -> bool {
|
||||
let repo = Repository::open_bare(path).unwrap();
|
||||
let mut walk = repo.revwalk().unwrap();
|
||||
walk.push_ref("refs/heads/main").unwrap();
|
||||
walk.any(|id| {
|
||||
let tree = repo.find_commit(id.unwrap()).unwrap().tree().unwrap();
|
||||
let mut found = false;
|
||||
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
|
||||
found |= names::parse_copy(&format!("{dir}{}", e.name().unwrap())).is_some();
|
||||
TreeWalkResult::Ok
|
||||
})
|
||||
.unwrap();
|
||||
found
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeping_a_handover_makes_no_copy_in_a_gbrain_vault() {
|
||||
// Same lines changed: the handover's version goes in place, no copy anywhere.
|
||||
let (_t, path) = setup("a\nb\nc\n", "a\nteam\nc\n", "a\naway\nc\n");
|
||||
let c = keep_handover(&path, 7, "Old laptop", VaultKind::Gbrain).unwrap();
|
||||
assert_eq!((c.copies, c.joined, c.replaced), (0, 0, 1));
|
||||
assert_eq!(main_files(&path), vec![("page.md".to_string(), "a\naway\nc\n".to_string())]);
|
||||
assert!(!any_copy_in_history(&path));
|
||||
|
||||
// Lines both added at the end: all kept, the earlier team lines first-in-place rule applies (handover first).
|
||||
let (_t, path) = setup("a\n", "a\nteam\n", "a\naway\n");
|
||||
let c = keep_handover(&path, 7, "Old laptop", VaultKind::Gbrain).unwrap();
|
||||
assert_eq!((c.copies, c.joined, c.replaced), (0, 1, 0));
|
||||
let files = main_files(&path);
|
||||
assert_eq!(files.len(), 1);
|
||||
assert!(files[0].1.contains("team") && files[0].1.contains("away"), "{files:?}");
|
||||
assert!(!any_copy_in_history(&path));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeping_a_handover_in_an_obsidian_vault_still_makes_a_copy() {
|
||||
let (_t, path) = setup("a\nb\nc\n", "a\nteam\nc\n", "a\naway\nc\n");
|
||||
let c = keep_handover(&path, 7, "Old laptop", VaultKind::Obsidian).unwrap();
|
||||
assert_eq!((c.copies, c.joined, c.replaced), (1, 0, 0));
|
||||
let files = main_files(&path);
|
||||
assert!(files.iter().any(|(p, _)| p == "page (Old laptop's version).md"), "{files:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +109,7 @@ async fn serve() -> Result<()> {
|
||||
.route("/api/team/remove", post(leave::team_remove))
|
||||
.route("/api/team/restore", post(leave::team_restore))
|
||||
.route("/api/vaults/settings", post(leave::vault_settings))
|
||||
.route("/api/vaults/kind", post(leave::vault_kind))
|
||||
.route("/api/vaults/delete", post(leave::delete_vault))
|
||||
.route("/api/departures/done", post(leave::departure_done))
|
||||
.route("/api/handovers", get(leave::handovers))
|
||||
|
||||
@@ -115,20 +115,20 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
|
||||
let vault_rows: Vec<(i64, String, bool)> = {
|
||||
let vault_rows: Vec<(i64, String, bool, String, bool)> = {
|
||||
let sql = if caller.owner {
|
||||
"SELECT id, name, delete_from_devices FROM vaults WHERE archived IS NULL ORDER BY created, id"
|
||||
"SELECT id, name, delete_from_devices, kind, hint_dismissed FROM vaults WHERE archived IS NULL ORDER BY created, id"
|
||||
} else {
|
||||
"SELECT v.id, v.name, v.delete_from_devices FROM vaults v JOIN memberships m ON m.vault_id = v.id
|
||||
"SELECT v.id, v.name, v.delete_from_devices, v.kind, v.hint_dismissed FROM vaults v JOIN memberships m ON m.vault_id = v.id
|
||||
WHERE m.account_id = ?1 ORDER BY v.created, v.id"
|
||||
};
|
||||
let mut stmt = conn.prepare(sql)?;
|
||||
let map = |r: &rusqlite::Row| Ok((r.get(0)?, r.get(1)?, r.get(2)?));
|
||||
let map = |r: &rusqlite::Row| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?));
|
||||
if caller.owner { stmt.query_map([], map)?.collect::<Result<_, _>>()? } else { stmt.query_map([caller.account_id], map)?.collect::<Result<_, _>>()? }
|
||||
};
|
||||
let mut vaults = vec![];
|
||||
let mut managed = vec![];
|
||||
for (id, name, delete_files) in &vault_rows {
|
||||
for (id, name, delete_files, kind, dismissed) in &vault_rows {
|
||||
let manage = can_manage(&conn, &caller, *id)?;
|
||||
if manage {
|
||||
managed.push(*id);
|
||||
@@ -151,9 +151,18 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
// GBrain (M8): managers see which devices couldn't refresh it, and a hint when the vault looks like one.
|
||||
let gbrain_stale = if manage && kind == "gbrain" { crate::health::gbrain_stale(&conn, *id).unwrap_or_default() } else { vec![] };
|
||||
let tidy_on: Vec<Value> = crate::health::tidy_on_devices(&conn, *id)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(device, count)| json!({ "device": device, "count": count }))
|
||||
.collect();
|
||||
let suggest_gbrain = manage && kind != "gbrain" && !dismissed && crate::health::has_gbrain_marker(&hub.repo_path(*id));
|
||||
vaults.push(json!({
|
||||
"id": format!("v{id}"), "name": name, "can_manage": manage, "delete_from_devices": delete_files,
|
||||
"tidy": tidy, "handovers": handovers
|
||||
"kind": kind, "gbrain_stale": gbrain_stale, "suggest_gbrain": suggest_gbrain,
|
||||
"tidy": tidy, "tidy_on": tidy_on, "handovers": handovers
|
||||
}));
|
||||
}
|
||||
let visible: Vec<i64> = vault_rows.iter().map(|v| v.0).collect();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The hub end to end: one-time links, pairing, roles enforced by the hub, secrets refused (P3).
|
||||
|
||||
use lune_core::config::VaultKind;
|
||||
use lune_core::hub::{self, HubLink};
|
||||
use lune_core::vault::{self, Vault};
|
||||
use lune_core::{remote, secrets, state};
|
||||
@@ -354,7 +355,7 @@ fn health_nudge_and_tidy() {
|
||||
let codex = as_device(&url, &sen_w);
|
||||
std::fs::write(a.root.join("draft.md"), "unsaved\n").unwrap();
|
||||
codex
|
||||
.report(&[hub::VaultHealth { vault_id: devops.id, last_synced: Some(1), waiting: 1, held_secrets: 0, holding: false }])
|
||||
.report(&[hub::VaultHealth { vault_id: devops.id, last_synced: Some(1), waiting: 1, held_secrets: 0, holding: false, gbrain_failed: false, to_tidy: 0 }])
|
||||
.unwrap();
|
||||
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
|
||||
@@ -616,6 +617,7 @@ fn deleting_a_vault_and_leaving_a_team() {
|
||||
branch: "main".into(),
|
||||
hub_vault: Some(1),
|
||||
hub_url: Some("http://127.0.0.1:9".into()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", false).is_err());
|
||||
lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", true).unwrap();
|
||||
@@ -818,3 +820,70 @@ fn a_folder_follows_its_settings() {
|
||||
assert_eq!(v.remote_url().as_deref(), Some(cfg.remote.as_str()));
|
||||
assert!(v.follow("").unwrap() && v.is_local());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vaults_kind_is_set_on_the_hub_and_every_device_follows() {
|
||||
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("cfg")) };
|
||||
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
|
||||
let (_, sen_w) = hub::join(&owner_link, "Mac").unwrap();
|
||||
let mut mac = device(&url, &sen_w, "Mac", &tmp.path().join("mac"));
|
||||
mac.use_hub_credentials();
|
||||
let link = mac.hubs[0].clone();
|
||||
link.create_vault("Brain").unwrap();
|
||||
// Existing and new vaults are Obsidian until someone says otherwise.
|
||||
assert_eq!(link.me().unwrap().vaults[0].kind, VaultKind::Obsidian);
|
||||
check_in(&mut mac);
|
||||
assert_eq!(mac.find("Brain").unwrap().kind, VaultKind::Obsidian);
|
||||
|
||||
// A Read member can't change it; Manage (here the owner) can, and it's logged.
|
||||
let invite = link.invite("Bob", &[("Brain".into(), "read".into())]).unwrap();
|
||||
let (_, bob_w) = hub::join(&invite, "Bob pc").unwrap();
|
||||
let bob = as_device(&url, &bob_w);
|
||||
let err = format!("{:#}", bob.vault_kind("Brain", Some(VaultKind::Gbrain), false).unwrap_err());
|
||||
assert!(err.contains("Manage"), "{err}");
|
||||
assert!(link.vault_kind("Brain", Some(VaultKind::Gbrain), false).is_ok());
|
||||
assert_eq!(bob.me().unwrap().vaults[0].kind, VaultKind::Gbrain);
|
||||
let log = link.log(20).unwrap();
|
||||
assert!(log.iter().any(|e| e.action == "vault setting" && e.detail == "Brain: kind set to GBrain"), "{log:?}");
|
||||
|
||||
// The device learns it at its next check-in, keeps it in its config, and ignores the per-device pin.
|
||||
mac.use_hub_credentials();
|
||||
let said = check_in(&mut mac);
|
||||
assert!(said.iter().any(|m| m.contains("GBrain")), "{said:?}");
|
||||
assert_eq!(mac.find("Brain").unwrap().kind, VaultKind::Gbrain);
|
||||
assert_eq!(Config::load().unwrap().find("Brain").unwrap().kind, VaultKind::Gbrain);
|
||||
let v = open(&mac, "Brain");
|
||||
write_and_save(&v, ".gbrain-source", "brain\n");
|
||||
write_and_save(&v, "gbrain.yml", "x: 1\n");
|
||||
assert_eq!(v.tracked_files().unwrap(), vec!["gbrain.yml".to_string()]);
|
||||
|
||||
// A device whose refresh failed says so; the canvas shows the vault's kind and which device is stale.
|
||||
let vid = link.me().unwrap().vaults[0].id;
|
||||
link.report(&[hub::VaultHealth { vault_id: vid, last_synced: Some(db_now()), waiting: 0, held_secrets: 0, holding: false, gbrain_failed: true, to_tidy: 2 }])
|
||||
.unwrap();
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
|
||||
let res = agent.post(format!("{url}/api/web/signin")).send_json(serde_json::json!({ "code": link.pair().unwrap() })).unwrap();
|
||||
let session = res.headers().get("set-cookie").unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
|
||||
let canvas: serde_json::Value =
|
||||
agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap().body_mut().read_json().unwrap();
|
||||
assert_eq!(canvas["vaults"][0]["kind"], "gbrain");
|
||||
assert_eq!(canvas["vaults"][0]["gbrain_stale"], serde_json::json!(["Mac"]));
|
||||
// Versions kept on a device are counted, never shown: the canvas says how many wait on which device.
|
||||
assert_eq!(canvas["vaults"][0]["tidy_on"], serde_json::json!([{ "device": "Mac", "count": 2 }]));
|
||||
assert_eq!(canvas["people"][0]["devices"][0]["health"]["status"], "behind");
|
||||
link.report(&[hub::VaultHealth { vault_id: vid, last_synced: Some(db_now()), waiting: 0, held_secrets: 0, holding: false, gbrain_failed: false, to_tidy: 0 }])
|
||||
.unwrap();
|
||||
|
||||
// Back to Obsidian: the device follows that too.
|
||||
link.vault_kind("Brain", Some(VaultKind::Obsidian), false).unwrap();
|
||||
check_in(&mut mac);
|
||||
assert_eq!(mac.find("Brain").unwrap().kind, VaultKind::Obsidian);
|
||||
// The "this looks like a GBrain" hint can be dismissed.
|
||||
link.vault_kind("Brain", None, true).unwrap();
|
||||
}
|
||||
|
||||
fn db_now() -> i64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
|
||||
vaults.forEach((v, i) => {
|
||||
const p = pos(v.id), delay = (i * 0.7).toFixed(1), vo = relV(v.id) ? 1 : 0.35;
|
||||
// Amber means a decision is waiting (X6): notes to tidy, handovers to review.
|
||||
const review = v.handovers.filter((h) => h.state === 'received').length, tidy = v.tidy.length;
|
||||
const review = v.handovers.filter((h) => h.state === 'received').length, tidy = v.tidy.length + v.tidy_on.reduce((n, t) => n + t.count, 0);
|
||||
const decide = review + tidy;
|
||||
if (decide > 0) {
|
||||
labels.push({
|
||||
@@ -329,6 +329,13 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
|
||||
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontWeight: 700, fontSize: 'max(1.05cqw, 9px)', color: '#7A4500', background: '#FBEBD3', border: '1px solid #E09A2B', borderRadius: 999, padding: '0.15em 0.7em', animationDelay: `${delay}s` },
|
||||
});
|
||||
}
|
||||
if (v.kind === 'gbrain') {
|
||||
labels.push({
|
||||
text: 'GBrain',
|
||||
style: { ...pct(p.x - 34, p.y + 44), transform: 'translate(-50%,-50%)', opacity: vo },
|
||||
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontWeight: 700, fontSize: 'max(0.95cqw, 8px)', color: '#4A3A8F', background: '#ECE7FA', border: '1px solid #B9AEE8', borderRadius: 999, padding: '0.1em 0.6em', animationDelay: `${delay}s` },
|
||||
});
|
||||
}
|
||||
blobs.push({ d: roundRect(p.x, p.y, 138, 70, 26), fill: vaultColor(v.id).fill, delay, op: focus && relV(v.id) ? 1 : 0 });
|
||||
labels.push({
|
||||
text: v.name,
|
||||
@@ -568,6 +575,8 @@ export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload:
|
||||
cycleRole={cycleRole} remove={(m) => revoke(keyOf(m))} grant={grant} run={run}
|
||||
compare={(copy) => setSheet({ kind: 'compare', vault: vault(sel.id), copy })}
|
||||
deleteVault={data.me.owner ? (v) => setSheet({ kind: 'delete', v }) : undefined}
|
||||
setKind={(v, kind) => run(() => api.vaultKind(v.name, kind), kind === 'gbrain' ? `${v.name} is now a GBrain vault. Every device learns it within a minute.` : `${v.name} is an Obsidian vault again.`)}
|
||||
dismissHint={(v) => run(() => api.dismissGbrainHint(v.name))}
|
||||
toggleDelete={(v) => run(() => api.vaultSetting(v.name, !v.delete_from_devices), v.delete_from_devices ? `Removed people keep a read-only copy of ${v.name}.` : `Removed people's copies of ${v.name} are deleted from their devices.`)} />
|
||||
)}
|
||||
{sel.kind === 'person' && person(sel.id) && (
|
||||
@@ -685,7 +694,8 @@ function Overview({ data, members, log, open, close, newVault, signOut }: {
|
||||
);
|
||||
}
|
||||
|
||||
function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete, run, compare, deleteVault }: {
|
||||
function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete, run, compare, deleteVault, setKind, dismissHint }: {
|
||||
setKind: (v: Vault, kind: 'obsidian' | 'gbrain') => void; dismissHint: (v: Vault) => void;
|
||||
v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void; deleteVault?: (v: Vault) => void;
|
||||
cycleRole: (m: Member) => void; remove: (m: Member) => void; grant: (v: string, p: string) => void; toggleDelete: (v: Vault) => void;
|
||||
run: (action: () => Promise<unknown>, ok?: string) => Promise<void>; compare: (copy: string) => void;
|
||||
@@ -696,7 +706,7 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t
|
||||
return (
|
||||
<>
|
||||
<div className="panel-head">
|
||||
<div><span className="eyebrow">Vault · {plural(inVault.length, 'person', 'people')}</span><h2 className="disp">{v.name}</h2></div>
|
||||
<div><span className="eyebrow">Vault · {plural(inVault.length, 'person', 'people')}</span><h2 className="disp">{v.name}{v.kind === 'gbrain' && <span className="pill" style={{ background: '#ECE7FA', color: '#4A3A8F', marginLeft: 8, fontSize: 12, verticalAlign: 'middle' }}>GBrain</span>}</h2></div>
|
||||
<CloseButton close={close} />
|
||||
</div>
|
||||
{!v.can_manage && mine && <div className="note">You have {roleName(mine.role)} access. People with Manage decide who else can sync it.</div>}
|
||||
@@ -712,6 +722,29 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{v.tidy_on.length > 0 && (
|
||||
<div className="note amber">
|
||||
<b>{plural(v.tidy_on.reduce((n, t) => n + t.count, 0), 'note')} to tidy</b>
|
||||
<span>The same lines were changed in two places. The newer version is in the vault; the other is kept on the device that made it, outside the notes.</span>
|
||||
{v.tidy_on.map((t) => <span key={t.device}>{plural(t.count, 'note')} to tidy on {t.device}</span>)}
|
||||
</div>
|
||||
)}
|
||||
{v.gbrain_stale.length > 0 && (
|
||||
<div className="note amber">
|
||||
<b>GBrain not refreshed</b>
|
||||
<span>On {v.gbrain_stale.join(', ')}. Notes keep syncing; the device offers Retry.</span>
|
||||
</div>
|
||||
)}
|
||||
{v.suggest_gbrain && (
|
||||
<div className="note">
|
||||
<b>This looks like a GBrain</b>
|
||||
<span>Mark it as one and each device can keep GBrain up to date after notes arrive.</span>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn btn-small" onClick={() => dismissHint(v)}>Not now</button>
|
||||
<button className="btn btn-small btn-primary" onClick={() => setKind(v, 'gbrain')}>Mark as GBrain</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{v.handovers.map((h) => <HandoverCard key={h.id} h={h} vault={v} run={run} />)}
|
||||
<div>
|
||||
<h3>People with access</h3>
|
||||
@@ -741,6 +774,15 @@ function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, t
|
||||
<div className="chips">{outside.map((p) => <button key={p.id} className="btn btn-small" onClick={() => grant(v.id, p.id)}>+ {p.name}</button>)}</div>
|
||||
</div>
|
||||
)}
|
||||
{v.can_manage && (
|
||||
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<h3>What this vault is</h3>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={v.kind === 'gbrain'} onChange={() => setKind(v, v.kind === 'gbrain' ? 'obsidian' : 'gbrain')} />
|
||||
<span>A GBrain brain: devices keep GBrain up to date after notes arrive</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
{v.can_manage && (
|
||||
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<h3>When someone is removed</h3>
|
||||
|
||||
@@ -7,8 +7,15 @@ export interface Vault {
|
||||
name: string;
|
||||
can_manage: boolean;
|
||||
delete_from_devices: boolean;
|
||||
kind: 'obsidian' | 'gbrain';
|
||||
/** Managers: devices whose last GBrain refresh failed. */
|
||||
gbrain_stale: string[];
|
||||
/** Managers: the vault looks like a GBrain but isn't marked as one. */
|
||||
suggest_gbrain: boolean;
|
||||
/** Notes kept in two versions (S4), from the hub's copy. */
|
||||
tidy: { note: string; copy: string; label: string }[];
|
||||
/** GBrain vaults: devices that keep a version of some notes to themselves, waiting to be tidied there. */
|
||||
tidy_on: { device: string; count: number }[];
|
||||
/** Departures needing a manager: waiting for the device, or received for review. */
|
||||
handovers: { id: number; person: string; device: string; state: 'waiting' | 'received' }[];
|
||||
}
|
||||
@@ -22,6 +29,7 @@ export interface Health {
|
||||
waiting: number;
|
||||
held_secrets: number;
|
||||
holding: boolean;
|
||||
gbrain_failed: boolean;
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
@@ -105,6 +113,8 @@ export const api = {
|
||||
createVault: (name: string) => call<object>('POST', '/api/vaults', { name }),
|
||||
vaultSetting: (vault: string, deleteFromDevices: boolean) =>
|
||||
call<object>('POST', '/api/vaults/settings', { vault, delete_from_devices: deleteFromDevices }),
|
||||
vaultKind: (vault: string, kind: 'obsidian' | 'gbrain') => call<object>('POST', '/api/vaults/kind', { vault, kind }),
|
||||
dismissGbrainHint: (vault: string) => call<object>('POST', '/api/vaults/kind', { vault, dismiss_suggestion: true }),
|
||||
renameDevice: (deviceId: string, label: string) => call<object>('POST', '/api/devices/rename', { device_id: deviceId, label }),
|
||||
nudge: (deviceId: string) => call<object>('POST', '/api/nudge', { device_id: deviceId }),
|
||||
compare: (vault: string, copy: string) => call<Comparison>('POST', '/api/tidy/compare', { vault, copy }),
|
||||
|
||||
@@ -22,8 +22,14 @@ interface VaultStatus {
|
||||
running: boolean;
|
||||
held: { message: string; removed: number; rewritten: number; total: number }[];
|
||||
secrets: { path: string; found: string[] }[];
|
||||
tidy: { note: string; copy: string; label: string }[];
|
||||
tidy: { note: string; copy: string; label: string; local?: boolean; held?: boolean }[];
|
||||
case_clashes: string[];
|
||||
kind: 'obsidian' | 'gbrain';
|
||||
suggest_gbrain: boolean;
|
||||
gbrain: {
|
||||
refresh: boolean | null; source: string; found: boolean; ask: boolean; failed: boolean;
|
||||
error: string | null; refreshing: boolean; last_refreshed: number | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface Overview {
|
||||
@@ -156,12 +162,53 @@ function VaultCard({ v, several, canUpload, upload, act, compare }: {
|
||||
<div className="vault-head">
|
||||
<Dot level={v.level} />
|
||||
<div className="vault-name">
|
||||
<b>{v.name}{several && v.team && <span className="team-tag">{host(v.team)}</span>}</b>
|
||||
<b>{v.name}{several && v.team && <span className="team-tag">{host(v.team)}</span>}{v.kind === 'gbrain' && <span className="team-tag">GBrain</span>}</b>
|
||||
<span className="muted">{v.headline}</span>
|
||||
</div>
|
||||
{canUpload && !v.team && <button className="btn btn-small" onClick={() => upload(v)}>Upload</button>}
|
||||
<button className="btn btn-small btn-ghost" onClick={() => act('open_folder', { vault: v.name }, '')}>Open folder</button>
|
||||
</div>
|
||||
{v.suggest_gbrain && v.team && (
|
||||
<div className="need">
|
||||
<b>This looks like a GBrain</b>
|
||||
<span className="muted">Mark it as one and Lune keeps GBrain up to date here after notes arrive. Every device on the team learns it.</span>
|
||||
<div className="actions">
|
||||
<button className="btn btn-small" onClick={() => act('dismiss_gbrain_hint', { vault: v.name }, 'OK — not asking again')}>Not now</button>
|
||||
<button className="btn btn-small btn-primary" onClick={() => act('set_vault_kind', { vault: v.name, kind: 'gbrain' }, `${v.name} is now a GBrain vault`)}>Mark as GBrain</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{v.gbrain?.failed && (
|
||||
<div className="need">
|
||||
<b>GBrain not refreshed</b>
|
||||
<span className="muted">{v.gbrain.error ?? 'The last refresh did not finish.'} Your notes keep syncing.</span>
|
||||
<div className="actions">
|
||||
<button className="btn btn-small btn-primary" disabled={v.gbrain.refreshing} onClick={() => act('gbrain_retry', { vault: v.name }, 'Refreshing GBrain')}>{v.gbrain.refreshing ? 'Refreshing…' : 'Retry'}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{v.gbrain?.ask && (
|
||||
<div className="need">
|
||||
<b>Refresh GBrain after sync?</b>
|
||||
<span className="muted">GBrain is installed on this Mac. Lune can bring it up to date whenever notes arrive here, in the background.</span>
|
||||
<div className="actions">
|
||||
<button className="btn btn-small" onClick={() => act('gbrain_settings', { vault: v.name, refresh: false }, 'OK — GBrain is left alone')}>No</button>
|
||||
<button className="btn btn-small btn-primary" onClick={() => act('gbrain_settings', { vault: v.name, refresh: true }, 'GBrain will refresh after sync')}>Yes, refresh it</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{v.gbrain && v.gbrain.refresh !== null && (
|
||||
<div className="muted" style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<span>Refresh GBrain after sync: {v.gbrain.refresh ? 'on' : 'off'}</span>
|
||||
<button className="btn btn-small btn-ghost" onClick={() => act('gbrain_settings', { vault: v.name, refresh: !v.gbrain!.refresh }, v.gbrain!.refresh ? 'GBrain is left alone' : 'GBrain will refresh after sync')}>{v.gbrain.refresh ? 'Turn off' : 'Turn on'}</button>
|
||||
</div>
|
||||
)}
|
||||
{v.team && (
|
||||
<div className="muted" style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<span>{v.kind === 'gbrain' ? 'A GBrain vault' : 'An Obsidian vault'}</span>
|
||||
<button className="btn btn-small btn-ghost" onClick={() => act('set_vault_kind', { vault: v.name, kind: v.kind === 'gbrain' ? 'obsidian' : 'gbrain' }, v.kind === 'gbrain' ? `${v.name} is an Obsidian vault again` : `${v.name} is now a GBrain vault`)}>{v.kind === 'gbrain' ? 'Make it Obsidian' : 'Mark as GBrain'}</button>
|
||||
</div>
|
||||
)}
|
||||
{v.held.map((h) => (
|
||||
<div key={h.message} className="need">
|
||||
<b>A big change is waiting for you</b>
|
||||
@@ -176,7 +223,9 @@ function VaultCard({ v, several, canUpload, upload, act, compare }: {
|
||||
{v.tidy.map((t) => (
|
||||
<div key={t.copy} className="need">
|
||||
<b>{t.note} was changed in two places</b>
|
||||
<span className="muted">Both versions are kept; pick one when you have a moment.</span>
|
||||
<span className="muted">{t.local
|
||||
? (t.held ? "Your version is kept on this Mac, outside your notes, because it looked like it held a secret. Pick one when you have a moment." : "The other version is in your notes. Yours is kept on this Mac, outside them. Pick one when you have a moment.")
|
||||
: 'Both versions are kept; pick one when you have a moment.'}</span>
|
||||
<div className="actions">
|
||||
<button className="btn btn-small btn-primary" onClick={() => compare(v.name, t.copy)}>Compare</button>
|
||||
</div>
|
||||
@@ -194,7 +243,7 @@ function CompareSheet({ vault, copy, close, done }: { vault: string; copy: strin
|
||||
const keep = async (which: 'note' | 'copy' | 'both') => {
|
||||
try {
|
||||
await invoke('tidy', { vault, copy, keep: which });
|
||||
done(which === 'both' ? 'Kept both as separate notes' : 'Tidied — every device gets it shortly');
|
||||
done(which === 'both' ? 'Kept both' : 'Tidied — every device gets it shortly');
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user