Skip to main content

agentmux_srv_core/backend/storage/
vault_sync.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the Vault keeps for a Vault shared across machines, beside its own tables (`vault.rs`): an entry's link-id
5//! aliases and the ids of removed entries, and the activity lines other machines made. The rules that use them are in
6//! `backend::vault::sync_links` and `sync_activity`; nothing here holds a value.
7
8use rusqlite::{params, OptionalExtension};
9
10use super::error::StoreError;
11use super::store::Store;
12use super::vault::{VaultActivityRow, VaultRow};
13use super::vault_versions::VaultVersionRow;
14
15pub(super) const SCHEMA: &str = "
16    -- The other link ids of an entry (`db_vault_link_ids` holds the one this machine gave it): a link made on another
17    -- machine of a shared Vault opens the entry here too. An id names one entry.
18    CREATE TABLE IF NOT EXISTS db_vault_link_aliases (
19        link_id  TEXT PRIMARY KEY,
20        entry_id TEXT NOT NULL
21    );
22    CREATE INDEX IF NOT EXISTS idx_vault_link_aliases_entry ON db_vault_link_aliases (entry_id);
23    -- Ids that named an entry that was removed: never given to another.
24    CREATE TABLE IF NOT EXISTS db_vault_link_retired (
25        link_id TEXT PRIMARY KEY
26    );
27    -- Activity lines that other machines made, named by machine and the sequence number there. They hold no value, and
28    -- they have no place in this machine's own hash chain.
29    CREATE TABLE IF NOT EXISTS db_vault_activity_remote (
30        machine     TEXT NOT NULL,
31        seq         INTEGER NOT NULL,
32        at          INTEGER NOT NULL,
33        entry_id    TEXT NOT NULL,
34        entry_label TEXT NOT NULL,
35        actor       TEXT NOT NULL,
36        action      TEXT NOT NULL,
37        target      TEXT NOT NULL,
38        outcome     TEXT NOT NULL,
39        version     INTEGER NOT NULL,
40        actor_kind  TEXT NOT NULL,
41        host        TEXT NOT NULL,
42        reason      TEXT NOT NULL,
43        refs        TEXT NOT NULL,
44        PRIMARY KEY (machine, seq)
45    );
46    CREATE INDEX IF NOT EXISTS idx_vault_activity_remote_at ON db_vault_activity_remote (at);
47";
48
49const REMOTE_COLUMNS: &str = "seq, at, entry_id, entry_label, actor, action, target, outcome, version, actor_kind, host, reason, refs";
50
51/// What [`Store::vault_take_write`] writes.
52pub struct TakeWrite<'a> {
53    /// The entry's whole row, its sealed parts under this machine's own key. A new entry's `created_at` is the record's;
54    /// an existing entry keeps its own.
55    pub row: &'a VaultRow,
56    /// The entry as it was read, if it exists: it is written only if it still is exactly that (its value, kind, label, fields,
57    /// tags, Vault and time of change), so a change made here since it was read is never overwritten, whichever part it changed.
58    pub was: Option<&'a VaultRow>,
59    pub primary: Option<&'a str>,
60    pub aliases: &'a [String],
61    pub revive: Option<&'a str>,
62    /// Versions the record's conflict keeps (`entry_created_at` is the entry's incarnation).
63    pub kept: &'a [VaultVersionRow],
64}
65
66/// Sets the ids of `entry_id` inside a transaction: see [`Store::vault_links_set`].
67fn links_set_in(tx: &rusqlite::Connection, entry_id: &str, primary: Option<&str>, aliases: &[String]) -> rusqlite::Result<()> {
68    let free = "NOT EXISTS (SELECT 1 FROM db_vault_link_retired WHERE link_id = ?2) AND NOT EXISTS (SELECT 1 FROM db_vault_link_ids WHERE link_id = ?2 AND entry_id != ?1) AND NOT EXISTS (SELECT 1 FROM db_vault_link_aliases WHERE link_id = ?2 AND entry_id != ?1)";
69    if let Some(p) = primary {
70        tx.execute(&format!("INSERT OR IGNORE INTO db_vault_link_ids (entry_id, link_id) SELECT ?1, ?2 WHERE {free}"), params![entry_id, p])?;
71    }
72    tx.execute("DELETE FROM db_vault_link_aliases WHERE entry_id = ?1", params![entry_id])?;
73    for a in aliases {
74        tx.execute(&format!("INSERT OR IGNORE INTO db_vault_link_aliases (link_id, entry_id) SELECT ?2, ?1 WHERE {free}"), params![entry_id, a])?;
75    }
76    Ok(())
77}
78
79impl Store {
80    /// The link id this machine gave `entry_id` as its own, if it has one.
81    pub fn vault_link_primary(&self, entry_id: &str) -> Result<Option<String>, StoreError> {
82        let conn = self.conn.lock().unwrap();
83        Ok(conn.query_row("SELECT link_id FROM db_vault_link_ids WHERE entry_id = ?1", params![entry_id], |r| r.get(0)).optional()?)
84    }
85
86    /// The other ids that open `entry_id`, in order.
87    pub fn vault_link_aliases(&self, entry_id: &str) -> Result<Vec<String>, StoreError> {
88        let conn = self.conn.lock().unwrap();
89        let mut stmt = conn.prepare("SELECT link_id FROM db_vault_link_aliases WHERE entry_id = ?1 ORDER BY link_id")?;
90        let rows = stmt.query_map(params![entry_id], |r| r.get::<_, String>(0))?;
91        Ok(rows.collect::<Result<Vec<_>, _>>()?)
92    }
93
94    /// The entry that holds `link_id` now, as its own id or as an alias, whether or not the entry still exists.
95    pub fn vault_link_holder(&self, link_id: &str) -> Result<Option<String>, StoreError> {
96        let conn = self.conn.lock().unwrap();
97        Ok(conn
98            .query_row(
99                "SELECT entry_id FROM db_vault_link_ids WHERE link_id = ?1 UNION ALL SELECT entry_id FROM db_vault_link_aliases WHERE link_id = ?1",
100                params![link_id],
101                |r| r.get(0),
102            )
103            .optional()?)
104    }
105
106    /// Whether `link_id` named an entry that was removed.
107    pub fn vault_link_retired(&self, link_id: &str) -> Result<bool, StoreError> {
108        let conn = self.conn.lock().unwrap();
109        let n: i64 = conn.query_row("SELECT COUNT(*) FROM db_vault_link_retired WHERE link_id = ?1", params![link_id], |r| r.get(0))?;
110        Ok(n > 0)
111    }
112
113    /// Sets the ids of `entry_id`: `primary` is kept only if the entry has none yet, and its aliases are replaced by
114    /// `aliases`. An id another entry holds, or a retired one, is not taken: the table holds each id once.
115    pub fn vault_links_set(&self, entry_id: &str, primary: Option<&str>, aliases: &[String]) -> Result<(), StoreError> {
116        let conn = self.conn.lock().unwrap();
117        let tx = conn.unchecked_transaction()?;
118        links_set_in(&tx, entry_id, primary, aliases)?;
119        tx.commit()?;
120        Ok(())
121    }
122
123    /// What taking a record from another machine writes, in one transaction (`backend::vault::sync_take`): the entry's row
124    /// (made if there is none, else its label, kind, fields, tags, value, Vault and update time replaced), its link ids, and
125    /// the versions of it that the record's conflict keeps. If `was` is `Some`, the entry must still hold that sealed value:
126    /// a change made here since it was read is never overwritten, and `false` is returned with nothing written. `revive` is
127    /// an id the record itself names: if an entry that had it was deleted here, the record is a later change to that entry
128    /// and takes the id back (every other retired id stays retired).
129    pub fn vault_take_write(&self, w: &TakeWrite<'_>) -> Result<bool, StoreError> {
130        let conn = self.conn.lock().unwrap();
131        let tx = conn.unchecked_transaction()?;
132        let row = w.row;
133        match w.was {
134            Some(was) => {
135                // The incarnation (`created_at`) stays: the entry's earlier values are filed under it.
136                let n = tx.execute(
137                    "UPDATE db_vault_entries SET kind = ?2, label = ?3, fields = ?4, tags = ?5, sealed = ?6, updated_at = ?7, vault_id = ?8 \
138                     WHERE id = ?1 AND sealed = ?9 AND kind = ?10 AND label = ?11 AND fields = ?12 AND tags = ?13 AND updated_at = ?14 AND vault_id = ?15",
139                    params![row.id, row.kind, row.label, row.fields, row.tags, row.sealed, row.updated_at, row.vault_id, was.sealed, was.kind, was.label, was.fields, was.tags, was.updated_at, was.vault_id],
140                )?;
141                if n == 0 {
142                    return Ok(false);
143                }
144            }
145            None => {
146                if let Some(id) = w.revive {
147                    tx.execute("DELETE FROM db_vault_link_retired WHERE link_id = ?1", params![id])?;
148                }
149                tx.execute(
150                    "INSERT INTO db_vault_entries (id, kind, label, fields, tags, sealed, created_at, updated_at, last_used_at, vault_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
151                    params![row.id, row.kind, row.label, row.fields, row.tags, row.sealed, row.created_at, row.updated_at, row.last_used_at, row.vault_id],
152                )?;
153            }
154        }
155        links_set_in(&tx, &row.id, w.primary, w.aliases)?;
156        for v in w.kept {
157            tx.execute(
158                "INSERT INTO db_vault_versions (entry_id, entry_created_at, sealed, replaced_at, replaced_by, how, state) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
159                params![v.entry_id, v.entry_created_at, v.sealed, v.replaced_at, v.replaced_by, v.how, v.state],
160            )?;
161        }
162        tx.commit()?;
163        Ok(true)
164    }
165
166    /// Adds an activity line that machine `machine` made as its number `seq`. `false` if this machine already has it.
167    pub fn vault_activity_remote_add(&self, machine: &str, seq: i64, r: &VaultActivityRow) -> Result<bool, StoreError> {
168        let conn = self.conn.lock().unwrap();
169        let n = conn.execute(
170            "INSERT OR IGNORE INTO db_vault_activity_remote (machine, seq, at, entry_id, entry_label, actor, action, target, outcome, version, actor_kind, host, reason, refs) \
171             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
172            params![machine, seq, r.at, r.entry_id, r.entry_label, r.actor, r.action, r.target, r.outcome, r.version, r.actor_kind, r.host, r.reason, r.refs],
173        )?;
174        Ok(n > 0)
175    }
176
177    pub fn vault_activity_remote_has(&self, machine: &str, seq: i64) -> Result<bool, StoreError> {
178        let conn = self.conn.lock().unwrap();
179        let n: i64 = conn.query_row("SELECT COUNT(*) FROM db_vault_activity_remote WHERE machine = ?1 AND seq = ?2", params![machine, seq], |r| r.get(0))?;
180        Ok(n > 0)
181    }
182
183    /// The latest `limit` lines other machines made, newest first, each with the machine that made it.
184    pub fn vault_activity_remote_list(&self, limit: i64) -> Result<Vec<(String, VaultActivityRow)>, StoreError> {
185        let conn = self.conn.lock().unwrap();
186        let mut stmt = conn.prepare(&format!("SELECT machine, {REMOTE_COLUMNS} FROM db_vault_activity_remote ORDER BY at DESC, machine, seq DESC LIMIT ?1"))?;
187        let rows = stmt.query_map(params![limit], |r| {
188            Ok((
189                r.get::<_, String>(0)?,
190                VaultActivityRow {
191                    seq: r.get(1)?,
192                    at: r.get(2)?,
193                    entry_id: r.get(3)?,
194                    entry_label: r.get(4)?,
195                    actor: r.get(5)?,
196                    action: r.get(6)?,
197                    target: r.get(7)?,
198                    outcome: r.get(8)?,
199                    version: r.get(9)?,
200                    actor_kind: r.get(10)?,
201                    host: r.get(11)?,
202                    reason: r.get(12)?,
203                    refs: r.get(13)?,
204                    prev_hash: String::new(),
205                    hash: String::new(),
206                },
207            ))
208        })?;
209        Ok(rows.collect::<Result<Vec<_>, _>>()?)
210    }
211}