Skip to main content

agentmux_srv_core/backend/storage/
vault_versions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Vault entry's earlier values: `db_vault_versions` (schema in `vault.rs`).
5//! Each row is a sealed blob as the entry held it, never a value.
6
7use rusqlite::{params, OptionalExtension};
8
9use super::error::StoreError;
10use super::store::Store;
11
12#[derive(Debug, Clone, PartialEq)]
13pub struct VaultVersionRow {
14    pub seq: i64,
15    pub entry_id: String,
16    pub entry_created_at: i64,
17    pub sealed: Vec<u8>,
18    pub replaced_at: i64,
19    /// Who put in the value that replaced it: "you" or an agent.
20    pub replaced_by: String,
21    /// How it was replaced: "replaced", "captured", "restored", …
22    pub how: String,
23    pub state: String,
24}
25
26const COLUMNS: &str = "seq, entry_id, entry_created_at, sealed, replaced_at, replaced_by, how, state";
27
28/// One write of a command's capture (`backend::vault::capture`), committed with
29/// the others it made or not at all.
30pub enum CaptureWrite {
31    /// A new entry.
32    Insert(super::vault::VaultRow),
33    /// A new sealed value for an entry, only if it is still the incarnation
34    /// (`row.created_at`), value (`was`) and plain fields (`was_fields`, which hold who a
35    /// login is shared with) that were read; `kept` is the value it replaces, kept as a version.
36    Replace { row: super::vault::VaultRow, was: Vec<u8>, was_fields: String, kept: Option<VaultVersionRow> },
37}
38
39fn row_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<VaultVersionRow> {
40    Ok(VaultVersionRow {
41        seq: r.get(0)?,
42        entry_id: r.get(1)?,
43        entry_created_at: r.get(2)?,
44        sealed: r.get(3)?,
45        replaced_at: r.get(4)?,
46        replaced_by: r.get(5)?,
47        how: r.get(6)?,
48        state: r.get(7)?,
49    })
50}
51
52impl Store {
53    /// Keeps an earlier value; returns its number. Tests only: versions are kept
54    /// in the transaction that replaces the value.
55    #[cfg(test)]
56    pub fn vault_version_add(&self, v: &VaultVersionRow) -> Result<i64, StoreError> {
57        let conn = self.conn.lock().unwrap();
58        conn.execute(
59            "INSERT INTO db_vault_versions (entry_id, entry_created_at, sealed, replaced_at, replaced_by, how, state) \
60             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
61            params![v.entry_id, v.entry_created_at, v.sealed, v.replaced_at, v.replaced_by, v.how, v.state],
62        )?;
63        Ok(conn.last_insert_rowid())
64    }
65
66    /// One incarnation's earlier values, newest first.
67    pub fn vault_versions(&self, entry_id: &str, entry_created_at: i64) -> Result<Vec<VaultVersionRow>, StoreError> {
68        let conn = self.conn.lock().unwrap();
69        let mut stmt = conn.prepare(&format!(
70            "SELECT {COLUMNS} FROM db_vault_versions WHERE entry_id = ?1 AND entry_created_at = ?2 ORDER BY seq DESC"
71        ))?;
72        let rows = stmt.query_map(params![entry_id, entry_created_at], row_of)?;
73        Ok(rows.collect::<Result<_, _>>()?)
74    }
75
76    pub fn vault_version_get(&self, seq: i64) -> Result<Option<VaultVersionRow>, StoreError> {
77        let conn = self.conn.lock().unwrap();
78        Ok(conn.query_row(&format!("SELECT {COLUMNS} FROM db_vault_versions WHERE seq = ?1"), params![seq], row_of).optional()?)
79    }
80
81    /// Makes version `seq` the entry's value, and keeps the value it replaces as
82    /// `previous`, in one transaction. Only if the entry still holds `previous`'s
83    /// value (same incarnation, same sealed blob): a value written since is never
84    /// overwritten unkept. False if anything changed, or `seq` isn't the entry's.
85    /// `kept_since` is the retention cutoff: a version replaced before it is past
86    /// its time and is never put back, whether or not it has been pruned yet.
87    pub fn vault_version_swap(&self, entry_id: &str, seq: i64, previous: &VaultVersionRow, now_ms: i64, kept_since: i64) -> Result<bool, StoreError> {
88        let conn = self.conn.lock().unwrap();
89        let tx = conn.unchecked_transaction()?;
90        let chosen: Option<Vec<u8>> = tx
91            .query_row(
92                "SELECT sealed FROM db_vault_versions WHERE seq = ?1 AND entry_id = ?2 AND replaced_at >= ?3",
93                params![seq, entry_id, kept_since],
94                |r| r.get(0),
95            )
96            .optional()?;
97        let Some(sealed) = chosen else { return Ok(false) };
98        if tx.execute(
99            "UPDATE db_vault_entries SET sealed = ?2, updated_at = ?3 WHERE id = ?1 AND created_at = ?4 AND sealed = ?5",
100            params![entry_id, sealed, now_ms, previous.entry_created_at, previous.sealed],
101        )? == 0
102        {
103            return Ok(false);
104        }
105        tx.execute("DELETE FROM db_vault_versions WHERE seq = ?1", params![seq])?;
106        tx.execute(
107            "INSERT INTO db_vault_versions (entry_id, entry_created_at, sealed, replaced_at, replaced_by, how, state) \
108             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
109            params![
110                previous.entry_id,
111                previous.entry_created_at,
112                previous.sealed,
113                previous.replaced_at,
114                previous.replaced_by,
115                previous.how,
116                previous.state
117            ],
118        )?;
119        tx.commit()?;
120        Ok(true)
121    }
122
123    /// Saves an edit of an entry: its label, fields, tags and sealed parts, only
124    /// if it still holds the sealed value `was` and the fields `was_fields` that were
125    /// read (a change to who a login is shared with is a change to its fields, which a
126    /// write from an older read must not undo), and keeps `kept` (the value a new one
127    /// replaces) in the same transaction. False, with nothing written, if the entry
128    /// changed or is gone.
129    pub fn vault_update_kept(&self, row: &super::vault::VaultRow, was: &[u8], was_fields: &str, kept: Option<&VaultVersionRow>) -> Result<bool, StoreError> {
130        self.vault_update_kept_bound(row, was, was_fields, kept, None)
131    }
132
133    pub fn vault_update_kept_bound(&self, row: &super::vault::VaultRow, was: &[u8], was_fields: &str, kept: Option<&VaultVersionRow>, link_id: Option<&str>) -> Result<bool, StoreError> {
134        let conn = self.conn.lock().unwrap();
135        let tx = conn.unchecked_transaction()?;
136        if let Some(link_id) = link_id {
137            if !super::vault_account_key::matches_link(&tx, &row.id, link_id)? {
138                return Ok(false);
139            }
140        }
141        let n = tx.execute(
142            "UPDATE db_vault_entries SET label = ?2, fields = ?3, tags = ?4, sealed = ?5, updated_at = ?6 WHERE id = ?1 AND created_at = ?7 AND sealed = ?8 AND fields = ?9",
143            params![row.id, row.label, row.fields, row.tags, row.sealed, row.updated_at, row.created_at, was, was_fields],
144        )?;
145        if n == 0 {
146            return Ok(false);
147        }
148        if let Some(v) = kept {
149            tx.execute(
150                "INSERT INTO db_vault_versions (entry_id, entry_created_at, sealed, replaced_at, replaced_by, how, state) \
151                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
152                params![v.entry_id, v.entry_created_at, v.sealed, v.replaced_at, v.replaced_by, v.how, v.state],
153            )?;
154        }
155        tx.commit()?;
156        Ok(true)
157    }
158
159    /// Changes only an entry's `fields`, and only if they are still `was_fields`
160    /// and the entry is still the one read (`created_at`, `sealed`): its label,
161    /// tags and sealed parts are left as they are. False, with nothing written, if
162    /// any of them changed or the entry is gone. For a change that touches no
163    /// sealed part (a share), where two overlapping changes must not each succeed
164    /// on what the other has since undone.
165    pub fn vault_set_fields_if(&self, id: &str, created_at: i64, sealed: &[u8], was_fields: &str, fields: &str, updated_at: i64) -> Result<bool, StoreError> {
166        let conn = self.conn.lock().unwrap();
167        let n = conn.execute(
168            "UPDATE db_vault_entries SET fields = ?5, updated_at = ?6 WHERE id = ?1 AND created_at = ?2 AND sealed = ?3 AND fields = ?4",
169            params![id, created_at, sealed, was_fields, fields, updated_at],
170        )?;
171        Ok(n > 0)
172    }
173
174    /// Commits a capture's writes in one transaction. False, with nothing written,
175    /// if an entry it replaces changed or was made again since it was read.
176    pub fn vault_capture_commit(&self, writes: &[CaptureWrite]) -> Result<bool, StoreError> {
177        let conn = self.conn.lock().unwrap();
178        let tx = conn.unchecked_transaction()?;
179        for w in writes {
180            match w {
181                CaptureWrite::Insert(row) => {
182                    tx.execute(
183                        "INSERT INTO db_vault_entries (id, kind, label, fields, tags, sealed, created_at, updated_at, last_used_at)                          VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
184                        params![row.id, row.kind, row.label, row.fields, row.tags, row.sealed, row.created_at, row.updated_at, row.last_used_at],
185                    )?;
186                }
187                CaptureWrite::Replace { row, was, was_fields, kept } => {
188                    let n = tx.execute(
189                        "UPDATE db_vault_entries SET sealed = ?2, updated_at = ?3, fields = ?6 WHERE id = ?1 AND created_at = ?4 AND sealed = ?5 AND fields = ?7",
190                        params![row.id, row.sealed, row.updated_at, row.created_at, was, row.fields, was_fields],
191                    )?;
192                    if n == 0 {
193                        // Dropping `tx` rolls back what this capture wrote so far.
194                        return Ok(false);
195                    }
196                    if let Some(v) = kept {
197                        tx.execute(
198                            "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)",
199                            params![v.entry_id, v.entry_created_at, v.sealed, v.replaced_at, v.replaced_by, v.how, v.state],
200                        )?;
201                    }
202                }
203            }
204        }
205        tx.commit()?;
206        Ok(true)
207    }
208
209    /// Keeps a rotation's new value, not yet the entry's (`state` "pending"), and
210    /// returns its number; `None` when the entry already has one waiting since
211    /// `stale_before` or later (one rotation at a time). An older one waiting is
212    /// marked `interrupted`: its rotation never finished (srv stopped).
213    pub fn vault_version_pending(&self, v: &VaultVersionRow, stale_before: i64, interrupted: &str) -> Result<Option<i64>, StoreError> {
214        let conn = self.conn.lock().unwrap();
215        let tx = conn.unchecked_transaction()?;
216        let waiting: i64 = tx.query_row(
217            "SELECT COUNT(*) FROM db_vault_versions WHERE entry_id = ?1 AND entry_created_at = ?2 AND state = ?3 AND replaced_at >= ?4",
218            params![v.entry_id, v.entry_created_at, v.state, stale_before],
219            |r| r.get(0),
220        )?;
221        if waiting > 0 {
222            return Ok(None);
223        }
224        tx.execute(
225            "UPDATE db_vault_versions SET state = ?4 WHERE entry_id = ?1 AND entry_created_at = ?2 AND state = ?3",
226            params![v.entry_id, v.entry_created_at, v.state, interrupted],
227        )?;
228        tx.execute(
229            "INSERT INTO db_vault_versions (entry_id, entry_created_at, sealed, replaced_at, replaced_by, how, state) \
230             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
231            params![v.entry_id, v.entry_created_at, v.sealed, v.replaced_at, v.replaced_by, v.how, v.state],
232        )?;
233        let seq = tx.last_insert_rowid();
234        tx.commit()?;
235        Ok(Some(seq))
236    }
237
238    /// Marks every version in `from` replaced before `before_ms` as `to` (a
239    /// rotation's pending value that never finished); returns how many.
240    pub fn vault_versions_restate_before(&self, from: &str, before_ms: i64, to: &str) -> Result<usize, StoreError> {
241        let conn = self.conn.lock().unwrap();
242        Ok(conn.execute("UPDATE db_vault_versions SET state = ?3 WHERE state = ?1 AND replaced_at < ?2", params![from, before_ms, to])?)
243    }
244
245    /// Deletes version `seq` (a rotation's value no service ever saw).
246    pub fn vault_version_delete(&self, seq: i64) -> Result<(), StoreError> {
247        let conn = self.conn.lock().unwrap();
248        conn.execute("DELETE FROM db_vault_versions WHERE seq = ?1", params![seq])?;
249        Ok(())
250    }
251
252    /// Sets version `seq`'s state (a rotation that failed); false if it is gone.
253    pub fn vault_version_mark(&self, seq: i64, state: &str) -> Result<bool, StoreError> {
254        let conn = self.conn.lock().unwrap();
255        Ok(conn.execute("UPDATE db_vault_versions SET state = ?2 WHERE seq = ?1", params![seq, state])? > 0)
256    }
257
258    /// Deletes the versions replaced before `before_ms`; returns how many. A version a sync conflict kept (`state` starts
259    /// with `kept_prefix`) is not pruned: the person settles it.
260    pub fn vault_versions_prune(&self, before_ms: i64, kept_prefix: &str) -> Result<usize, StoreError> {
261        let conn = self.conn.lock().unwrap();
262        Ok(conn.execute("DELETE FROM db_vault_versions WHERE replaced_at < ?1 AND substr(state, 1, length(?2)) != ?2", params![before_ms, kept_prefix])?)
263    }
264
265    /// How many earlier values each entry has, for the pane's list.
266    pub fn vault_version_counts(&self) -> Result<std::collections::HashMap<String, (i64, u32)>, StoreError> {
267        let conn = self.conn.lock().unwrap();
268        let mut stmt = conn.prepare("SELECT entry_id, entry_created_at, COUNT(*) FROM db_vault_versions GROUP BY entry_id, entry_created_at")?;
269        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, (r.get::<_, i64>(1)?, r.get::<_, u32>(2)?))))?;
270        Ok(rows.collect::<Result<_, _>>()?)
271    }
272}