Skip to main content

agentmux_srv_core/backend/storage/
vault_changes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the Vault keeps of changes agents made, for the person to look at (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md):
5//! which entries hold a value an agent had the Vault read (an import or a capture), or a site an agent chose, that the person
6//! has not yet seen; the details an agent's edit replaced, kept 7 days; and the changes of where a login is offered that an
7//! agent proposed on a login it did not make. The rules are in `backend::vault::agent_set`, `details` and `proposals`;
8//! nothing here holds a value.
9
10use rusqlite::{params, OptionalExtension};
11
12use super::error::StoreError;
13use super::store::Store;
14
15pub(super) const SCHEMA: &str = "
16    -- An entry whose value an agent had the Vault read (`import`, `capture`) and the person has not seen yet: a use of it
17    -- never goes ahead on silence until they have marked it seen or answered a use of it once. `entry_created_at` ties the
18    -- row to one incarnation of a reused id. One row per entry; a later change by an agent replaces it.
19    CREATE TABLE IF NOT EXISTS db_vault_unseen (
20        entry_id         TEXT PRIMARY KEY,
21        entry_created_at INTEGER NOT NULL,
22        by_agent         TEXT NOT NULL,
23        at               INTEGER NOT NULL
24    );
25
26    -- The details an agent's edit replaced (label, plain fields, tags: never a value), kept 7 days so the person can put them
27    -- back. Written in the same transaction as the change.
28    CREATE TABLE IF NOT EXISTS db_vault_details_kept (
29        id               INTEGER PRIMARY KEY AUTOINCREMENT,
30        entry_id         TEXT NOT NULL,
31        entry_created_at INTEGER NOT NULL,
32        label            TEXT NOT NULL,
33        fields           TEXT NOT NULL,
34        tags             TEXT NOT NULL,
35        changed_at       INTEGER NOT NULL,
36        changed_by       TEXT NOT NULL,
37        what             TEXT NOT NULL
38    );
39    CREATE INDEX IF NOT EXISTS db_vault_details_kept_entry ON db_vault_details_kept (entry_id, entry_created_at);
40
41    -- A change of where a login is offered (site, realm, proxy) that an agent asked for on a login it did not make. It is
42    -- only a record until the person accepts it; one per entry and field, kept 7 days.
43    CREATE TABLE IF NOT EXISTS db_vault_proposals (
44        entry_id         TEXT NOT NULL,
45        field            TEXT NOT NULL,
46        entry_created_at INTEGER NOT NULL,
47        entry_updated_at INTEGER NOT NULL,
48        value            TEXT NOT NULL,
49        agent            TEXT NOT NULL,
50        reason           TEXT NOT NULL,
51        at               INTEGER NOT NULL,
52        PRIMARY KEY (entry_id, field)
53    );
54
55    -- Which changes by agents the person has marked seen, on this machine only (never synced): one by one, or every change up
56    -- to a line (`Seen all`).
57    CREATE TABLE IF NOT EXISTS db_vault_changes_seen (
58        seq INTEGER PRIMARY KEY
59    );
60    CREATE TABLE IF NOT EXISTS db_vault_changes_seen_all (
61        id          INTEGER PRIMARY KEY CHECK (id = 1),
62        through_seq INTEGER NOT NULL
63    );
64";
65/// Added to a table an older build made.
66pub(super) const COLUMNS: [&str; 1] = ["ALTER TABLE db_vault_unseen ADD COLUMN what TEXT NOT NULL DEFAULT 'value'"];
67
68/// An entry's value an agent set and the person has not seen.
69#[derive(Debug, Clone, PartialEq)]
70pub struct Unseen {
71    pub by_agent: String,
72    pub at: i64,
73    /// What the agent set: `value`, `site` or `value and site`.
74    pub what: String,
75}
76
77/// The two marks an agent's changes can leave on an entry.
78pub const VALUE: &str = "value";
79pub const SITE: &str = "site";
80
81/// `old` and `new` together: an entry whose value and site an agent each set is marked for both.
82fn merged(old: &str, new: &str) -> String {
83    let (value, site) = (old.contains(VALUE) || new.contains(VALUE), old.contains(SITE) || new.contains(SITE));
84    match (value, site) {
85        (true, true) => format!("{VALUE} and {SITE}"),
86        (false, true) => SITE.to_string(),
87        _ => VALUE.to_string(),
88    }
89}
90
91/// The details an agent's edit replaced.
92#[derive(Debug, Clone, PartialEq)]
93pub struct DetailsKept {
94    pub entry_id: String,
95    pub entry_created_at: i64,
96    pub label: String,
97    pub fields: String,
98    pub tags: String,
99    pub changed_at: i64,
100    pub changed_by: String,
101    /// What the edit changed, in names (`label`, `field site`).
102    pub what: String,
103}
104
105/// An agent's request to change where a login is offered, waiting for the person.
106#[derive(Debug, Clone, PartialEq)]
107pub struct Proposal {
108    pub entry_id: String,
109    pub field: String,
110    pub entry_created_at: i64,
111    pub entry_updated_at: i64,
112    pub value: String,
113    pub agent: String,
114    pub reason: String,
115    pub at: i64,
116}
117
118/// [`Store::vault_unseen_mark`] inside the caller's transaction.
119fn mark_in(tx: &rusqlite::Transaction<'_>, entry_id: &str, entry_created_at: i64, by_agent: &str, at: i64, what: &str) -> Result<(), StoreError> {
120    tx.execute("DELETE FROM db_vault_grants WHERE entry_id = ?1", params![entry_id])?;
121    let before: Option<String> = tx.query_row("SELECT what FROM db_vault_unseen WHERE entry_id = ?1 AND entry_created_at = ?2", params![entry_id, entry_created_at], |r| r.get(0)).optional()?;
122    let what = before.map_or_else(|| what.to_string(), |old| merged(&old, what));
123    tx.execute(
124        "INSERT OR REPLACE INTO db_vault_unseen (entry_id, entry_created_at, by_agent, at, what) VALUES (?1, ?2, ?3, ?4, ?5)",
125        params![entry_id, entry_created_at, by_agent, at, what],
126    )?;
127    Ok(())
128}
129
130impl Store {
131    /// Records that `by_agent` set the `what` (value or site) of `entry_id` (made at `entry_created_at`) at `at`, unseen by the person. The
132    /// entry's *Always* grants go in the same step: they were given for the value the person saw, and several uses skip the
133    /// card on a grant, so a value an agent replaced must ask again.
134    pub fn vault_unseen_mark(&self, entry_id: &str, entry_created_at: i64, by_agent: &str, at: i64, what: &str) -> Result<(), StoreError> {
135        let mut conn = self.conn.lock().unwrap();
136        let tx = conn.transaction()?;
137        mark_in(&tx, entry_id, entry_created_at, by_agent, at, what)?;
138        tx.commit()?;
139        Ok(())
140    }
141
142    /// The unseen value of `entry_id`, if the entry that holds it is still the one it was set on.
143    pub fn vault_unseen_get(&self, entry_id: &str) -> Result<Option<Unseen>, StoreError> {
144        let conn = self.conn.lock().unwrap();
145        Ok(conn
146            .query_row(
147                "SELECT u.by_agent, u.at, u.what FROM db_vault_unseen u JOIN db_vault_entries e ON e.id = u.entry_id AND e.created_at = u.entry_created_at WHERE u.entry_id = ?1",
148                params![entry_id],
149                |r| Ok(Unseen { by_agent: r.get(0)?, at: r.get(1)?, what: r.get(2)? }),
150            )
151            .optional()?)
152    }
153
154    /// The person has seen it, or answered a use of it: it is trusted as any other. True when there was a mark.
155    pub fn vault_unseen_clear(&self, entry_id: &str) -> Result<bool, StoreError> {
156        let conn = self.conn.lock().unwrap();
157        Ok(conn.execute("DELETE FROM db_vault_unseen WHERE entry_id = ?1", params![entry_id])? > 0)
158    }
159
160    /// An edit of an entry's details (label, plain fields, tags), only if it still holds the sealed value `was` and the fields
161    /// `was_fields`, label and tags that were read (`kept` holds them: a change of only the label or the tags is not
162    /// overwritten by an older read), and the details it replaces kept in the same transaction. False, with nothing written, if
163    /// the entry changed or is gone. With `unseen_site_by` (the agent), the entry's place is marked unseen and its *Always*
164    /// grants dropped in the same transaction: a change of where a login is offered is never made without the mark.
165    pub fn vault_update_details_kept(&self, row: &super::vault::VaultRow, was: &[u8], was_fields: &str, kept: &DetailsKept, unseen_site_by: Option<&str>) -> Result<bool, StoreError> {
166        let mut conn = self.conn.lock().unwrap();
167        let tx = conn.transaction()?;
168        let n = tx.execute(
169            "UPDATE db_vault_entries SET label = ?2, fields = ?3, tags = ?4, updated_at = ?5 WHERE id = ?1 AND created_at = ?6 AND sealed = ?7 AND fields = ?8 AND label = ?9 AND tags = ?10",
170            params![row.id, row.label, row.fields, row.tags, row.updated_at, row.created_at, was, was_fields, kept.label, kept.tags],
171        )?;
172        if n == 0 {
173            return Ok(false);
174        }
175        tx.execute(
176            "INSERT INTO db_vault_details_kept (entry_id, entry_created_at, label, fields, tags, changed_at, changed_by, what) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
177            params![kept.entry_id, kept.entry_created_at, kept.label, kept.fields, kept.tags, kept.changed_at, kept.changed_by, kept.what],
178        )?;
179        if let Some(agent) = unseen_site_by {
180            mark_in(&tx, &row.id, row.created_at, agent, row.updated_at, SITE)?;
181        }
182        tx.commit()?;
183        Ok(true)
184    }
185
186    /// The details earlier edits of the entry replaced, newest first.
187    pub fn vault_details_kept(&self, entry_id: &str, entry_created_at: i64) -> Result<Vec<DetailsKept>, StoreError> {
188        let conn = self.conn.lock().unwrap();
189        let mut stmt = conn.prepare(
190            "SELECT entry_id, entry_created_at, label, fields, tags, changed_at, changed_by, what FROM db_vault_details_kept WHERE entry_id = ?1 AND entry_created_at = ?2 ORDER BY id DESC",
191        )?;
192        let rows = stmt.query_map(params![entry_id, entry_created_at], |r| {
193            Ok(DetailsKept { entry_id: r.get(0)?, entry_created_at: r.get(1)?, label: r.get(2)?, fields: r.get(3)?, tags: r.get(4)?, changed_at: r.get(5)?, changed_by: r.get(6)?, what: r.get(7)? })
194        })?;
195        Ok(rows.collect::<Result<_, _>>()?)
196    }
197
198    /// Drops one kept row, once its change has been put back, so it is not offered again.
199    pub fn vault_details_kept_delete(&self, kept: &DetailsKept) -> Result<(), StoreError> {
200        let conn = self.conn.lock().unwrap();
201        conn.execute(
202            "DELETE FROM db_vault_details_kept WHERE entry_id = ?1 AND entry_created_at = ?2 AND changed_at = ?3 AND changed_by = ?4 AND what = ?5",
203            params![kept.entry_id, kept.entry_created_at, kept.changed_at, kept.changed_by, kept.what],
204        )?;
205        Ok(())
206    }
207
208    /// Drops the kept details older than `before_ms`.
209    pub fn vault_details_prune(&self, before_ms: i64) -> Result<usize, StoreError> {
210        let conn = self.conn.lock().unwrap();
211        Ok(conn.execute("DELETE FROM db_vault_details_kept WHERE changed_at < ?1", params![before_ms])?)
212    }
213
214    /// Records `p`, replacing the one for the same entry and field.
215    pub fn vault_proposal_put(&self, p: &Proposal) -> Result<(), StoreError> {
216        let conn = self.conn.lock().unwrap();
217        conn.execute(
218            "INSERT OR REPLACE INTO db_vault_proposals (entry_id, field, entry_created_at, entry_updated_at, value, agent, reason, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
219            params![p.entry_id, p.field, p.entry_created_at, p.entry_updated_at, p.value, p.agent, p.reason, p.at],
220        )?;
221        Ok(())
222    }
223
224    /// The proposals not older than `since_ms`, for one entry or (`None`) every entry, oldest first.
225    pub fn vault_proposals(&self, entry_id: Option<&str>, since_ms: i64) -> Result<Vec<Proposal>, StoreError> {
226        let conn = self.conn.lock().unwrap();
227        let mut stmt = conn.prepare(
228            "SELECT entry_id, field, entry_created_at, entry_updated_at, value, agent, reason, at FROM db_vault_proposals WHERE at >= ?1 AND (?2 IS NULL OR entry_id = ?2) ORDER BY at, entry_id, field",
229        )?;
230        let rows = stmt.query_map(params![since_ms, entry_id], |r| {
231            Ok(Proposal { entry_id: r.get(0)?, field: r.get(1)?, entry_created_at: r.get(2)?, entry_updated_at: r.get(3)?, value: r.get(4)?, agent: r.get(5)?, reason: r.get(6)?, at: r.get(7)? })
232        })?;
233        Ok(rows.collect::<Result<_, _>>()?)
234    }
235
236    /// Drops a proposal. True when there was one.
237    pub fn vault_proposal_delete(&self, entry_id: &str, field: &str) -> Result<bool, StoreError> {
238        let conn = self.conn.lock().unwrap();
239        Ok(conn.execute("DELETE FROM db_vault_proposals WHERE entry_id = ?1 AND field = ?2", params![entry_id, field])? > 0)
240    }
241
242    /// The person marks the change recorded by history line `seq` as seen.
243    pub fn vault_change_seen(&self, seq: i64) -> Result<(), StoreError> {
244        let conn = self.conn.lock().unwrap();
245        conn.execute("INSERT OR IGNORE INTO db_vault_changes_seen (seq) VALUES (?1)", params![seq])?;
246        Ok(())
247    }
248
249    /// The person marks every change up to history line `through_seq` as seen. The one-by-one marks it covers go.
250    pub fn vault_changes_seen_all(&self, through_seq: i64) -> Result<(), StoreError> {
251        let mut conn = self.conn.lock().unwrap();
252        let tx = conn.transaction()?;
253        tx.execute(
254            "INSERT INTO db_vault_changes_seen_all (id, through_seq) VALUES (1, ?1) ON CONFLICT(id) DO UPDATE SET through_seq = MAX(through_seq, excluded.through_seq)",
255            params![through_seq],
256        )?;
257        tx.execute("DELETE FROM db_vault_changes_seen WHERE seq <= ?1", params![through_seq])?;
258        tx.commit()?;
259        Ok(())
260    }
261
262    /// What the person has marked seen: every change up to the first number, and the lines in the set.
263    pub fn vault_changes_seen(&self) -> Result<(i64, std::collections::HashSet<i64>), StoreError> {
264        let conn = self.conn.lock().unwrap();
265        let through: i64 = conn.query_row("SELECT through_seq FROM db_vault_changes_seen_all WHERE id = 1", [], |r| r.get(0)).optional()?.unwrap_or(0);
266        let mut stmt = conn.prepare("SELECT seq FROM db_vault_changes_seen")?;
267        let seqs = stmt.query_map([], |r| r.get::<_, i64>(0))?.collect::<Result<_, _>>()?;
268        Ok((through, seqs))
269    }
270
271    /// Drops the proposals older than `before_ms`.
272    pub fn vault_proposals_prune(&self, before_ms: i64) -> Result<usize, StoreError> {
273        let conn = self.conn.lock().unwrap();
274        Ok(conn.execute("DELETE FROM db_vault_proposals WHERE at < ?1", params![before_ms])?)
275    }
276}