Skip to main content

agentmux_srv_core/backend/vault/
sync_capture.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault's entries as records in the sync layer's log (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md
5//! section 6): what a machine writes into a Vault's collection when its entries change.
6//!
7//! [`capture`] reads one Vault's entries from the store and writes whatever changed since the last capture into the
8//! Vault's collection, one record per entry, named by the entry's link id (the id that is the same on every machine). A
9//! record's body is the entry's [`EntryBody`](super::sync_record::EntryBody) sealed with the Vault's key at the epoch the
10//! record carries, so the log, a LAN peer, the relay and the cloud see only the clear header. An entry that is gone, or
11//! moved to another Vault, ends its record with a tombstone. It sends nothing and changes no entry: taking a record from
12//! another machine into the store is the next step.
13//!
14//! What this machine keeps to itself does not go: a sign-in that [`stays_here`], the agents an entry is shared with, and
15//! when it was last used (`EntryBody` leaves those out).
16
17use ring::hmac;
18use rusqlite::{params, Connection, OptionalExtension};
19use zeroize::Zeroizing;
20
21use super::seal::{self, Key};
22use super::sync_capture_kinds as kinds;
23use super::sync_links;
24use super::sync_record::{stays_here, EntryBody, Profiles};
25use super::sync_store::links_of;
26use crate::backend::storage::store::Store;
27use crate::backend::storage::vault::VaultRow;
28use crate::backend::user_sync::log::{self, Signer};
29use crate::backend::user_sync::seal::KeyRing;
30
31/// The kind of a Vault's collection.
32pub const KIND: &str = "vault";
33
34/// What a capture remembers: per entry its Vault, the record it was written as and a digest of what was written, so an
35/// unchanged entry costs one lookup and no new version (a sealed body is different every time, so the log cannot say).
36const SCHEMA: &str = "
37    CREATE TABLE IF NOT EXISTS db_sync_vault_seen (
38        entry_id TEXT PRIMARY KEY,
39        vault    TEXT NOT NULL,
40        record   TEXT NOT NULL,
41        hash     TEXT NOT NULL
42    );
43    -- Records the log holds that the store could not take (an error, or a kind this version does not know yet): taken again
44    -- from the log by `Taker::retake`, because a record the log holds is never sent again.
45    CREATE TABLE IF NOT EXISTS db_sync_vault_retake (
46        vault  TEXT NOT NULL,
47        record TEXT NOT NULL,
48        -- Why the other side of a conflict was kept, when the record won one: the retake keeps it the same way.
49        kept   TEXT,
50        PRIMARY KEY (vault, record)
51    );
52    -- Records this machine no longer writes an entry under (it follows another machine's, see `sync_take`): ended with a
53    -- tombstone by the next capture.
54    CREATE TABLE IF NOT EXISTS db_sync_vault_ended (
55        vault  TEXT NOT NULL,
56        record TEXT NOT NULL,
57        PRIMARY KEY (vault, record)
58    );";
59
60/// Creates the log's tables and this module's.
61pub fn init(conn: &Connection) -> rusqlite::Result<()> {
62    log::init(conn)?;
63    conn.execute_batch(SCHEMA)?;
64    conn.execute_batch(kinds::SCHEMA)
65}
66
67/// What a capture did.
68#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
69pub struct Captured {
70    /// Records written: an entry's first version, or a changed one.
71    pub written: usize,
72    /// Records ended with a tombstone: an entry deleted, or moved to another Vault, or a grant revoked.
73    pub tombstoned: usize,
74    /// Activity lines written.
75    pub lines: usize,
76    /// Site grants written.
77    pub grants: usize,
78}
79
80/// For `log::append_local_with`: seals `body` for the place the record will have, under the Vault's key at the epoch the
81/// record carries. It is the layer's own seal, so the layer can open what a Vault wrote when it writes the record again at a
82/// new epoch (`ops::reissue`) without knowing anything of the Vault.
83pub use crate::backend::user_sync::seal::sealer;
84
85/// What is kept of a body to tell later whether it changed: an HMAC under this machine's own key, never a bare hash. A
86/// hash of the body would let anyone holding the database test guesses at a low-entropy secret (everything else in the body
87/// is in the tables beside it) without either key.
88fn digest(key: &Key, body: &[u8]) -> String {
89    let mut ctx = hmac::Context::with_key(&hmac::Key::new(hmac::HMAC_SHA256, &key[..]));
90    ctx.update(b"agentmux-vault-sync-seen-v1\0");
91    ctx.update(body);
92    ctx.sign().as_ref().iter().map(|b| format!("{b:02x}")).collect()
93}
94
95/// The body a record carries for `row`: the entry as [`EntryBody`] writes it, with its link ids, as the bytes that are
96/// sealed and compared. Wiped when dropped.
97pub(super) fn body_of(store: &Store, row: &VaultRow, key: &Key, profiles: &dyn Profiles) -> Result<Zeroizing<Vec<u8>>, String> {
98    let parts = seal::open(key, &row.id, &row.sealed)?;
99    let body = EntryBody::of_row(row, &parts, profiles).with_link_ids(links_of(store, &row.id)?.ids());
100    Ok(Zeroizing::new(serde_json::to_vec(&body).map_err(|e| e.to_string())?))
101}
102
103/// Notes that `row`, as it is stored now, is what the log holds for `record` in `vault_id`: a capture then finds nothing
104/// changed. Taking a record into the store ends with this, or the next capture would write the taken entry back as a new
105/// version made here.
106pub(super) fn mark_seen(store: &Store, row: &VaultRow, record: &str, key: &Key, profiles: &dyn Profiles) -> Result<(), String> {
107    let hash = digest(key, &body_of(store, row, key, profiles)?);
108    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
109    conn.execute("INSERT OR REPLACE INTO db_sync_vault_seen (entry_id, vault, record, hash) VALUES (?1, ?2, ?3, ?4)", params![row.id, row.vault_id, record, hash]).map_err(|e| e.to_string())?;
110    Ok(())
111}
112
113/// Notes that the store did not take `record` of `vault`, which the log holds: `Taker::retake` takes it again.
114/// `kept` is why the side of a conflict this machine held is kept, if the record won one.
115pub(super) fn retake_mark(store: &Store, vault: &str, record: &str, kept: Option<&str>) -> Result<(), String> {
116    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
117    conn.execute("INSERT OR IGNORE INTO db_sync_vault_retake (vault, record, kept) VALUES (?1, ?2, ?3)", params![vault, record, kept]).map_err(|e| e.to_string())?;
118    Ok(())
119}
120
121/// `record` of `vault` is in the store, or is no longer to be taken.
122pub(super) fn retake_clear(store: &Store, vault: &str, record: &str) -> Result<(), String> {
123    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
124    conn.execute("DELETE FROM db_sync_vault_retake WHERE vault = ?1 AND record = ?2", params![vault, record]).map_err(|e| e.to_string())?;
125    Ok(())
126}
127
128/// The records of `vault` to take again, in the order they were noted.
129pub(super) fn retake_pending(store: &Store, vault: &str) -> Result<Vec<(String, Option<String>)>, String> {
130    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
131    let mut stmt = conn.prepare("SELECT record, kept FROM db_sync_vault_retake WHERE vault = ?1 ORDER BY rowid").map_err(|e| e.to_string())?;
132    let rows = stmt.query_map(params![vault], |r| Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?))).map_err(|e| e.to_string())?;
133    rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
134}
135
136/// Every entry that has been written: the record it is written under.
137fn records_written(store: &Store) -> Result<std::collections::HashMap<String, String>, String> {
138    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
139    let mut stmt = conn.prepare("SELECT entry_id, record FROM db_sync_vault_seen").map_err(|e| e.to_string())?;
140    let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| e.to_string())?;
141    rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
142}
143
144/// The Vault and record `entry_id` is written under, if it has been written; otherwise the record it will be written
145/// under, which is its own link id, with no Vault (nothing of it is in any log).
146pub(super) fn identity_of(store: &Store, entry_id: &str) -> Result<Option<(String, String)>, String> {
147    {
148        let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
149        if let Some(s) = seen_of(&conn, entry_id).map_err(|e| e.to_string())? {
150            return Ok(Some((s.vault, s.record)));
151        }
152    }
153    Ok(store.vault_link_primary(entry_id).map_err(|e| e.to_string())?.map(|p| (String::new(), p)))
154}
155
156/// Notes that `record` in `vault` is no longer written: the next capture of that Vault ends it with a tombstone.
157pub(super) fn end_record(store: &Store, vault: &str, record: &str) -> Result<(), String> {
158    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
159    conn.execute("INSERT OR IGNORE INTO db_sync_vault_ended (vault, record) VALUES (?1, ?2)", params![vault, record]).map_err(|e| e.to_string())?;
160    Ok(())
161}
162
163/// Forgets an entry that was deleted here because a record said so: its tombstone is already in the log.
164pub(super) fn forget(store: &Store, entry_id: &str) -> Result<(), String> {
165    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
166    conn.execute("DELETE FROM db_sync_vault_seen WHERE entry_id = ?1", params![entry_id]).map_err(|e| e.to_string())?;
167    Ok(())
168}
169
170struct Seen {
171    vault: String,
172    record: String,
173    hash: String,
174}
175
176fn seen_of(conn: &Connection, entry_id: &str) -> rusqlite::Result<Option<Seen>> {
177    conn.query_row("SELECT vault, record, hash FROM db_sync_vault_seen WHERE entry_id = ?1", params![entry_id], |r| {
178        Ok(Seen { vault: r.get(0)?, record: r.get(1)?, hash: r.get(2)? })
179    })
180    .optional()
181}
182
183/// Ends a record, if it is live.
184pub(super) fn tombstone(conn: &Connection, signer: &mut Signer, collection: &str, record: &str, now_ms: i64) -> Result<bool, String> {
185    match log::current(conn, collection, record).map_err(|e| e.to_string())? {
186        Some(cur) if !cur.header.tombstone => {
187            log::append_local(conn, signer, collection, record, Vec::new(), true, now_ms).map_err(|e| format!("{e:?}"))?;
188            Ok(true)
189        }
190        _ => Ok(false),
191    }
192}
193
194/// An entry that is to be recorded: the entry, the record it goes as, and the body.
195struct Pending {
196    entry_id: String,
197    record: String,
198    /// The body in the clear, wiped when dropped, on an error return too.
199    body: Zeroizing<Vec<u8>>,
200    hash: String,
201}
202
203/// Writes what changed in `vault_id`'s entries into its collection. `key` is this machine's own key, which opens the
204/// entries' values; `ring` holds the Vault's keys; `profiles` names the person's browser profiles here.
205pub fn capture(store: &Store, signer: &mut Signer, vault_id: &str, ring: &KeyRing, key: &Key, profiles: &dyn Profiles, now_ms: i64) -> Result<Captured, String> {
206    // Everything that reads the store comes first: the connection is the store's own, and is taken only after. The lines and
207    // grants are read before the entries, so a line is never read for an entry that was made after the entries were.
208    let more = kinds::read(store, vault_id)?;
209    let all: Vec<_> = store.vault_list().map_err(|e| e.to_string())?.into_iter().filter(|r| r.vault_id == vault_id).collect();
210    let here: std::collections::HashSet<&str> = all.iter().map(|r| r.id.as_str()).collect();
211    let rows: Vec<_> = all.iter().filter(|r| !stays_here(r, profiles)).cloned().collect();
212    let ids: Vec<&str> = rows.iter().map(|r| r.id.as_str()).collect();
213    let link_of = super::link_ids(store, &ids)?;
214    let written_as = records_written(store)?;
215    let mut pending = Vec::new();
216    for row in &rows {
217        // The record an entry is written under is the one it was first written (or taken) as, whatever link ids it has
218        // learned since: one entry is one record (`identity_of`). Until then, its own link id.
219        let Some(record) = written_as.get(&row.id).or_else(|| link_of.get(&row.id)) else { continue };
220        if !sync_links::is_link_id(record) {
221            continue;
222        }
223        let body = body_of(store, row, key, profiles)?;
224        let hash = digest(key, &body);
225        pending.push(Pending { entry_id: row.id.clone(), record: record.clone(), body, hash });
226    }
227    let now_here: std::collections::HashSet<&str> = rows.iter().map(|r| r.id.as_str()).collect();
228
229    let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
230    let mut out = Captured::default();
231    log::ensure_collection(&conn, vault_id, KIND, now_ms).map_err(|e| e.to_string())?;
232    // Records that an entry has left for another machine's: ended once.
233    let mut ended = conn.prepare("SELECT record FROM db_sync_vault_ended WHERE vault = ?1").map_err(|e| e.to_string())?;
234    let ended: Vec<String> = ended.query_map(params![vault_id], |r| r.get(0)).map_err(|e| e.to_string())?.collect::<Result<_, _>>().map_err(|e| e.to_string())?;
235    for record in ended {
236        if tombstone(&conn, signer, vault_id, &record, now_ms)? {
237            out.tombstoned += 1;
238        }
239        conn.execute("DELETE FROM db_sync_vault_ended WHERE vault = ?1 AND record = ?2", params![vault_id, record]).map_err(|e| e.to_string())?;
240    }
241    for p in &pending {
242        let seen = seen_of(&conn, &p.entry_id).map_err(|e| e.to_string())?;
243        if seen.as_ref().is_some_and(|s| s.vault == vault_id && s.record == p.record && s.hash == p.hash) {
244            continue;
245        }
246        log::append_local_with(&conn, signer, vault_id, &p.record, false, now_ms, sealer(ring, &p.body)).map_err(|e| format!("{e:?}"))?;
247        out.written += 1;
248        // An entry that came from another Vault ends its record there.
249        if let Some(old) = seen.filter(|s| s.vault != vault_id) {
250            if tombstone(&conn, signer, &old.vault, &old.record, now_ms)? {
251                out.tombstoned += 1;
252            }
253        }
254        conn.execute(
255            "INSERT OR REPLACE INTO db_sync_vault_seen (entry_id, vault, record, hash) VALUES (?1, ?2, ?3, ?4)",
256            params![p.entry_id, vault_id, p.record, p.hash],
257        )
258        .map_err(|e| e.to_string())?;
259    }
260    let records: std::collections::HashMap<String, String> = pending.iter().map(|p| (p.entry_id.clone(), p.record.clone())).collect();
261    let wrote = kinds::write(&conn, signer, vault_id, ring, &more, &rows, &records, &here, now_ms)?;
262    out.lines = wrote.lines;
263    out.grants = wrote.grants;
264    out.tombstoned += wrote.tombstoned;
265    // Entries this Vault had recorded that no longer exist: deleted. One moved to another Vault is left to that Vault's
266    // capture, which ends this record when it writes the entry; one that is only no longer kept here (its profile is
267    // gone) is not deleted for the other machines.
268    let mut stmt = conn.prepare("SELECT entry_id, record FROM db_sync_vault_seen WHERE vault = ?1").map_err(|e| e.to_string())?;
269    let was: Vec<(String, String)> = stmt.query_map(params![vault_id], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| e.to_string())?.collect::<Result<_, _>>().map_err(|e| e.to_string())?;
270    drop(stmt);
271    for (entry_id, record) in was.into_iter().filter(|(e, _)| !now_here.contains(e.as_str())) {
272        let exists = conn.query_row("SELECT 1 FROM db_vault_entries WHERE id = ?1", params![entry_id], |_| Ok(())).optional().map_err(|e| e.to_string())?.is_some();
273        if exists {
274            continue;
275        }
276        if tombstone(&conn, signer, vault_id, &record, now_ms)? {
277            out.tombstoned += 1;
278        }
279        conn.execute("DELETE FROM db_sync_vault_seen WHERE entry_id = ?1", params![entry_id]).map_err(|e| e.to_string())?;
280    }
281    Ok(out)
282}
283
284#[cfg(test)]
285#[path = "sync_capture_tests.rs"]
286mod tests;