Skip to main content

agentmux_srv_core/backend/vault/
history.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An entry's history: one row for every change to it and every use of it, in `db_vault_activity`
5//! (docs/specs/SPEC_VAULT_PARITY_ENTRY_HISTORY_REASONS_AND_IMPORT_2026_11_06.md ยง5).
6//!
7//! A row says who, what, where, under which version of the value, and why (the agent's own reason), and never
8//! holds a value, a tail, a length or a hash of one. Rows are chained: each carries the hash of the one before,
9//! and the newest row's place is also kept in the OS keychain, so a row edited, removed or slipped in by
10//! someone with only the database is found. That is evidence for the person, not proof against someone who
11//! holds the database and the keychain both.
12
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Mutex, OnceLock};
15use std::time::{Duration, Instant};
16
17use serde::Serialize;
18
19use super::{expiry, vaults, VaultActivity, PERSON};
20use crate::backend::storage::store::Store;
21use crate::backend::storage::vault::{activity_hash, VaultActivityRow};
22use crate::identity::secret_store;
23
24/// A reason has at least this many characters, and at most [`MAX_REASON`], on one line.
25pub const MIN_REASON: usize = 8;
26pub const MAX_REASON: usize = 300;
27/// An event has at most this many references, each at most [`MAX_REF`] characters.
28pub const MAX_REFS: usize = 3;
29pub const MAX_REF: usize = 120;
30/// The most rows one history answers with.
31pub const MAX_ROWS: i64 = 1000;
32
33/// The keychain item holding the newest row's place in the chain.
34const HEAD_ID: &str = "vault-history-head";
35/// The head is written to the keychain at most this often (a trailing write follows a burst).
36const HEAD_EVERY: Duration = Duration::from_secs(30);
37
38/// What an event adds to its row besides what the row already says.
39#[derive(Debug, Clone, Default)]
40pub struct Why {
41    pub reason: String,
42    pub refs: Vec<String>,
43}
44
45/// The reason an agent gives for using or changing an entry, checked before anything is asked or written:
46/// one line of [`MIN_REASON`] to [`MAX_REASON`] characters. The error is what to tell the agent.
47pub fn require_reason(raw: Option<&str>) -> Result<String, String> {
48    let line = one_line(raw.unwrap_or(""), usize::MAX);
49    let n = line.chars().count();
50    if n < MIN_REASON {
51        return Err(format!(
52            "a reason is required: say in one line what you need this for and why, for which task ({MIN_REASON} to {MAX_REASON} characters). The person sees it in the approval, and it is kept in the entry's history"
53        ));
54    }
55    if n > MAX_REASON {
56        return Err(format!("a reason is at most {MAX_REASON} characters, one line: yours is {n}"));
57    }
58    Ok(line)
59}
60
61/// `agent`, `person` (the pane) or `srv` (a sweep, an expiry reminder).
62pub fn actor_kind(actor: &str) -> &'static str {
63    if actor == PERSON {
64        "person"
65    } else if actor == expiry::ACTOR {
66        "srv"
67    } else {
68        "agent"
69    }
70}
71
72/// The actor as a row keeps it: an agent is written `agent:<id>`, so a row for an agent named like the person or the
73/// system can't be read as theirs. The person, the system, AgentMux's own parts (a label with a space, or
74/// `AgentMux`) and a label that already has a kind (`drone:<id>`) stay as they are, and an older row without the
75/// prefix still reads as an agent.
76pub fn actor_label(actor: &str) -> String {
77    let own_part = actor == super::setting_key::AGENTMUX || actor.contains(char::is_whitespace);
78    if actor == PERSON || actor == expiry::ACTOR || own_part || actor.contains(':') {
79        actor.to_string()
80    } else {
81        format!("agent:{actor}")
82    }
83}
84
85/// The agent a row names, without the kind its actor is written with. A row from before the kind was written has none.
86pub fn agent_of(actor: &str) -> &str {
87    actor.strip_prefix("agent:").unwrap_or(actor)
88}
89
90/// `text` on one line, trimmed and clipped to `max` characters.
91pub fn one_line(text: &str, max: usize) -> String {
92    let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
93    flat.chars().take(max).collect()
94}
95
96/// The references as the row keeps them: up to [`MAX_REFS`], each on one line, empty ones dropped.
97pub fn refs_text(refs: &[String]) -> String {
98    let kept: Vec<String> = refs.iter().map(|r| one_line(r, MAX_REF)).filter(|r| !r.is_empty()).take(MAX_REFS).collect();
99    if kept.is_empty() {
100        String::new()
101    } else {
102        serde_json::to_string(&kept).unwrap_or_default()
103    }
104}
105
106/// The references of a row, as a list.
107pub fn refs_of(text: &str) -> Vec<String> {
108    serde_json::from_str(text).unwrap_or_default()
109}
110
111/// This machine's name, as the rows say where an event happened. Empty when it can't be found.
112fn host() -> &'static str {
113    static HOST: OnceLock<String> = OnceLock::new();
114    HOST.get_or_init(|| {
115        let found = ["HOSTNAME", "COMPUTERNAME", "HOST"]
116            .iter()
117            .filter_map(|k| std::env::var(k).ok())
118            .chain(std::fs::read_to_string("/etc/hostname").ok())
119            .map(|h| h.trim().split('.').next().unwrap_or("").to_string())
120            .find(|h| !h.is_empty());
121        found.unwrap_or_default()
122    })
123}
124
125/// Fills in what the history keeps on every row (who kind of actor, the machine, a clean reason and references),
126/// appends it to the chain, and notes the chain's new head. A failure is logged, not raised: a use or a change
127/// never fails for want of a history line.
128pub fn append(store: &Store, mut row: VaultActivityRow) {
129    row.actor_kind = actor_kind(&row.actor).into();
130    row.actor = actor_label(&row.actor);
131    row.host = host().into();
132    row.reason = one_line(&row.reason, MAX_REASON);
133    match store.vault_activity_add(&row) {
134        Ok(stored) => note_head(&stored),
135        Err(e) => tracing::warn!(error = %e, action = row.action, "vault: couldn't record activity"),
136    }
137}
138
139/// An entry's history, newest first: every change and use since it was made. `agent` is the proven agent asking
140/// (`None` for one that isn't, which sees what every agent may), or the person's pane (`person`, which may see all).
141pub fn history_for(store: &Store, entry_id: &str, agent: Asker<'_>, limit: i64) -> Result<Vec<VaultActivity>, String> {
142    let row = store.vault_get(entry_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {entry_id}"))?;
143    if let Asker::Agent(agent) = agent {
144        let allowed = store.vaults().map_err(|e| e.to_string())?.iter().find(|v| v.id == row.vault_id).is_none_or(|v| vaults::may_use(v, agent));
145        if !allowed {
146            // The same answer as for an id that isn't there.
147            return Err(format!("no entry {entry_id}"));
148        }
149    }
150    let rows = store.vault_activity_history(entry_id, row.created_at, limit.clamp(1, MAX_ROWS)).map_err(|e| e.to_string())?;
151    Ok(rows.into_iter().map(VaultActivity::from).collect())
152}
153
154/// Who is asking for a history.
155#[derive(Debug, Clone, Copy)]
156pub enum Asker<'a> {
157    /// The person, in the pane.
158    Person,
159    /// An agent: `Some(id)` when it proved who it is.
160    Agent(Option<&'a str>),
161}
162
163/// Where the chain stands, for the pane.
164#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
165#[ts(export, export_to = "../../../frontend/types/rpc/")]
166pub struct VaultChain {
167    /// No line was changed, removed or slipped in that the chain can tell.
168    pub intact: bool,
169    /// How many lines are chained and checked.
170    pub checked: usize,
171    /// How many older lines were made before the chain began, and so can't be checked.
172    pub before_chain: usize,
173    /// How many lines after the chain began have no place in it and look like what an older AgentMux sharing this
174    /// computer's store writes (it doesn't know the chain). They are not checked, and are shown as a count.
175    pub unchained_after: usize,
176    /// The first line found wrong, when not intact.
177    #[ts(type = "number | null")]
178    pub broken_at: Option<i64>,
179    /// Whether the newest line was compared with the place the keychain keeps for it. False when the keychain
180    /// couldn't be read or holds none yet: lines removed from the end of the record would not be seen.
181    pub head_checked: bool,
182    /// What is wrong with it, in a sentence; empty when intact.
183    pub problem: String,
184}
185
186/// The place in the chain the keychain holds.
187#[derive(Debug, Clone, PartialEq)]
188pub struct Head {
189    pub seq: i64,
190    pub hash: String,
191}
192
193/// Whether a row with no hash is what a build that doesn't know the chain writes: none of the columns the chain
194/// added. (Someone blanking them all by hand looks the same, which is why such rows are counted and shown.)
195fn looks_unchained(r: &VaultActivityRow) -> bool {
196    r.version == 0 && r.actor_kind.is_empty() && r.host.is_empty() && r.reason.is_empty() && r.refs.is_empty() && r.prev_hash.is_empty()
197}
198
199/// Walks `rows` (oldest first) and says whether the chain holds, and whether `head` is a row in it.
200pub fn verify_chain(rows: &[VaultActivityRow], head: Option<&Head>) -> VaultChain {
201    let mut out = VaultChain { intact: true, checked: 0, before_chain: 0, unchained_after: 0, broken_at: None, head_checked: head.is_some(), problem: String::new() };
202    let mut prev = String::new();
203    let mut broke = |out: &mut VaultChain, seq: i64, problem: &str| {
204        out.intact = false;
205        out.broken_at = Some(seq);
206        out.problem = problem.into();
207    };
208    for row in rows {
209        if row.hash.is_empty() {
210            // Before the chain began, or after it by an older build still running on the same store. Such a row
211            // has none of the chain's columns; one that has some but no place in the chain was taken out of it.
212            if !looks_unchained(row) {
213                broke(&mut out, row.seq, "this line was taken out of the chain");
214                return out;
215            }
216            if out.checked > 0 {
217                out.unchained_after += 1;
218            } else {
219                out.before_chain += 1;
220            }
221            continue;
222        }
223        if row.prev_hash != prev {
224            broke(&mut out, row.seq, "the line before this one was removed or changed");
225            return out;
226        }
227        if activity_hash(&prev, row) != row.hash {
228            broke(&mut out, row.seq, "this line was changed");
229            return out;
230        }
231        prev = row.hash.clone();
232        out.checked += 1;
233    }
234    if let Some(head) = head {
235        match rows.iter().find(|r| r.seq == head.seq) {
236            None => broke(&mut out, head.seq, "the newest lines were removed"),
237            Some(r) if r.hash != head.hash => broke(&mut out, head.seq, "this line is not the one the keychain recorded"),
238            Some(_) => {}
239        }
240    }
241    out
242}
243
244/// Where the chain stands now: the whole table walked, and the keychain's head compared.
245pub fn check(store: &Store) -> Result<VaultChain, String> {
246    let rows = store.vault_activity_all().map_err(|e| e.to_string())?;
247    Ok(verify_chain(&rows, read_head().as_ref()))
248}
249
250fn read_head() -> Option<Head> {
251    if cfg!(any(test, feature = "test-support")) {
252        return None;
253    }
254    let stored = secret_store::get_optional(HEAD_ID).ok()??;
255    let (seq, hash) = stored.split_once(':')?;
256    Some(Head { seq: seq.parse().ok()?, hash: hash.to_string() })
257}
258
259struct HeadWrites {
260    last: Option<Instant>,
261    pending: Option<String>,
262    trailing: bool,
263}
264
265static HEAD_WRITES: Mutex<HeadWrites> = Mutex::new(HeadWrites { last: None, pending: None, trailing: false });
266static HEAD_FAILED_BEFORE: AtomicBool = AtomicBool::new(false);
267
268fn write_head(value: &str) {
269    if let Err(e) = secret_store::put(HEAD_ID, value) {
270        // Said once: a keychain that can't be written stays so for every line after.
271        if !HEAD_FAILED_BEFORE.swap(true, Ordering::Relaxed) {
272            tracing::warn!(error = %e, "vault: couldn't keep the history's head in the keychain");
273        }
274    }
275}
276
277/// Keeps the new row's place in the keychain: at once, or at most every [`HEAD_EVERY`], with a write after a
278/// burst so the head catches up with the last row.
279fn note_head(row: &VaultActivityRow) {
280    if cfg!(any(test, feature = "test-support")) {
281        return;
282    }
283    let value = format!("{}:{}", row.seq, row.hash);
284    let mut st = HEAD_WRITES.lock().unwrap();
285    if st.last.is_none_or(|t| t.elapsed() >= HEAD_EVERY) {
286        st.last = Some(Instant::now());
287        st.pending = None;
288        drop(st);
289        write_head(&value);
290        return;
291    }
292    st.pending = Some(value);
293    if st.trailing {
294        return;
295    }
296    st.trailing = true;
297    let wait = HEAD_EVERY.saturating_sub(st.last.map_or(Duration::ZERO, |t| t.elapsed()));
298    drop(st);
299    std::thread::spawn(move || {
300        std::thread::sleep(wait);
301        let value = {
302            let mut st = HEAD_WRITES.lock().unwrap();
303            st.trailing = false;
304            st.last = Some(Instant::now());
305            st.pending.take()
306        };
307        if let Some(value) = value {
308            write_head(&value);
309        }
310    });
311}
312
313#[cfg(test)]
314mod actor_label_tests {
315    use super::*;
316
317    #[test]
318    fn an_agent_is_written_with_its_kind_and_the_rest_stay() {
319        assert_eq!(actor_label("lolly"), "agent:lolly");
320        assert_eq!(actor_label(PERSON), PERSON);
321        assert_eq!(actor_label(expiry::ACTOR), expiry::ACTOR);
322        assert_eq!(actor_label("drone:d1"), "drone:d1");
323        assert_eq!(actor_label("agent:lolly"), "agent:lolly");
324        assert_eq!(actor_label("AgentMux voice input"), "AgentMux voice input");
325        assert_eq!(actor_label(super::super::setting_key::AGENTMUX), super::super::setting_key::AGENTMUX);
326    }
327
328    #[test]
329    fn an_agent_named_like_the_person_is_not_read_as_the_person() {
330        // An old bare row still reads as the kind it always did; a new row for such an agent says it is an agent.
331        assert_eq!(actor_kind(&actor_label("lolly")), "agent");
332        assert_eq!(actor_kind(PERSON), "person");
333        assert_eq!(agent_of("agent:lolly"), "lolly");
334        assert_eq!(agent_of("lolly"), "lolly");
335    }
336}