Skip to main content

agentmux_srv_core/backend/vault/
agent_changes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the person sees instead of a card: the changes agents made that they have not looked at yet, and what they can do
5//! about each (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md ยง5).
6//!
7//! A change is a history line an agent wrote. The list is read from the history, so it cannot disagree with it. *Seen* is a
8//! mark on this machine only, and it also trusts the value or place the agent set (`agent_set`). *Undo* puts back what the
9//! change replaced (the earlier value, the earlier details) or removes an entry an agent added, as the person's own action.
10//! Nothing here holds a value.
11
12use std::collections::BTreeMap;
13
14use serde::Serialize;
15
16use agentmux_common::time::now_ms;
17
18use super::{agent_set, expiry, history, inspect, proposals, record_line, versions, Line, PERSON};
19use crate::backend::storage::store::Store;
20use crate::backend::storage::vault::{VaultActivityRow, VaultRow};
21use crate::backend::storage::vault_changes::DetailsKept;
22
23/// How far back the list reaches.
24const LOOK_BACK_MS: i64 = 30 * 24 * 60 * 60 * 1000;
25/// The most changes it lists.
26const MOST: i64 = 300;
27/// How near in time an earlier value or earlier details are to the line that replaced them: they are written in one call.
28const NEAR_MS: i64 = 5_000;
29/// The Activity action of the person putting earlier details back.
30pub const RESTORED_DETAILS: &str = "restored earlier details";
31
32/// The lines of an agent that are changes to look at.
33const ACTIONS: [&str; 5] = ["generated", "imported", "captured", inspect::CHANGED_DETAILS, proposals::PROPOSED];
34
35/// A pending proposal's field, what is proposed and what the login has now.
36#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
37#[ts(export, export_to = "../../../frontend/types/rpc/")]
38pub struct ProposalInfo {
39    pub field: String,
40    /// When it was proposed: what Accept and Dismiss name, so a replacement is never applied in its place.
41    #[ts(type = "number")]
42    pub at: i64,
43    pub value: String,
44    pub current: String,
45}
46
47/// One change by an agent.
48#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
49#[ts(export, export_to = "../../../frontend/types/rpc/")]
50pub struct AgentChange {
51    /// The history line's number on this machine: what *Seen* and *Undo* name.
52    #[ts(type = "number")]
53    pub seq: i64,
54    #[ts(type = "number")]
55    pub at: i64,
56    /// The agent's id, as the history writes it after `agent:`.
57    pub agent: String,
58    pub entry_id: String,
59    pub entry_label: String,
60    /// `added`, `new value`, `changed details` or `proposal`.
61    pub kind: String,
62    /// The history line's action (`generated`, `imported`, `captured`, `changed details`) and its target in names.
63    pub action: String,
64    pub target: String,
65    /// The agent's reason, as it wrote it: text, never markup.
66    pub reason: String,
67    pub seen: bool,
68    /// What *Undo* does: `remove` (an entry the agent added), `restore value`, `restore details`, or empty.
69    pub undo: String,
70    /// A new value on an entry the person made.
71    pub replaces_yours: bool,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    #[ts(optional)]
74    pub proposal: Option<ProposalInfo>,
75}
76
77fn agent_of(actor: &str) -> String {
78    actor.strip_prefix("agent:").unwrap_or(actor).to_string()
79}
80
81fn is_agent(row: &VaultActivityRow, agent_label: &str) -> bool {
82    row.actor_kind == "agent" && history::actor_label(&row.actor) == agent_label
83}
84
85/// The lines by this agent on this entry that `keep` accepts, as (time, line number).
86fn agent_lines(rows: &[VaultActivityRow], entry_id: &str, label: &str, keep: impl Fn(&VaultActivityRow) -> bool) -> Vec<(i64, i64)> {
87    rows.iter().filter(|r| r.entry_id == entry_id && is_agent(r, label) && keep(r)).map(|r| (r.at, r.seq)).collect()
88}
89
90/// Gives each thing kept (the times in `kept`, oldest first) the one line of `lines` that wrote it: a line is written in the
91/// same call as the version or details it replaced, so each takes the nearest line not already taken. Two quick changes by one
92/// agent each keep their own, even in one millisecond, and a kept row whose own line is gone is nobody's.
93fn assign(lines: &[(i64, i64)], kept: &[i64]) -> Vec<Option<i64>> {
94    let mut taken = std::collections::HashSet::new();
95    kept.iter()
96        .map(|at| {
97            let line = lines.iter().filter(|l| !taken.contains(&l.1) && (l.0 - at).abs() <= NEAR_MS).min_by_key(|l| ((l.0 - at).abs(), l.1)).map(|l| l.1);
98            taken.extend(line);
99            line
100        })
101        .collect()
102}
103
104/// The earlier value `row` replaced, while it is still kept.
105fn earlier_value(store: &Store, entry: &VaultRow, row: &VaultActivityRow, rows: &[VaultActivityRow]) -> Option<i64> {
106    let label = history::actor_label(&row.actor);
107    let lines = agent_lines(rows, &entry.id, &label, |r| r.action != inspect::CHANGED_DETAILS && r.action != proposals::PROPOSED);
108    let mut mine: Vec<_> = store.vault_versions(&entry.id, entry.created_at).ok()?.into_iter().filter(|v| v.state == versions::PREVIOUS && history::actor_label(&v.replaced_by) == label).collect();
109    mine.sort_by_key(|v| (v.replaced_at, v.seq));
110    let owners = assign(&lines, &mine.iter().map(|v| v.replaced_at).collect::<Vec<_>>());
111    mine.iter().zip(owners).find(|(_, owner)| *owner == Some(row.seq)).map(|(v, _)| v.seq)
112}
113
114/// The details `row` replaced, while they are still kept.
115fn earlier_details(store: &Store, entry: &VaultRow, row: &VaultActivityRow, rows: &[VaultActivityRow]) -> Option<DetailsKept> {
116    let label = history::actor_label(&row.actor);
117    let lines = agent_lines(rows, &entry.id, &label, |r| r.action == inspect::CHANGED_DETAILS && r.target == row.target);
118    let mut mine: Vec<_> = store.vault_details_kept(&entry.id, entry.created_at).ok()?.into_iter().rev().filter(|d| d.changed_by == label && d.what == row.target).collect();
119    mine.sort_by_key(|d| d.changed_at);
120    let owners = assign(&lines, &mine.iter().map(|d| d.changed_at).collect::<Vec<_>>());
121    mine.into_iter().zip(owners).find(|(_, owner)| *owner == Some(row.seq)).map(|(d, _)| d)
122}
123
124/// `row` as a change the person can look at, or none when it is not one now (the entry is gone, the proposal is settled).
125fn change_of(store: &Store, rows: &[VaultActivityRow], row: &VaultActivityRow, seen: bool) -> Option<AgentChange> {
126    let entry = store.vault_get(&row.entry_id).ok()??;
127    let first = store.vault_activity_first(&entry.id, entry.created_at).ok()?;
128    // Only a creation line makes an entry "added": one with no local creation line (from sync or a bulk import) has an edit
129    // for its first line, and removing it as an Undo would delete the person's entry.
130    let created_here = first.as_ref().filter(|f| inspect::is_creation(f, &entry));
131    let by_agent = created_here.is_some_and(|f| f.actor_kind == "agent");
132    let added = created_here.is_some_and(|f| f.seq == row.seq);
133    let mut change = AgentChange {
134        seq: row.seq,
135        at: row.at,
136        agent: agent_of(&row.actor),
137        entry_id: entry.id.clone(),
138        entry_label: entry.label.clone(),
139        kind: String::new(),
140        action: row.action.clone(),
141        target: row.target.clone(),
142        reason: row.reason.clone(),
143        seen,
144        undo: String::new(),
145        replaces_yours: false,
146        proposal: None,
147    };
148    let recent = now_ms() - row.at <= versions::KEEP_MS;
149    if row.action == proposals::PROPOSED {
150        let field = row.target.strip_prefix("field ").unwrap_or(&row.target).to_string();
151        let waiting = store.vault_proposals(Some(&entry.id), now_ms() - proposals::KEEP_MS).ok()?.into_iter().find(|p| {
152            let lines = agent_lines(rows, &entry.id, &history::actor_label(&row.actor), |r| r.action == proposals::PROPOSED && r.target == row.target);
153            p.field == field && history::actor_label(&p.agent) == history::actor_label(&row.actor) && assign(&lines, &[p.at]) == [Some(row.seq)]
154        })?;
155        let current = signins_field(&entry, &field);
156        change.kind = "proposal".into();
157        change.proposal = Some(ProposalInfo { field, at: waiting.at, value: waiting.value, current });
158    } else if added {
159        change.kind = "added".into();
160        change.undo = "remove".into();
161    } else if row.action == inspect::CHANGED_DETAILS {
162        change.kind = "changed details".into();
163        if recent && earlier_details(store, &entry, row, rows).is_some() {
164            change.undo = "restore details".into();
165        }
166    } else {
167        change.kind = "new value".into();
168        change.replaces_yours = !by_agent;
169        if recent && earlier_value(store, &entry, row, rows).is_some() {
170            change.undo = "restore value".into();
171        }
172    }
173    Some(change)
174}
175
176fn signins_field(entry: &VaultRow, field: &str) -> String {
177    super::signins::fields_of(entry).get(field).cloned().unwrap_or_default()
178}
179
180/// The changes by agents, newest first, of one entry (`entry`) or all, with the ones the person has marked seen left out
181/// unless `include_seen`. A proposal, and a new value on an entry the person made, come first.
182pub fn list(store: &Store, entry: Option<&str>, include_seen: bool) -> Result<Vec<AgentChange>, String> {
183    versions::prune(store);
184    let since = now_ms() - LOOK_BACK_MS;
185    let rows = store.vault_activity_agent_changes(since, &ACTIONS, entry, include_seen, MOST).map_err(|e| e.to_string())?;
186    let (through, marked) = store.vault_changes_seen().map_err(|e| e.to_string())?;
187    let mut histories = BTreeMap::new();
188    let mut out = Vec::new();
189    for row in &rows {
190        if !histories.contains_key(&row.entry_id) {
191            let history = store.vault_activity_agent_changes(since, &ACTIONS, Some(&row.entry_id), true, -1).map_err(|e| e.to_string())?;
192            histories.insert(row.entry_id.clone(), history);
193        }
194        if let Some(change) = change_of(store, &histories[&row.entry_id], row, row.seq <= through || marked.contains(&row.seq)) {
195            if include_seen || !change.seen {
196                out.push(change);
197            }
198        }
199    }
200    out.sort_by_key(|c| (!(c.kind == "proposal" || c.replaces_yours), std::cmp::Reverse(c.seq)));
201    Ok(out)
202}
203
204/// A change that can have left the entry's unseen mark: a new entry, a new value, or a changed place. A new label, tags or a
205/// plain field do not, and a proposal sets nothing until it is accepted.
206fn sets_the_mark(c: &AgentChange) -> bool {
207    match c.kind.as_str() {
208        "added" | "new value" => true,
209        "changed details" => c.target.split(", ").any(|t| matches!(t, "field site" | "field realm" | "field proxy")),
210        _ => false,
211    }
212}
213
214/// The value or place an agent set is trusted once the person has dealt with every change by an agent on the entry: the mark
215/// is the entry's, not one change's, so a newer change that is still listed keeps it.
216fn trust_when_none_left(store: &Store, entry_id: &str) -> Result<(), String> {
217    if !list(store, Some(entry_id), false)?.iter().any(sets_the_mark) {
218        agent_set::clear(store, entry_id);
219    }
220    Ok(())
221}
222
223/// The person has looked at the change recorded by line `seq` (one an agent wrote): it leaves the list, and the value or place
224/// the agent set is trusted from now on, as if they had answered a use of it, once no other change by an agent on the entry
225/// is left unseen.
226pub fn seen(store: &Store, seq: i64) -> Result<(), String> {
227    let row = store.vault_activity_get(seq).map_err(|e| e.to_string())?.filter(|r| r.actor_kind == "agent").ok_or("no such change by an agent")?;
228    store.vault_change_seen(seq).map_err(|e| e.to_string())?;
229    trust_when_none_left(store, &row.entry_id)
230}
231
232/// [`seen`] for every change listed now except a proposal, which waits for Accept or Dismiss and so stays listed.
233pub fn seen_all(store: &Store) -> Result<(), String> {
234    let all = list(store, None, false)?;
235    let floor = all.iter().filter(|c| c.kind == "proposal").map(|c| c.seq).min();
236    let mut through = 0;
237    for c in all.iter().filter(|c| c.kind != "proposal") {
238        agent_set::clear(store, &c.entry_id);
239        if floor.is_none_or(|f| c.seq < f) {
240            through = through.max(c.seq);
241        } else {
242            store.vault_change_seen(c.seq).map_err(|e| e.to_string())?;
243        }
244    }
245    if through > 0 {
246        store.vault_changes_seen_all(through).map_err(|e| e.to_string())?;
247    }
248    Ok(())
249}
250
251/// The person puts back what the change recorded by line `seq` replaced, or removes the entry it added: their own action,
252/// recorded as theirs. Refused when there is nothing to put back (past its 7 days).
253pub fn undo(store: &Store, seq: i64) -> Result<(), String> {
254    let row = store.vault_activity_get(seq).map_err(|e| e.to_string())?.filter(|r| r.actor_kind == "agent").ok_or("no such change by an agent")?;
255    let rows = store.vault_activity_agent_changes(now_ms() - LOOK_BACK_MS, &ACTIONS, Some(&row.entry_id), true, -1).map_err(|e| e.to_string())?;
256    let change = change_of(store, &rows, &row, false).ok_or("that change is not there any more")?;
257    let entry = store.vault_get(&change.entry_id).map_err(|e| e.to_string())?.ok_or("that entry is gone")?;
258    match change.undo.as_str() {
259        "remove" => super::delete(store, &entry.id)?,
260        "restore value" => {
261            let version = earlier_value(store, &entry, &row, &rows).ok_or("the earlier value is past its 7 days")?;
262            versions::restore(store, &entry.id, version)?;
263        }
264        "restore details" => restore_details(store, &entry, &row, &rows)?,
265        _ => return Err("there is nothing to put back for that change: the earlier version is past its 7 days".into()),
266    }
267    store.vault_change_seen(seq).map_err(|e| e.to_string())?;
268    trust_when_none_left(store, &change.entry_id)
269}
270
271/// Puts back only what the agent's change touched (the names in its line's target), so a later edit of something else by the
272/// person is kept, and drops the kept row it read so the same change cannot be undone twice.
273fn restore_details(store: &Store, entry: &VaultRow, row: &VaultActivityRow, rows: &[VaultActivityRow]) -> Result<(), String> {
274    let kept = earlier_details(store, entry, row, rows).ok_or("the earlier details are past their 7 days")?;
275    let earlier: BTreeMap<String, String> = serde_json::from_str(&kept.fields).unwrap_or_default();
276    let mut fields = super::signins::fields_of(entry);
277    let (mut label, mut tags) = (entry.label.clone(), entry.tags.clone());
278    let mut put_back = |name: &str| {
279        match earlier.get(name) {
280            Some(v) => fields.insert(name.to_string(), v.clone()),
281            None => fields.remove(name),
282        };
283    };
284    for part in row.target.split(", ") {
285        match part {
286            "label" => label = kept.label.clone(),
287            "tags" => tags = kept.tags.clone(),
288            "no expiry date" => put_back(expiry::FIELD),
289            p if p.starts_with("expires ") => put_back(expiry::FIELD),
290            p => {
291                if let Some(name) = p.strip_prefix("field ") {
292                    put_back(name);
293                }
294            }
295        }
296    }
297    let now = DetailsKept {
298        entry_id: entry.id.clone(),
299        entry_created_at: entry.created_at,
300        label: entry.label.clone(),
301        fields: entry.fields.clone(),
302        tags: entry.tags.clone(),
303        changed_at: now_ms(),
304        changed_by: PERSON.to_string(),
305        what: RESTORED_DETAILS.to_string(),
306    };
307    let fields_json = serde_json::to_string(&fields).map_err(|e| e.to_string())?;
308    let changed = VaultRow { label: label.clone(), fields: fields_json, tags, updated_at: now_ms().max(entry.updated_at + 1), ..entry.clone() };
309    if !store.vault_update_details_kept(&changed, &entry.sealed, &entry.fields, &now, None).map_err(|e| e.to_string())? {
310        return Err(format!("{} changed while this was being put back: nothing was changed", entry.label));
311    }
312    store.vault_details_kept_delete(&kept).map_err(|e| e.to_string())?;
313    record_line(store, Line { entry_id: &entry.id, label: &label, actor: PERSON, action: RESTORED_DETAILS, target: &row.target, outcome: "done", reason: "" });
314    Ok(())
315}