1use 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
23const LOOK_BACK_MS: i64 = 30 * 24 * 60 * 60 * 1000;
25const MOST: i64 = 300;
27const NEAR_MS: i64 = 5_000;
29pub const RESTORED_DETAILS: &str = "restored earlier details";
31
32const ACTIONS: [&str; 5] = ["generated", "imported", "captured", inspect::CHANGED_DETAILS, proposals::PROPOSED];
34
35#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
37#[ts(export, export_to = "../../../frontend/types/rpc/")]
38pub struct ProposalInfo {
39 pub field: String,
40 #[ts(type = "number")]
42 pub at: i64,
43 pub value: String,
44 pub current: String,
45}
46
47#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
49#[ts(export, export_to = "../../../frontend/types/rpc/")]
50pub struct AgentChange {
51 #[ts(type = "number")]
53 pub seq: i64,
54 #[ts(type = "number")]
55 pub at: i64,
56 pub agent: String,
58 pub entry_id: String,
59 pub entry_label: String,
60 pub kind: String,
62 pub action: String,
64 pub target: String,
65 pub reason: String,
67 pub seen: bool,
68 pub undo: String,
70 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
85fn 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
90fn 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
104fn 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
114fn 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
124fn 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 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
180pub 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
204fn 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
214fn 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
223pub 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
232pub 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
251pub 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
271fn 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}