Skip to main content

agentmux_srv_core/backend/vault/
sync_take.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A record from another machine, taken into the Vault (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md
5//! sections 6.2 to 6.5): the other half of [`super::sync_capture`], which writes this machine's changes into the log.
6//!
7//! [`Taker::receive`] hands a record to the sync layer with the Vault's adapter ([`super::sync_adapter`]), and when the layer
8//! makes it, or keeps it as the other side of a conflict, puts the result in the store:
9//! - A change that follows on from what this machine holds replaces the entry's value. The value it replaces is kept for 7 days
10//!   as a version, like an edit made here.
11//! - A change made apart from what this machine holds is a conflict, and a value is never merged: the later version is the
12//!   entry's value on every machine, and the other is kept as a version that says "changed on <machine> at the same time"
13//!   (`versions::KEPT_PREFIX`) and is not pruned. Only the tags are merged, as a union.
14//! - A tombstone deletes the entry, its versions and its grants, unless the entry has moved to another Vault, or a rotation of it
15//!   is waiting to be confirmed (then the delete is the kept side of a conflict, and the entry stays).
16//! - A change to an entry this machine deleted brings the entry back when it is the later of the two, under the id the record
17//!   names, and the delete is kept as a version that holds no value.
18//!
19//! A record names an entry by one of its link ids (`sync_links`), and never makes a second entry for an id that one entry
20//! has. A new entry is made with the ids the record carries, the record's own first, in the same transaction as its row, so a
21//! capture can never give a taken entry an id of its own in between.
22//!
23//! What the person keeps to themselves on this machine stays: the agents an entry is shared with and when it was last used are
24//! not replaced (`EntryBody::into_row`). What arrives is checked first: a kind this machine does not know, or a secret part the
25//! kind does not have, is not taken.
26//!
27//! Where a conflict keeps nothing in the store, the side that lost is still in the log, sealed: when the entry is deleted (a
28//! change made apart from a delete has nowhere to be kept once the entry is gone), and when the entry is not here to attach it to.
29//! A pane that lists conflicts reads it from there; this module only says so ([`Effect::KeptInLog`]).
30//!
31//! Taking and capturing run one at a time on one worker: both read the store, then write it, and neither locks the other out.
32
33use std::cell::RefCell;
34
35use super::kinds;
36use super::seal::{self, Key, Parts};
37use super::sync_activity::{self, ActivityBody};
38use super::sync_adapter::{merge_of, Kind, Rotations, VaultAdapter};
39use super::sync_capture;
40use super::sync_links::{self, LinkOwners, Links};
41use super::sync_merge::{self, Decision, Kept, Side as Chose};
42use super::sync_record::{EntryBody, Profiles};
43use super::sync_store::{apply_activity, links_of};
44use super::versions::{self, KEPT_PREFIX, PREVIOUS};
45use crate::backend::storage::store::Store;
46use crate::backend::storage::vault::VaultRow;
47use crate::backend::storage::vault_sync::TakeWrite;
48use crate::backend::storage::vault_versions::VaultVersionRow;
49use crate::backend::user_sync::adapter::{Adapter, Merge};
50use crate::backend::user_sync::hlc::Clock;
51use crate::backend::user_sync::log::{self, Outcome, Pins};
52use crate::backend::user_sync::record::{Header, Record};
53use crate::backend::user_sync::seal::{self as user_seal, KeyRing};
54
55/// What taking a record did to the store.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Effect {
58    /// Nothing: the record was held, older than what is here, void, or about an entry this machine does not have (a delete
59    /// of one it never had, or of one that moved to another Vault).
60    None,
61    /// The entry was made or its value replaced.
62    Wrote { entry: String },
63    /// The entry was deleted.
64    Deleted { entry: String },
65    /// An activity line another machine made was added to the lines shown with a Machine column.
66    Line { machine: String, seq: i64 },
67    /// A site grant another machine made was made here, for the entry.
68    Granted { entry: String },
69    /// A site grant another machine revoked was ended here, for the entry.
70    Revoked { entry: String },
71    /// The record was not taken into the store, and why (no value in it), and it is not going to be.
72    Skipped(String),
73    /// The record was not taken into the store yet, and why: a kind this version does not know, or an id another entry holds.
74    /// The log holds it and does not send it again, so [`Taker::retake`] takes it again from the log.
75    Deferred(String),
76    /// The side of a conflict that lost has nowhere in the store to be kept: it stays in the log, sealed.
77    KeptInLog(String),
78}
79
80/// What [`Taker::receive`] did: what the layer made of the record, what the store did, and the version a conflict kept.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Taken {
83    pub outcome: Outcome,
84    pub effect: Effect,
85    /// Why a version was kept ("changed on <machine> at the same time"), for a conflict.
86    pub kept: Option<String>,
87}
88
89/// Whether a rotation of the entry is waiting here, read before the log is locked (the store and the log are one connection).
90struct Rotating(bool);
91
92impl Rotations for Rotating {
93    fn rotating(&self, _record: &str) -> bool {
94        self.0
95    }
96}
97
98/// The Vault's adapter, keeping its last answer: the layer is told `Merge`, the take needs what was kept and why.
99struct Recording<'a> {
100    inner: VaultAdapter<'a>,
101    last: RefCell<Option<Decision>>,
102}
103
104impl Adapter for Recording<'_> {
105    fn merge(&self, local: Option<&Header>, incoming: &Header) -> Merge {
106        let decision = self.inner.decide(local, incoming);
107        let merge = merge_of(&decision);
108        *self.last.borrow_mut() = Some(decision);
109        merge
110    }
111}
112
113/// The ids the record's own entry may take: a retired one is allowed for `record`, which is a later change to the entry that
114/// had it (see `Store::vault_take_write`). Every other id is as `Store` answers.
115struct Reviving<'a> {
116    store: &'a Store,
117    record: &'a str,
118}
119
120impl LinkOwners for Reviving<'_> {
121    fn owner_of(&self, id: &str) -> Option<String> {
122        self.store.owner_of(id)
123    }
124    fn retired(&self, id: &str) -> bool {
125        id != self.record && self.store.retired(id)
126    }
127}
128
129/// The entry a record is about.
130enum Found {
131    None,
132    One(String),
133    /// The record's ids belong to two entries here.
134    Two,
135}
136
137/// This machine's side of the sync layer for the Vault: its store, the Vault's keys, this machine's own key, and its profiles.
138pub struct Taker<'a> {
139    /// This machine's id in the layer (the origin of its own records): the machine a version of its own is "changed on".
140    pub machine: &'a str,
141    pub store: &'a Store,
142    pub ring: &'a KeyRing,
143    /// This machine's own key, which seals the values it keeps.
144    pub key: &'a Key,
145    pub profiles: &'a dyn Profiles,
146}
147
148/// The body of `rec`, opened with the Vault's key at the place its header names.
149pub(super) fn open_body<T: serde::de::DeserializeOwned>(ring: &KeyRing, rec: &Record) -> Result<T, String> {
150    let plain = user_seal::open(ring, &rec.header, &rec.body).map_err(|e| match e {
151        user_seal::OpenError::NoKey => format!("no key for epoch {}", rec.header.epoch),
152        e => format!("a record that does not open: {e:?}"),
153    })?;
154    serde_json::from_slice(&plain).map_err(|_| "a record whose body is not what its id says".to_string())
155}
156
157/// Why a body is not taken, if it is not: it would make an entry the Vault cannot show or use.
158fn refused(body: &EntryBody) -> Option<String> {
159    let Some(kind) = kinds::kind(&body.kind) else {
160        return Some(format!("a kind this version does not know: {}", body.kind));
161    };
162    body.parts.keys().find(|p| !kind.parts.contains(&p.as_str())).map(|p| format!("a part the kind {} does not have: {p}", kind.name))
163}
164
165fn tags_of(row: &VaultRow) -> Vec<String> {
166    serde_json::from_str(&row.tags).unwrap_or_default()
167}
168
169fn tags_json(tags: &[String]) -> String {
170    serde_json::to_string(tags).unwrap_or_else(|_| "[]".to_string())
171}
172
173/// A version this machine keeps of what a take replaced.
174fn version(entry_id: &str, created_at: i64, sealed: Vec<u8>, state: String, machine: &str, now_ms: i64) -> VaultVersionRow {
175    VaultVersionRow { seq: 0, entry_id: entry_id.to_string(), entry_created_at: created_at, sealed, replaced_at: now_ms, replaced_by: machine.to_string(), how: "synced".to_string(), state }
176}
177
178impl Taker<'_> {
179    /// Hands `rec` to the layer, and takes its result into the store. An error from the layer (a record that is refused, out of
180    /// sequence or at another epoch) comes back as text and the log does not hold the record. An error from the store, or a
181    /// record the store cannot take yet ([`Effect::Deferred`]), comes back after the log holds the record, which the layer does
182    /// not hand over again: so it is noted, and [`Taker::retake`] takes it again from the log.
183    pub fn receive(&self, rec: &Record, pins: &Pins, clock: &mut Clock, now_ms: i64) -> Result<Taken, String> {
184        let h = &rec.header;
185        // Everything that reads the store comes before the log is locked: the log is the store's own connection.
186        let holder = match Kind::of(&h.record) {
187            Kind::Entry => match self.find(&self.ids_of(rec))? {
188                Found::One(id) => Some(id),
189                _ => None,
190            },
191            _ => None,
192        };
193        let rotating = match &holder {
194            Some(id) => self.rotation_waits(id)?,
195            None => false,
196        };
197        let (outcome, decision) = {
198            let conn = self.store.conn().lock().unwrap_or_else(|e| e.into_inner());
199            let adapter = Recording { inner: VaultAdapter { conn: &conn, rotations: &Rotating(rotating) }, last: RefCell::new(None) };
200            let outcome = log::apply_remote(&conn, rec, pins, clock, now_ms, &adapter).map_err(|e| format!("{e:?}"))?;
201            (outcome, adapter.last.into_inner())
202        };
203        let none = |outcome| Taken { outcome, effect: Effect::None, kept: None };
204        // The adapter is not asked about a record the layer already holds or voids.
205        let Some(decision) = decision else { return Ok(none(outcome)) };
206        // Why the other side of a conflict is kept, when this record won one: a retake keeps it the same way.
207        let lost = match &decision {
208            Decision::Conflict { current: Chose::Incoming, kept, .. } => Some(kept.label()),
209            _ => None,
210        };
211        let result = match decision {
212            Decision::KeptLocal => return Ok(none(outcome)),
213            Decision::Applied => self.current(rec, None, false, now_ms).map(|effect| Taken { outcome, effect, kept: None }),
214            Decision::Conflict { current: Chose::Incoming, kept, .. } => {
215                let label = kept.label();
216                self.current(rec, Some(&label), false, now_ms).map(|effect| Taken { outcome, effect, kept: Some(label) })
217            }
218            Decision::Conflict { current: Chose::Local, kept, .. } => {
219                let label = kept.label();
220                self.keep_incoming(rec, &label, now_ms).map(|effect| Taken { outcome, effect, kept: Some(label) })
221            }
222        };
223        // The log holds the record now. What the store could not take of it is noted, so a record that is never sent again is
224        // still taken; what it took, or is not going to, is not.
225        let (vault, record) = (&h.collection, &h.record);
226        match &result {
227            Err(_) | Ok(Taken { effect: Effect::Deferred(_), .. }) => {
228                sync_capture::retake_mark(self.store, vault, record, lost.as_deref()).map_err(|e| format!("the log holds the record, and it could not be noted for `retake`: {e}"))?;
229            }
230            // Clearing a mark that is not needed any more fails harmlessly: the record is taken again, and the take is the same.
231            Ok(_) => drop(sync_capture::retake_clear(self.store, vault, record)),
232        }
233        result.map_err(|e| format!("{e}: the log holds the record, and `retake` takes it again"))
234    }
235
236    /// Takes again the records of `vault` that the log holds and the store did not take (an error, a key not here yet, a kind
237    /// this version does not know), from the log's current state of each, as a plain change that follows on: the side of a
238    /// conflict that lost stays in the log. A record taken, or no longer in the log, is not noted any more; one that fails again
239    /// stays, with the conflict it won (so does one that finds the entry changed here since it was read, which is never written over). Run it after a
240    /// capture, at the start of a sync round, and after an upgrade: a change made here is in the log by then.
241    pub fn retake(&self, vault: &str, now_ms: i64) -> Result<Vec<(String, Result<Effect, String>)>, String> {
242        let mut out = Vec::new();
243        for (record, lost) in sync_capture::retake_pending(self.store, vault)? {
244            let current = log::current(&self.store.conn().lock().unwrap_or_else(|e| e.into_inner()), vault, &record).map_err(|e| e.to_string())?;
245            let Some(rec) = current else {
246                sync_capture::retake_clear(self.store, vault, &record)?;
247                continue;
248            };
249            let effect = self.current(&rec, lost.as_deref(), true, now_ms);
250            if !matches!(effect, Err(_) | Ok(Effect::Deferred(_))) {
251                sync_capture::retake_clear(self.store, vault, &record)?;
252            }
253            out.push((record, effect));
254        }
255        Ok(out)
256    }
257
258    /// The ids a record names its entry by: its own, then the ones its body says the entry has (a body that does not open, or
259    /// a tombstone, names only its own).
260    fn ids_of(&self, rec: &Record) -> Vec<String> {
261        let mut ids = vec![rec.header.record.clone()];
262        if !rec.header.tombstone {
263            if let Ok(body) = open_body::<EntryBody>(self.ring, rec) {
264                ids.extend(body.link_ids.iter().filter(|i| sync_links::is_link_id(i) && **i != rec.header.record).cloned());
265            }
266        }
267        ids
268    }
269
270    /// The entry here that has any of `ids`. Ids that belong to two entries here are not an entry: they are told apart, and
271    /// a record that names both is not taken (it would make one entry of two).
272    fn find(&self, ids: &[String]) -> Result<Found, String> {
273        let mut found: Vec<String> = Vec::new();
274        for id in ids {
275            if let Some(entry) = self.store.vault_entry_of_link(id).map_err(|e| e.to_string())? {
276                if !found.contains(&entry) {
277                    found.push(entry);
278                }
279            }
280        }
281        Ok(match found.len() {
282            0 => Found::None,
283            1 => Found::One(found.remove(0)),
284            _ => Found::Two,
285        })
286    }
287
288    /// Whether the entry has a rotation waiting to be confirmed (spec 6.3).
289    fn rotation_waits(&self, entry_id: &str) -> Result<bool, String> {
290        let Some(row) = self.store.vault_get(entry_id).map_err(|e| e.to_string())? else { return Ok(false) };
291        Ok(self.store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())?.iter().any(|v| v.state == versions::PENDING))
292    }
293
294    /// `rec` is now the record's current state: the entry takes its value, or is deleted. `lost` is the other side of a
295    /// conflict, which this machine held, and which is kept.
296    fn current(&self, rec: &Record, lost: Option<&str>, settled: bool, now_ms: i64) -> Result<Effect, String> {
297        match Kind::of(&rec.header.record) {
298            Kind::Activity => return self.line(rec),
299            Kind::Grant => return self.grant(rec),
300            Kind::Entry => {}
301        }
302        if !sync_links::is_link_id(&rec.header.record) {
303            return Ok(Effect::Skipped("a record whose id is not an entry's".to_string()));
304        }
305        if rec.header.tombstone {
306            return self.delete(rec, lost, settled, now_ms);
307        }
308        let body: EntryBody = open_body(self.ring, rec)?;
309        if let Some(why) = refused(&body) {
310            return Ok(Effect::Deferred(why));
311        }
312        // One try: what was decided was decided against the entry as it was read. An entry changed here since is not written
313        // over, and the decision is not run again against it: the change here is sent by the next capture, and `retake` takes
314        // the record's state then.
315        match self.write(rec, &body, lost, now_ms)? {
316            Some(effect) => {
317                // Grants that came before the entry did are made now.
318                if let Effect::Wrote { entry } = &effect {
319                    self.apply_waiting(entry, &rec.header.collection)?;
320                }
321                Ok(effect)
322            }
323            None => Err("the entry was changed here while its record was taken, so nothing was overwritten".to_string()),
324        }
325    }
326
327    /// One try at writing `body` as the entry's value. `None` if the entry changed here between the read and the write.
328    fn write(&self, rec: &Record, body: &EntryBody, lost: Option<&str>, now_ms: i64) -> Result<Option<Effect>, String> {
329        let h = &rec.header;
330        let store = self.store;
331        let mut ids = vec![h.record.clone()];
332        ids.extend(body.link_ids.iter().filter(|i| **i != h.record).cloned());
333        let existing = match self.find(&ids)? {
334            Found::None => None,
335            Found::One(id) => store.vault_get(&id).map_err(|e| e.to_string())?,
336            Found::Two => return Ok(Some(Effect::Deferred("its ids belong to two entries here".to_string()))),
337        };
338        // The entry is in another Vault here, and that Vault's record of it is live and later than this one: this record is the
339        // entry's past (the source Vault's, taken after the destination's), and does not move it back.
340        if let Some(old) = existing.as_ref().filter(|r| r.vault_id != h.collection) {
341            let there = log::current(&store.conn().lock().unwrap_or_else(|e| e.into_inner()), &old.vault_id, &h.record).map_err(|e| e.to_string())?;
342            if there.is_some_and(|t| !t.header.tombstone && t.header.version > h.version) {
343                return Ok(Some(Effect::None));
344            }
345        }
346        // One entry is one record. An entry that is written under another record than this one has two: the smaller id's is
347        // the one every machine follows, so the larger's is not taken (it names the entry's ids, so a link made from it
348        // opens it), and this machine's own larger one is left for the smaller (below).
349        let mut adopting: Option<(String, String)> = None;
350        if let Some(old) = &existing {
351            if let Some((vault, mine)) = sync_capture::identity_of(store, &old.id)? {
352                if mine != h.record {
353                    if h.record > mine {
354                        let local = links_of(store, &old.id)?;
355                        let settled = sync_links::settle(store, &old.id, &local, &ids);
356                        if settled != local {
357                            store.vault_links_set(&old.id, settled.primary.as_deref(), &settled.aliases).map_err(|e| e.to_string())?;
358                        }
359                        return Ok(Some(Effect::Skipped("another record of an entry here: the one with the smaller id is followed".to_string())));
360                    }
361                    adopting = Some((vault, mine));
362                }
363            }
364        }
365        let entry_id = existing.as_ref().map_or_else(|| uuid::Uuid::new_v4().to_string(), |r| r.id.clone());
366        // The ids: the record's own, then the ones the sender says the entry has. A new entry takes the record's as its own.
367        let local = if existing.is_some() { links_of(store, &entry_id)? } else { Links::default() };
368        let links = sync_links::settle(&Reviving { store, record: &h.record }, &entry_id, &local, &ids);
369        if existing.is_none() && links.primary.as_deref() != Some(h.record.as_str()) {
370            return Ok(Some(Effect::Deferred("its id is held by another entry here".to_string())));
371        }
372        let sealed = seal::seal(self.key, &entry_id, &Parts(body.parts.clone()))?;
373        let mut row = body.into_row(&entry_id, &h.collection, sealed, existing.as_ref(), self.profiles);
374        let machine = h.version.machine.as_str();
375        // This machine's own larger record is left for the smaller: if what the entry holds here is not what that record
376        // says, this machine's value is kept beside it as a version of its own, as for a change made at the same time.
377        let adopt_label = Kept::SameTime { machine: self.machine.to_string() }.label();
378        let lost = match (&adopting, &existing) {
379            (Some(_), Some(old)) if lost.is_none() && self.differs(old, &row, body) => Some(adopt_label.as_str()),
380            _ => lost,
381        };
382        let mut kept = Vec::new();
383        match (&existing, lost) {
384            // A conflict: the value this machine held is kept as it was, and the tags are the two sides' together.
385            (Some(old), Some(why)) => {
386                kept.push(version(&old.id, old.created_at, old.sealed.clone(), format!("{KEPT_PREFIX}{why}"), machine, now_ms));
387                row.tags = tags_json(&sync_merge::union_tags(&body.tags, &tags_of(old)));
388            }
389            // A change that follows on: the value it replaces is kept for 7 days, if it differs.
390            (Some(old), None) => {
391                let same = seal::open(self.key, &old.id, &old.sealed).is_ok_and(|p| p.0 == body.parts);
392                if !same {
393                    kept.push(version(&old.id, old.created_at, old.sealed.clone(), PREVIOUS.to_string(), machine, now_ms));
394                }
395            }
396            // The entry was deleted here, and this change is later than the delete: it comes back, and the delete is kept.
397            (None, Some(why)) => kept.push(version(&entry_id, row.created_at, Vec::new(), format!("{KEPT_PREFIX}{why}"), machine, now_ms)),
398            (None, None) => {}
399        }
400        let write = TakeWrite {
401            row: &row,
402            was: existing.as_ref(),
403            primary: links.primary.as_deref(),
404            aliases: &links.aliases,
405            revive: existing.is_none().then_some(h.record.as_str()),
406            kept: &kept,
407        };
408        if !store.vault_take_write(&write).map_err(|e| e.to_string())? {
409            return Ok(None);
410        }
411        // What was written is what is marked as seen, not what the store holds by now: a change made here after the write is
412        // not in the log, and the next capture has to send it.
413        sync_capture::mark_seen(store, &row, &h.record, self.key, self.profiles)?;
414        // The record this machine wrote it under is ended by its next capture, so a machine that has only that one (a
415        // new member) does not make a second entry of it.
416        if let Some((vault, mine)) = adopting.filter(|(vault, _)| !vault.is_empty()) {
417            sync_capture::end_record(store, &vault, &mine)?;
418        }
419        Ok(Some(Effect::Wrote { entry: entry_id }))
420    }
421
422    /// An activity line another machine made: added once, to the lines of other machines. A line names the machine that made
423    /// it, and only that machine may make it; a line never changes, so a delete of one is not taken.
424    fn line(&self, rec: &Record) -> Result<Effect, String> {
425        let h = &rec.header;
426        let Some((machine, seq)) = sync_activity::parse_record_id(&h.record) else { return Ok(Effect::Skipped("not an activity line".to_string())) };
427        if h.tombstone {
428            return Ok(Effect::Skipped("an activity line is never deleted".to_string()));
429        }
430        if machine != h.origin {
431            return Ok(Effect::Skipped("an activity line named for another machine".to_string()));
432        }
433        let mut body: ActivityBody = open_body(self.ring, rec)?;
434        // A line names its entry by its record; here the entry has an id of its own, if it is here.
435        if let Some(entry) = self.store.vault_entry_of_link(&body.entry_id).map_err(|e| e.to_string())? {
436            body.entry_id = entry;
437        }
438        Ok(match apply_activity(self.store, machine, seq, &body)? {
439            Decision::Applied => Effect::Line { machine: machine.to_string(), seq },
440            _ => Effect::None,
441        })
442    }
443
444    /// `rec`, a tombstone, is now the record's current state. A conflict's other side is the entry's last value, which the
445    /// delete takes with it: it stays in the log.
446    ///
447    /// A tombstone in a Vault is also what a move to another Vault leaves behind, and the two Vaults' records come separately,
448    /// in either order. An entry that moved is not deleted by its old Vault's tombstone: not when the new Vault's record is
449    /// already in the log, and not on first sight either, when it may still come in this round. The delete waits one round
450    /// (`settled` is false then, true when [`Taker::retake`] takes it again), and by then the new Vault's record has moved the
451    /// entry, which keeps its grants, versions and ids; if it has not, the entry is deleted.
452    fn delete(&self, rec: &Record, lost: Option<&str>, settled: bool, now_ms: i64) -> Result<Effect, String> {
453        let h = &rec.header;
454        let Some(id) = self.store.vault_entry_of_link(&h.record).map_err(|e| e.to_string())? else { return Ok(Effect::None) };
455        let Some(row) = self.store.vault_get(&id).map_err(|e| e.to_string())? else { return Ok(Effect::None) };
456        // An entry that moved to another Vault is not deleted by its old Vault's tombstone.
457        if row.vault_id != h.collection {
458            return Ok(Effect::None);
459        }
460        // Nor by the end of a record it is no longer written under (it follows another's, see `write`).
461        if sync_capture::identity_of(self.store, &id)?.is_some_and(|(_, mine)| mine != h.record) {
462            return Ok(Effect::None);
463        }
464        let moved = log::live_elsewhere(&self.store.conn().lock().unwrap_or_else(|e| e.into_inner()), &h.collection, &h.record).map_err(|e| e.to_string())?;
465        if moved {
466            return Ok(Effect::None);
467        }
468        // A rotation may have started since the tombstone came (a rotation holds a pending value beside the entry, and is not a
469        // change to it): the delete does not take the pending value with it, and is kept beside the entry, as a delete that
470        // came while the entry was being rotated is.
471        if self.rotation_waits(&id)? {
472            return self.keep_incoming(rec, &format!("deleted on {} while this was being rotated", h.version.machine), now_ms);
473        }
474        if !settled {
475            return Ok(Effect::Deferred("deleted in this Vault: it waits one round, in case the entry moved to another Vault whose record has not come yet".to_string()));
476        }
477        self.store.vault_delete(&id).map_err(|e| e.to_string())?;
478        sync_capture::forget(self.store, &id)?;
479        Ok(match lost {
480            Some(why) => Effect::KeptInLog(why.to_string()),
481            None => Effect::Deleted { entry: id },
482        })
483    }
484
485    /// Whether `old`, the entry as it is stored, differs from `new`, the row `body` makes of it.
486    fn differs(&self, old: &VaultRow, new: &VaultRow, body: &EntryBody) -> bool {
487        let same_parts = seal::open(self.key, &old.id, &old.sealed).is_ok_and(|p| p.0 == body.parts);
488        old.kind != new.kind || old.label != new.label || old.fields != new.fields || old.tags != new.tags || !same_parts
489    }
490
491    /// `rec` lost a conflict: this machine's value stays, and `rec` is kept beside it as a version, with its tags.
492    fn keep_incoming(&self, rec: &Record, label: &str, now_ms: i64) -> Result<Effect, String> {
493        let h = &rec.header;
494        let label = label.to_string();
495        let Some(id) = self.store.vault_entry_of_link(&h.record).map_err(|e| e.to_string())? else { return Ok(Effect::KeptInLog(label)) };
496        let machine = h.version.machine.as_str();
497        let state = format!("{KEPT_PREFIX}{label}");
498        // A delete that lost holds no value; a value that lost is sealed under this machine's key, like the entry's own.
499        let (sealed, theirs) = if h.tombstone {
500            (Vec::new(), None)
501        } else {
502            let body: EntryBody = open_body(self.ring, rec)?;
503            if let Some(why) = refused(&body) {
504                return Ok(Effect::Skipped(why));
505            }
506            (seal::seal(self.key, &id, &Parts(body.parts.clone()))?, Some(body.tags.clone()))
507        };
508        // One try, as in `current`: an entry changed here since it was read is not written over.
509        let Some(row) = self.store.vault_get(&id).map_err(|e| e.to_string())? else { return Ok(Effect::KeptInLog(label)) };
510        let mut next = row.clone();
511        if let Some(theirs) = &theirs {
512            next.tags = tags_json(&sync_merge::union_tags(&tags_of(&row), theirs));
513        }
514        let links = links_of(self.store, &id)?;
515        let kept = [version(&id, row.created_at, sealed, state, machine, now_ms)];
516        let write = TakeWrite { row: &next, was: Some(&row), primary: links.primary.as_deref(), aliases: &links.aliases, revive: None, kept: &kept };
517        if !self.store.vault_take_write(&write).map_err(|e| e.to_string())? {
518            return Err("the entry was changed here while its record was taken, so nothing was overwritten".to_string());
519        }
520        sync_capture::mark_seen(self.store, &next, &h.record, self.key, self.profiles)?;
521        Ok(Effect::Wrote { entry: id })
522    }
523}
524
525#[cfg(test)]
526#[path = "sync_take_tests.rs"]
527mod tests;