Milestone 2: secret check and runaway guard

Notes with a likely secret on a new line are held on the device (own
short rule list, per SPEC §8); `lunesync held pointer|not-secret`
resolves them. Bursts removing or rewriting a big part of the vault are
saved but not shared until `lunesync held share|undo`. Incoming edits
to a held note land in place with the held version kept beside it.
Adds `tidy show` and SPEC §6 detail for M2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 00:08:02 +07:00
parent 25b8be5bbd
commit 62bc3db416
11 changed files with 963 additions and 55 deletions

View File

@@ -1,8 +1,10 @@
//! 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::guard::{self, Damage, HeldBurst};
use crate::names;
use crate::remote;
use crate::secrets::{self, Hit};
use crate::state;
use anyhow::{Context, Result, bail};
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
@@ -43,6 +45,15 @@ pub struct Saved {
pub id: Oid,
pub message: String,
pub files: Vec<String>,
/// Set when the runaway guard held this burst back.
pub held: Option<Damage>,
}
/// A note whose change is held back because it seems to contain a secret.
#[derive(Debug, Clone)]
pub struct SecretNote {
pub path: String,
pub hits: Vec<Hit>,
}
/// What one sync round did, in terms the run log can print.
@@ -60,6 +71,10 @@ pub struct SyncReport {
pub shared: usize,
/// Incoming changes touch a file that is still being edited here; they'll land after it settles.
pub waiting_for_local_edits: bool,
/// (note, copy) for held notes moved aside so an incoming version could land.
pub set_aside: Vec<(String, String)>,
/// A big change is held here, so nothing from this device was shared.
pub holding: bool,
}
impl Vault {
@@ -119,8 +134,20 @@ impl Vault {
self.repo.is_path_ignored(rel).unwrap_or(false)
}
/// Saves every changed file as one history entry, except paths in `skip` (still being written).
/// Saves every changed file as one history entry, except paths in `skip` (still being written)
/// and notes that seem to contain a secret. A runaway burst is saved but held (S6).
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
self.save(message, skip, true)
}
/// Like `save_changes`, without the runaway guard: for changes the app makes on the owner's say-so.
pub fn save_unguarded(&self, message: Option<&str>) -> Result<Option<Saved>> {
self.save(message, &HashSet::new(), false)
}
fn save(&self, message: Option<&str>, skip: &HashSet<String>, guarded: bool) -> Result<Option<Saved>> {
let mut skip = skip.clone();
skip.extend(self.secret_holds()?.into_iter().map(|n| n.path));
let mut index = self.repo.index()?;
index.read(false)?;
let mut filter = |p: &Path, _: &[u8]| -> i32 { if skip.contains(&names::slash_path(p)) { 1 } else { 0 } };
@@ -143,10 +170,107 @@ impl Vault {
Some(m) => m.to_string(),
None => describe_files(&diff),
};
let damage = match &old_tree {
Some(old) if guarded => Some(guard::assess(&self.repo, old, &tree)?).filter(|d| d.is_runaway()),
_ => None,
};
let sig = self.signature()?;
let parents: Vec<&Commit> = parent.iter().collect();
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
Ok(Some(Saved { id, message, files }))
if let Some(d) = damage {
let mut held = guard::load(&self.git_dir);
held.push(HeldBurst {
id: id.to_string(),
message: message.clone(),
removed: d.removed,
rewritten: d.rewritten,
total: d.total,
at: chrono::Utc::now().timestamp(),
});
guard::save(&self.git_dir, &held)?;
}
Ok(Some(Saved { id, message, files, held: damage }))
}
/// Changed notes (not yet saved) that seem to contain a secret on a new line.
pub fn secret_holds(&self) -> Result<Vec<SecretNote>> {
let allowed = secrets::load_allowed(&self.git_dir);
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
let mut known_blobs: Option<HashSet<Oid>> = None;
let mut opts = StatusOptions::new();
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false);
let mut out = vec![];
for entry in self.repo.statuses(Some(&mut opts))?.iter() {
let st = entry.status();
if st.is_wt_deleted() || st.is_index_deleted() {
continue;
}
let Ok(path) = entry.path() else { continue };
let Ok(bytes) = std::fs::read(self.root.join(path)) else { continue };
let old = match head_tree.as_ref().and_then(|t| t.get_path(Path::new(path)).ok()) {
Some(e) => Some(self.repo.find_blob(e.id())?.content().to_vec()),
None => {
// A new file whose exact bytes are already in the vault (a copy or a move) was already shared.
let known = known_blobs.get_or_insert_with(|| blob_ids(head_tree.as_ref()));
if known.contains(&Oid::hash_object(git2::ObjectType::Blob, &bytes)?) {
continue;
}
None
}
};
let hits = secrets::scan_bytes(&bytes, old.as_deref(), &allowed);
if !hits.is_empty() {
out.push(SecretNote { path: path.to_string(), hits });
}
}
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);
guard::save(&self.git_dir, &[])?;
Ok(held)
}
/// 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)>> {
let held = guard::load(&self.git_dir);
let mut kept_both = vec![];
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)?;
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)?;
let head_tree = head.tree()?;
let mut keep = TreeUpdateBuilder::new();
for d in added.deltas().filter(|d| d.status() == git2::Delta::Added) {
if let Some(p) = d.new_file().path()
&& let Ok(e) = head_tree.get_path(p)
{
keep.upsert(p, e.id(), file_mode(e.filemode()));
}
}
let tree = self.repo.find_tree(keep.create_updated(&self.repo, &reverted)?)?;
if tree.id() == head.tree_id() {
continue;
}
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, &format!("Undid: {}", h.message), &tree, &[&head])?;
self.move_to(id).map_err(|e| {
if e.code() == ErrorCode::Conflict {
anyhow::anyhow!("some of those notes are being edited right now — try again in a few seconds")
} else {
e.into()
}
})?;
}
guard::save(&self.git_dir, &[])?;
Ok(kept_both)
}
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
@@ -225,6 +349,7 @@ impl Vault {
let target = self.fix_case_clashes(target, &mut report)?;
let incoming = incoming.as_ref().unwrap();
self.note_incoming(local.as_ref(), incoming, target, &mut report)?;
self.set_aside_held_notes(target, &mut report)?;
match self.move_to(target) {
Ok(()) => {}
Err(e) if e.code() == ErrorCode::Conflict => {
@@ -244,6 +369,10 @@ impl Vault {
if ahead == 0 {
return Ok(report);
}
if !guard::load(&self.git_dir).is_empty() {
report.holding = true;
return Ok(report);
}
if self.push()? {
report.shared += ahead;
return Ok(report);
@@ -255,6 +384,20 @@ impl Vault {
/// Combines two lines of history. Same-lines clashes keep both: incoming in place, ours beside it (S4).
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
let mut index = self.repo.merge_commits(local, incoming, None)?;
self.keep_both(&mut index, &mut report.kept_both)?;
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let from = incoming.author().name().unwrap_or("another device").to_string();
let mut message = format!("Combined changes from {from}");
if !report.kept_both.is_empty() {
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
}
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
}
/// 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<()> {
if index.has_conflicts() {
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
for c in conflicts {
@@ -270,7 +413,7 @@ impl Vault {
.unwrap();
index.add(&stage0(&theirs, None))?;
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
report.kept_both.push((note, copy));
kept_both.push((note, copy));
}
// Different paths, or one side removed the note: keep whatever still exists.
(ours, theirs) => {
@@ -281,15 +424,7 @@ impl Vault {
}
}
}
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let from = incoming.author().name().unwrap_or("another device").to_string();
let mut message = format!("Combined changes from {from}");
if !report.kept_both.is_empty() {
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
}
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
Ok(())
}
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
@@ -366,6 +501,35 @@ impl Vault {
Ok(())
}
/// A held note can't take an incoming version in place, and must not wait for it either:
/// move the local version beside it (still held) and put back the saved one so the update lands.
fn set_aside_held_notes(&self, target: Oid, report: &mut SyncReport) -> Result<()> {
let held = self.secret_holds()?;
if held.is_empty() {
return Ok(());
}
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
let target_tree = self.repo.find_commit(target)?.tree()?;
for note in held {
let p = Path::new(&note.path);
let current = head_tree.as_ref().and_then(|t| t.get_path(p).ok()).map(|e| e.id());
let incoming = target_tree.get_path(p).ok().map(|e| e.id());
if current == incoming {
continue;
}
let copy = (1..)
.map(|n| names::copy_name(&note.path, &self.label, n))
.find(|c| !self.root.join(c).exists() && target_tree.get_path(Path::new(c)).is_err())
.unwrap();
std::fs::rename(self.root.join(p), self.root.join(&copy))?;
if let Some(id) = current {
std::fs::write(self.root.join(p), self.repo.find_blob(id)?.content())?;
}
report.set_aside.push((note.path, copy));
}
Ok(())
}
/// Writes `target` to the folder without touching anything that's still being edited, then makes it current.
fn move_to(&self, target: Oid) -> Result<(), git2::Error> {
let commit = self.repo.find_commit(target)?;
@@ -408,6 +572,17 @@ impl Vault {
}
}
fn blob_ids(tree: Option<&git2::Tree>) -> HashSet<Oid> {
let mut ids = HashSet::new();
if let Some(t) = tree {
let _ = t.walk(TreeWalkMode::PreOrder, |_, e| {
ids.insert(e.id());
TreeWalkResult::Ok
});
}
ids
}
fn stage0(e: &IndexEntry, path: Option<&[u8]>) -> IndexEntry {
let mut e = IndexEntry { path: e.path.clone(), ..*e };
e.flags = 0;
@@ -438,7 +613,12 @@ fn describe_files(diff: &git2::Diff) -> String {
};
return format!("{verb} {path}");
}
format!("Updated {} notes", deltas.len())
let verb = match deltas.iter().map(|d| d.status()).collect::<Vec<_>>() {
s if s.iter().all(|&x| x == git2::Delta::Deleted) => "Removed",
s if s.iter().all(|&x| matches!(x, git2::Delta::Added | git2::Delta::Untracked)) => "Added",
_ => "Updated",
};
format!("{verb} {} notes", deltas.len())
}
/// What `add` did with the folder.