Skip to main content

agentmux_srv_core/backend/vault/
proposals.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's request to change where a login is offered, on a login it did not make
5//! (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md R8).
6//!
7//! The call returns at once and changes nothing: the login keeps its site, realm and proxy in every way, so the person's own
8//! sign-ins at the old place keep working. The request waits 7 days as a record, one per entry and field, a newer one
9//! replacing the older. The person accepts it (it applies only if the entry is as it was when proposed) or dismisses it.
10//! Nothing here asks anyone and nothing here holds a value.
11
12use std::collections::BTreeMap;
13
14use agentmux_common::time::now_ms;
15
16use super::{history, kinds, record_line, signins, validate, Line, Parts, PERSON};
17use crate::backend::storage::store::Store;
18use crate::backend::storage::vault_changes::{DetailsKept, Proposal};
19
20/// How long a proposal waits.
21pub const KEEP_MS: i64 = 7 * 24 * 60 * 60 * 1000;
22/// What the person is told when the proposal they were shown has been replaced by another.
23pub const REPLACED: &str = "the agent changed its proposal since this was shown: look at the new one";
24/// The Activity action of an agent's proposal.
25pub const PROPOSED: &str = "proposed a change";
26/// The Activity action of the person accepting one.
27pub const ACCEPTED: &str = "accepted a proposed change";
28/// The Activity action of the person dismissing one.
29pub const DISMISSED: &str = "dismissed a proposed change";
30
31/// The fields of a login that say where it is offered and that an agent may propose a change of. `profile` is not among
32/// them: a login usable in an agent's browser is a share, and a share asks.
33pub const FIELDS: [&str; 3] = [signins::SITE, signins::REALM, signins::PROXY];
34
35/// Records that `agent` asks for `field` of the login `id` to become `value` (empty: removed), with its reason, and writes
36/// the line that says so. The login is unchanged.
37pub fn propose(store: &Store, id: &str, field: &str, value: &str, agent: &str, reason: &str) -> Result<(), String> {
38    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
39    let proposal = Proposal {
40        entry_id: row.id.clone(),
41        field: field.to_string(),
42        entry_created_at: row.created_at,
43        entry_updated_at: row.updated_at,
44        value: value.trim().to_string(),
45        agent: agent.to_string(),
46        reason: reason.to_string(),
47        at: now_ms(),
48    };
49    store.vault_proposal_put(&proposal).map_err(|e| e.to_string())?;
50    let target = format!("field {field}");
51    record_line(store, Line { entry_id: &row.id, label: &row.label, actor: agent, action: PROPOSED, target: &target, outcome: "waiting for the person", reason });
52    Ok(())
53}
54
55/// The proposals still waiting, oldest first; older ones are dropped first.
56pub fn list(store: &Store) -> Result<Vec<Proposal>, String> {
57    if let Err(e) = store.vault_proposals_prune(now_ms() - KEEP_MS) {
58        tracing::warn!(error = %e, "vault: couldn't delete old proposals");
59    }
60    store.vault_proposals(None, now_ms() - KEEP_MS).map_err(|e| e.to_string())
61}
62
63fn waiting(store: &Store, id: &str, field: &str) -> Result<Proposal, String> {
64    let all = store.vault_proposals(Some(id), now_ms() - KEEP_MS).map_err(|e| e.to_string())?;
65    all.into_iter().find(|p| p.field == field).ok_or_else(|| format!("no proposal for {field} of {id}: it was accepted, dismissed or is older than 7 days"))
66}
67
68/// The person accepts the proposal for `field` of `id`: it is applied if the entry is as it was when proposed, with the
69/// details it replaces kept 7 days, and a line records it. An entry changed since is refused, saying so.
70pub fn accept(store: &Store, id: &str, field: &str) -> Result<(), String> {
71    accept_shown(store, id, field, None)
72}
73
74/// [`accept`] of the proposal the person was shown, made at `shown_at`: refused when an agent has replaced it since, so what
75/// is applied is what they saw. `None` accepts whichever is waiting.
76pub fn accept_shown(store: &Store, id: &str, field: &str, shown_at: Option<i64>) -> Result<(), String> {
77    let p = waiting(store, id, field)?;
78    if shown_at.is_some_and(|at| at != p.at) {
79        return Err(REPLACED.into());
80    }
81    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
82    if row.created_at != p.entry_created_at || row.updated_at != p.entry_updated_at {
83        return Err("the login changed after this was proposed: dismiss it, and the agent can propose again".into());
84    }
85    let mut fields: BTreeMap<String, String> = signins::fields_of(&row);
86    match p.value.as_str() {
87        "" => fields.remove(field),
88        v => fields.insert(field.to_string(), v.to_string()),
89    };
90    signins::normalize_site(&row.kind, &mut fields);
91    // The same checks an edit passes: a value that was never valid for the field is not written.
92    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
93    validate(kind, &row.label, &fields, &signins::tags_of(&row), &Parts::default())?;
94    let was = (row.sealed.clone(), row.fields.clone());
95    let kept = DetailsKept {
96        entry_id: row.id.clone(),
97        entry_created_at: row.created_at,
98        label: row.label.clone(),
99        fields: row.fields.clone(),
100        tags: row.tags.clone(),
101        changed_at: now_ms(),
102        changed_by: PERSON.to_string(),
103        what: format!("field {field}"),
104    };
105    let new = crate::backend::storage::vault::VaultRow { fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?, updated_at: now_ms().max(row.updated_at + 1), ..row.clone() };
106    if !store.vault_update_details_kept(&new, &was.0, &was.1, &kept, None).map_err(|e| e.to_string())? {
107        return Err("the login changed while this was being applied, so nothing was changed: look at it again".into());
108    }
109    let _ = store.vault_proposal_delete(id, field);
110    // The old place's grants name the old origin and stop matching by themselves; a new place starts with none.
111    let target = format!("field {field}");
112    let reason = format!("{} asked: {}", history::actor_label(&p.agent), p.reason);
113    record_line(store, Line { entry_id: &row.id, label: &row.label, actor: PERSON, action: ACCEPTED, target: &target, outcome: "done", reason: &reason });
114    Ok(())
115}
116
117/// The person dismisses the proposal for `field` of `id`. True when there was one.
118pub fn dismiss(store: &Store, id: &str, field: &str) -> Result<bool, String> {
119    dismiss_shown(store, id, field, None)
120}
121
122/// [`dismiss`] of the proposal the person was shown (see [`accept_shown`]): a replacement is left waiting to be looked at.
123pub fn dismiss_shown(store: &Store, id: &str, field: &str, shown_at: Option<i64>) -> Result<bool, String> {
124    let p = match waiting(store, id, field) {
125        Ok(p) => p,
126        Err(_) => return Ok(false),
127    };
128    if shown_at.is_some_and(|at| at != p.at) {
129        return Err(REPLACED.into());
130    }
131    let row = store.vault_get(id).map_err(|e| e.to_string())?;
132    let gone = store.vault_proposal_delete(id, field).map_err(|e| e.to_string())?;
133    if let (true, Some(row)) = (gone, row) {
134        let target = format!("field {field}");
135        record_line(store, Line { entry_id: &row.id, label: &row.label, actor: PERSON, action: DISMISSED, target: &target, outcome: "done", reason: &p.reason });
136    }
137    Ok(gone)
138}