Skip to main content

agentmux_srv_core/backend/vault/
sync_links.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An entry's link ids on several machines. A link id is the opaque name a deep link gives a Vault entry
5//! (`agentmux://vault/entry/<link id>`): it says nothing about the entry and each machine gives one on first use. A link
6//! made on one machine of a shared Vault has to open the entry on the others, so the ids travel in the entry's sealed body.
7//!
8//! The build guarantees:
9//! - When two machines each gave the same entry an id before they first synced, the entry keeps both: one is its own id,
10//!   the other an alias, and a link made with either opens the entry on both machines.
11//! - An id is never reassigned: one that names another entry here, or that named an entry that was removed, is not taken
12//!   for this one.
13//! - The set is small and bounded ([`MAX_LINKS`]) and the same on every machine whatever order the records arrive in.
14//! - A machine keeps the id it gave an entry as that entry's own: it never changes under a link it showed.
15//!
16//! Pure functions over ids: the store tells which entry owns an id and which ids were retired through [`LinkOwners`].
17
18/// The most ids an entry keeps, its own and its aliases together.
19pub const MAX_LINKS: usize = 4;
20
21/// The prefix of every link id.
22const PREFIX: &str = "e_";
23
24/// Whether `s` has the shape of a link id: the prefix and 16 lowercase letters and digits. Anything else in a received
25/// body is dropped.
26pub fn is_link_id(s: &str) -> bool {
27    s.strip_prefix(PREFIX).is_some_and(|rest| rest.len() == 16 && rest.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
28}
29
30/// The link ids of one entry on this machine.
31#[derive(Debug, Clone, PartialEq, Eq, Default)]
32pub struct Links {
33    /// The id this machine gave the entry, or took from another machine if it had none. It is the one the pane shows.
34    pub primary: Option<String>,
35    /// The others, in order, none equal to the primary.
36    pub aliases: Vec<String>,
37}
38
39impl Links {
40    /// Every id: the entry's own first, then the aliases. This is what the entry's sync body carries.
41    pub fn ids(&self) -> Vec<String> {
42        self.primary.iter().chain(self.aliases.iter()).cloned().collect()
43    }
44
45    pub fn opens(&self, id: &str) -> bool {
46        self.primary.as_deref() == Some(id) || self.aliases.iter().any(|a| a == id)
47    }
48}
49
50/// What the store knows of link ids, besides this entry's own.
51pub trait LinkOwners {
52    /// The entry that holds `id` here now, if any.
53    fn owner_of(&self, id: &str) -> Option<String>;
54    /// Whether `id` once named an entry that has been removed. A removed entry's ids are kept for good for this.
55    fn retired(&self, id: &str) -> bool;
56}
57
58/// The ids of `entry_id` after a record for it arrived carrying `incoming`: what this machine had, plus the ids it did not
59/// have, except those it must not take. An id held by another entry here, or retired, is refused; so is anything that
60/// does not have the shape of an id. The result does not depend on the order records arrive in: the aliases are kept in
61/// sorted order and cut to the bound.
62pub fn settle(owners: &dyn LinkOwners, entry_id: &str, local: &Links, incoming: &[String]) -> Links {
63    let had = local.ids();
64    let mut taken: Vec<String> = Vec::new();
65    for id in incoming {
66        if !is_link_id(id) || had.contains(id) || taken.contains(id) {
67            continue;
68        }
69        let held_elsewhere = owners.owner_of(id).is_some_and(|owner| owner != entry_id);
70        if held_elsewhere || owners.retired(id) {
71            continue;
72        }
73        taken.push(id.clone());
74    }
75    // An entry with no id of its own yet takes the first one it was sent, the sender's own.
76    let primary = local.primary.clone().or_else(|| (!taken.is_empty()).then(|| taken.remove(0)));
77    let mut aliases: Vec<String> = local.aliases.iter().chain(taken.iter()).filter(|a| Some(*a) != primary.as_ref() && is_link_id(a)).cloned().collect();
78    aliases.sort();
79    aliases.dedup();
80    aliases.truncate(MAX_LINKS.saturating_sub(usize::from(primary.is_some())));
81    Links { primary, aliases }
82}
83
84#[cfg(test)]
85#[path = "sync_links_tests.rs"]
86mod tests;