Skip to main content

agentmux_srv_core/backend/vault/
sync_adapter.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault's merge rule as the sync layer's adapter (`user_sync::adapter`): the layer hands over the record's current
5//! header and the incoming one, and this answers `Applied`, `KeptLocal` or `Conflict { current }` by the rules of
6//! [`super::sync_merge`]. It sees headers only, never a body: which side is current is decided by versions, what a
7//! change replaced (`Header::base`, signed by the origin and sealed into the body) and whether the entry is being rotated
8//! here. The tags of a conflicted entry, a union of both sides, are put together afterwards from the two bodies.
9//!
10//! The record's other versions are read from the layer's own log, so a late record that this machine already has an
11//! ancestor of is not taken for a change made apart.
12
13use rusqlite::{params, Connection};
14
15use super::sync_activity;
16use super::sync_grant;
17use super::sync_merge::{self, Change, Decision, Held, Side as Chose};
18use super::sync_seal::Version;
19use crate::backend::user_sync::adapter::{Adapter, Merge, Side};
20use crate::backend::user_sync::record::Header;
21
22/// Whether an entry is being rotated on this machine: a new value is waiting to be confirmed, and no sync may overwrite
23/// it (spec 6.3). The Vault's store answers this; the layer does not know.
24pub trait Rotations {
25    fn rotating(&self, record: &str) -> bool;
26}
27
28/// What a record of a Vault's collection is, by its id. One collection holds all three, and each has its own rule.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Kind {
31    /// An entry (and anything whose id is not one of the other two): keep-both on a change made apart.
32    Entry,
33    /// An activity line, `a.<machine>.<seq>` (`sync_activity`): never changes, so never conflicts.
34    Activity,
35    /// A site grant, `g-<hex>` (`sync_grant`): the later version, a grant or its revoking, is the one to follow.
36    Grant,
37}
38
39impl Kind {
40    pub fn of(record: &str) -> Kind {
41        if sync_activity::parse_record_id(record).is_some() {
42            Kind::Activity
43        } else if sync_grant::is_record_id(record) {
44            Kind::Grant
45        } else {
46            Kind::Entry
47        }
48    }
49}
50
51/// The Vault's adapter, over the layer's log (`conn`) and the Vault's rotations.
52pub struct VaultAdapter<'a> {
53    pub conn: &'a Connection,
54    pub rotations: &'a dyn Rotations,
55}
56
57/// Every version of `record` this machine knows, from any origin: the ones its log holds, and the ones those say they
58/// replaced (the signed `base` of each). A version only known as a base has not arrived yet, but it is known to be
59/// superseded, so it is not taken for a change made apart when it does. The record being decided, `(origin, seq)`, is
60/// not counted: the layer has already written it into the log.
61fn versions_held(conn: &Connection, incoming: &Header) -> rusqlite::Result<Vec<Version>> {
62    let mut stmt = conn.prepare(
63        "SELECT wall_ms, counter, machine FROM db_sync_log WHERE collection = ?1 AND record = ?2 AND NOT (origin = ?3 AND seq = ?4) \
64         UNION SELECT base_wall, base_counter, base_machine FROM db_sync_log WHERE collection = ?1 AND record = ?2 AND NOT (origin = ?3 AND seq = ?4) AND base_wall IS NOT NULL",
65    )?;
66    let rows = stmt.query_map(params![incoming.collection, incoming.record, incoming.origin, incoming.seq as i64], |r| {
67        Ok(Version { wall_ms: r.get(0)?, counter: r.get(1)?, machine: r.get(2)? })
68    })?;
69    rows.collect()
70}
71
72impl VaultAdapter<'_> {
73    /// The whole answer for `incoming`, with what is kept and why (the layer is told only `Merge`; taking the record into
74    /// the store needs the rest, see `sync_take`).
75    pub fn decide(&self, local: Option<&Header>, incoming: &Header) -> Decision {
76        match Kind::of(&incoming.record) {
77            Kind::Activity => return sync_activity::merge(local.is_some()),
78            Kind::Grant => {
79                let had = versions_held(self.conn, incoming).unwrap_or_default();
80                return sync_grant::merge(local.map(|l| &l.version), &had, &incoming.version);
81            }
82            Kind::Entry => {}
83        }
84        let held = local.map(|l| {
85            // The current version first, then the others it had. If the log can't be read, only the current one is known,
86            // which can only turn a late ancestor into a kept version, never lose a change.
87            let mut versions = vec![l.version.clone()];
88            for v in versions_held(self.conn, incoming).unwrap_or_default() {
89                if !versions.contains(&v) {
90                    versions.push(v);
91                }
92            }
93            Held { versions, deleted: l.tombstone, pending_rotation: self.rotations.rotating(&l.record), tags: Vec::new() }
94        });
95        let change = Change { version: incoming.version.clone(), base: incoming.base.clone(), tags: (!incoming.tombstone).then(Vec::new) };
96        sync_merge::merge(held.as_ref(), &change)
97    }
98}
99
100/// What the layer is told of a [`Decision`].
101pub fn merge_of(decision: &Decision) -> Merge {
102    match decision {
103        Decision::Applied => Merge::Applied,
104        Decision::KeptLocal => Merge::KeptLocal,
105        Decision::Conflict { current, .. } => Merge::Conflict { current: if *current == Chose::Local { Side::Local } else { Side::Incoming } },
106    }
107}
108
109impl Adapter for VaultAdapter<'_> {
110    fn merge(&self, local: Option<&Header>, incoming: &Header) -> Merge {
111        merge_of(&self.decide(local, incoming))
112    }
113}
114
115#[cfg(test)]
116#[path = "sync_adapter_tests.rs"]
117mod tests;