Skip to main content

agentmux_srv_core/backend/user_sync/
members.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A collection's members (SPEC_USER_DATA_SYNC_LAYER ยง3.1): one signed, hash-chained log of membership changes.
5//! The first entry founds the collection and is signed by the founder; every later entry is signed by a machine that
6//! is a member at the point it extends. A client takes an entry only if it verifies against the signer's key as the
7//! chain lists it and it extends the chain it holds, so a change that no member signed is refused, wherever it came
8//! from.
9//!
10//! A member is a machine (named by the id its signing key makes, with a box key that key signed, for sealing the
11//! collection key to it) or a recovery subject (a box key only: it never signs, never writes a record and is never
12//! pinned, but a new epoch's key is sealed to it too). A member's label is inside the seal: this module only carries
13//! the sealed bytes.
14
15use std::collections::BTreeMap;
16
17use agentmux_common::jekt_sign::{ed25519_sign_b64, ed25519_verify_b64, wan_instance_id};
18use serde::{Deserialize, Serialize};
19use sha2::{Digest, Sha256};
20
21use super::log::Pins;
22
23const DOMAIN: &str = "agentmux-sync-member-v1";
24const BOX_DOMAIN: &str = "agentmux-sync-member-box-v1";
25const SEP: char = '\u{1f}';
26
27/// What kind of subject a member is.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29pub enum Kind {
30    Machine,
31    Recovery,
32}
33
34/// How a machine joins: a machine proven by the LAN trust and the account joins at once (`auto_proven`), or a
35/// person confirms on an existing member (`approve`).
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37pub enum Policy {
38    AutoProven,
39    Approve,
40}
41
42/// A member of a collection. Keys are lower-case hex.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct Subject {
45    pub kind: Kind,
46    /// A machine's origin id (made from its signing key); a recovery subject's fingerprint.
47    pub id: String,
48    /// A machine's Ed25519 signing key; none for a recovery subject.
49    pub signing_key: Option<String>,
50    /// The X25519 key the collection key is sealed to.
51    pub box_key: String,
52    /// A machine's signing key over its box key; none for a recovery subject.
53    pub box_sig: Option<String>,
54    /// The member's label (a host name), sealed with the collection key: opaque here.
55    pub sealed_label: String,
56}
57
58fn hex(bytes: &[u8]) -> String {
59    bytes.iter().map(|b| format!("{b:02x}")).collect()
60}
61
62pub(super) fn unhex32(s: &str) -> Option<[u8; 32]> {
63    if s.len() != 64 || !s.is_ascii() {
64        return None;
65    }
66    let mut out = [0u8; 32];
67    for (i, b) in out.iter_mut().enumerate() {
68        *b = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?;
69    }
70    Some(out)
71}
72
73/// A recovery subject's id: made from its box key, so it cannot take another member's id.
74fn recovery_id(box_key: &[u8; 32]) -> String {
75    format!("recovery-{}", hex(&Sha256::digest(box_key)[..8]))
76}
77
78fn box_material(id: &str, box_key: &str) -> String {
79    [BOX_DOMAIN, id, box_key].join(&SEP.to_string())
80}
81
82impl Subject {
83    /// A machine subject for the signing key whose seed is `private`, offering `box_key` (32 bytes) to seal to.
84    pub fn machine(private: &[u8; 32], box_key: &[u8; 32], sealed_label: &str) -> Option<Subject> {
85        let public = ed25519_dalek::SigningKey::from_bytes(private).verifying_key().to_bytes();
86        let id = wan_instance_id(&public);
87        let box_key = hex(box_key);
88        let box_sig = ed25519_sign_b64(private, &box_material(&id, &box_key))?;
89        Some(Subject { kind: Kind::Machine, id, signing_key: Some(hex(&public)), box_key, box_sig: Some(box_sig), sealed_label: sealed_label.to_string() })
90    }
91
92    /// A recovery subject: a box key and nothing else.
93    pub fn recovery(box_key: &[u8; 32], sealed_label: &str) -> Subject {
94        Subject { kind: Kind::Recovery, id: recovery_id(box_key), signing_key: None, box_key: hex(box_key), box_sig: None, sealed_label: sealed_label.to_string() }
95    }
96
97    /// A machine's signing key, if this is a machine whose fields are well formed.
98    pub fn public(&self) -> Option<[u8; 32]> {
99        (self.kind == Kind::Machine).then_some(())?;
100        unhex32(self.signing_key.as_deref()?)
101    }
102
103    /// Whether the subject is what it says: a machine's id is made from its signing key and its box key is signed by
104    /// that key; a recovery subject has neither.
105    pub fn valid(&self) -> bool {
106        if unhex32(&self.box_key).is_none() || self.id.is_empty() || self.id.contains(SEP) || self.sealed_label.contains(SEP) {
107            return false;
108        }
109        match self.kind {
110            Kind::Machine => match (self.public(), &self.box_sig) {
111                (Some(public), Some(sig)) => wan_instance_id(&public) == self.id && ed25519_verify_b64(&public, &box_material(&self.id, &self.box_key), sig),
112                _ => false,
113            },
114            Kind::Recovery => {
115                let own = unhex32(&self.box_key).map(|k| recovery_id(&k));
116                self.signing_key.is_none() && self.box_sig.is_none() && own.as_deref() == Some(self.id.as_str())
117            }
118        }
119    }
120
121    fn text(&self) -> String {
122        let kind = if self.kind == Kind::Machine { "machine" } else { "recovery" };
123        [kind, &self.id, self.signing_key.as_deref().unwrap_or("-"), &self.box_key, self.box_sig.as_deref().unwrap_or("-"), &self.sealed_label]
124            .join(&SEP.to_string())
125    }
126}
127
128/// One change to the member list.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub enum Change {
131    /// The first entry: the founder, and how machines join.
132    Found { member: Subject, policy: Policy },
133    Add { member: Subject },
134    /// A member leaves or is removed: the collection moves to the next key epoch. `ended` is, for each member that
135    /// remains, the last sequence it wrote at the epoch being left (the `ended` of `log::set_epoch`).
136    Remove { id: String, ended: BTreeMap<String, u64> },
137    /// Changes how machines join; signed like any change, so no peer can quietly relax `approve`.
138    SetPolicy { policy: Policy },
139}
140
141impl Change {
142    fn text(&self) -> String {
143        let policy = |p: &Policy| if *p == Policy::AutoProven { "auto_proven" } else { "approve" };
144        match self {
145            Change::Found { member, policy: p } => ["found".to_string(), member.text(), policy(p).to_string()].join(&SEP.to_string()),
146            Change::Add { member } => ["add".to_string(), member.text()].join(&SEP.to_string()),
147            Change::Remove { id, ended } => {
148                let ended: Vec<String> = ended.iter().map(|(k, v)| format!("{k}={v}")).collect();
149                ["remove", id, &ended.join(",")].join(&SEP.to_string())
150            }
151            Change::SetPolicy { policy: p } => ["policy", policy(p)].join(&SEP.to_string()),
152        }
153    }
154}
155
156/// A signed entry of the chain.
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct Entry {
159    pub collection: String,
160    /// 1 for the founding entry, then each entry one more.
161    pub n: u64,
162    /// The hash of the entry before it; none for the first.
163    pub prev: Option<String>,
164    pub change: Change,
165    /// The id of the machine that signed.
166    pub signer: String,
167    pub sig: String,
168}
169
170impl Entry {
171    fn material(&self) -> String {
172        [DOMAIN, &self.collection, &self.n.to_string(), self.prev.as_deref().unwrap_or("-"), &self.change.text(), &self.signer]
173            .join(&SEP.to_string())
174    }
175
176    /// The hash the next entry names: over everything, signature included.
177    pub fn hash(&self) -> String {
178        hex(&Sha256::digest(format!("{}{SEP}{}", self.material(), self.sig).as_bytes()))
179    }
180
181    /// An entry signed with the seed of the signing machine's key.
182    pub fn sign(private: &[u8; 32], collection: &str, n: u64, prev: Option<String>, change: Change, signer: &str) -> Option<Entry> {
183        let mut entry = Entry { collection: collection.to_string(), n, prev, change, signer: signer.to_string(), sig: String::new() };
184        entry.sig = ed25519_sign_b64(private, &entry.material())?;
185        Some(entry)
186    }
187}
188
189/// Why an entry was refused.
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191pub enum MemberError {
192    /// Not for this collection, or not the next entry, or it does not name the head it extends.
193    DoesNotExtend,
194    /// The first entry must found the collection, and only the first.
195    Founding,
196    /// The signer is not a machine that is a member at this point.
197    NotAMember,
198    /// The signature does not verify against the signer's key as the chain lists it.
199    BadSignature,
200    /// A subject whose id, keys or signature are not what they say.
201    BadSubject,
202    AlreadyMember,
203    /// A removal of someone who is not a member, or of the last machine, or an `ended` naming a non-member.
204    BadRemoval,
205    /// An entry on a branch that settled against the chain (beside the head, or beside an earlier entry the chain has gone
206    /// on from), or a second founding entry.
207    ForkLost,
208}
209
210/// The members, the epoch and the policy as a chain leaves them.
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct State {
213    pub collection: String,
214    pub members: BTreeMap<String, Subject>,
215    pub epoch: u32,
216    pub policy: Policy,
217    pub n: u64,
218    pub head: Option<String>,
219    /// For each member, the position of the entry that made it one: the founder is 1, so an earlier member ranks
220    /// before a later one (this is what settles two members removing each other at once).
221    pub joined: BTreeMap<String, u64>,
222}
223
224impl State {
225    fn empty(collection: &str) -> State {
226        State { collection: collection.to_string(), members: BTreeMap::new(), epoch: 0, policy: Policy::Approve, n: 0, head: None, joined: BTreeMap::new() }
227    }
228
229    /// The signing keys of the machines, for `log::apply_remote`: a recovery subject is never in it.
230    pub fn pins(&self) -> Pins {
231        self.members.values().filter_map(|m| Some((m.id.clone(), m.public()?))).collect()
232    }
233
234    /// Whether a machine that is a member here is one the caller itself trusts (its own LAN pin and account check):
235    /// the anchor of a join. A recovery subject never is.
236    pub fn anchored(&self, trusted: &dyn Fn(&str) -> bool) -> bool {
237        self.members.values().any(|m| m.kind == Kind::Machine && trusted(&m.id))
238    }
239
240    fn machines(&self) -> usize {
241        self.members.values().filter(|m| m.kind == Kind::Machine).count()
242    }
243
244    /// Checks `entry` against this state and, if it holds, takes it in.
245    fn apply(&mut self, entry: &Entry) -> Result<(), MemberError> {
246        if entry.collection != self.collection || entry.n != self.n + 1 || entry.prev != self.head {
247            return Err(MemberError::DoesNotExtend);
248        }
249        if (entry.n == 1) != matches!(entry.change, Change::Found { .. }) {
250            return Err(MemberError::Founding);
251        }
252        let signer_key = match &entry.change {
253            Change::Found { member, .. } => {
254                if !member.valid() || member.kind != Kind::Machine || member.id != entry.signer {
255                    return Err(MemberError::BadSubject);
256                }
257                member.public()
258            }
259            _ => self.members.get(&entry.signer).filter(|m| m.kind == Kind::Machine).and_then(Subject::public),
260        };
261        let key = signer_key.ok_or(MemberError::NotAMember)?;
262        if !ed25519_verify_b64(&key, &entry.material(), &entry.sig) {
263            return Err(MemberError::BadSignature);
264        }
265        match &entry.change {
266            Change::Found { member, policy } => {
267                self.members.insert(member.id.clone(), member.clone());
268                self.joined.insert(member.id.clone(), entry.n);
269                self.policy = *policy;
270            }
271            Change::Add { member } => {
272                if !member.valid() {
273                    return Err(MemberError::BadSubject);
274                }
275                if self.members.contains_key(&member.id) {
276                    return Err(MemberError::AlreadyMember);
277                }
278                self.members.insert(member.id.clone(), member.clone());
279                self.joined.insert(member.id.clone(), entry.n);
280            }
281            Change::Remove { id, ended } => {
282                let removed = self.members.get(id).ok_or(MemberError::BadRemoval)?;
283                if removed.kind == Kind::Machine && self.machines() == 1 {
284                    return Err(MemberError::BadRemoval);
285                }
286                // `ended` names every machine that remains, and only those: a machine left out would have its
287                // old-epoch records refused for good.
288                let remaining: Vec<&String> = self.members.values().filter(|m| m.kind == Kind::Machine && m.id != *id).map(|m| &m.id).collect();
289                if ended.len() != remaining.len() || remaining.iter().any(|m| !ended.contains_key(*m)) {
290                    return Err(MemberError::BadRemoval);
291                }
292                self.members.remove(id);
293                self.joined.remove(id);
294                self.epoch += 1;
295            }
296            Change::SetPolicy { policy } => self.policy = *policy,
297        }
298        self.n = entry.n;
299        self.head = Some(entry.hash());
300        Ok(())
301    }
302}
303
304/// What taking an entry did.
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
306pub enum Taken {
307    /// It extended the chain.
308    Extended,
309    /// Already held.
310    Duplicate,
311    /// It was on a branch that settled in its favour, at the head or at an earlier place the chain had gone on from: the
312    /// entries it displaced, from the first of them to the old head, are returned. The chain may now be shorter or longer.
313    Replaced(Vec<Entry>),
314}
315
316/// The most entries kept that are not in the chain (branches that lost), so a member's flood of them has a limit. The oldest
317/// positions are dropped first.
318pub const MAX_SIDE: usize = 64;
319
320/// The entries a machine holds for one collection: the chain, and the other entries it has seen that are valid on their own
321/// branch (a fork, at the head or further back, and what was signed on top of the branch that lost), so the winner at every
322/// position is a function of everything seen and not of the order it arrived in.
323#[derive(Debug, Clone, PartialEq, Eq, Default)]
324pub struct Chain {
325    pub entries: Vec<Entry>,
326    /// The entries beside the head: at its position, naming the head's predecessor.
327    contested: Vec<Entry>,
328    /// The other entries off the chain, by position then hash.
329    older: Vec<Entry>,
330}
331
332/// Which of the entries at one position wins. An entry signed by a member another entry removes loses to it, so a
333/// member cannot undo its own removal by racing it; if every entry is removed by another, they all stand. Among
334/// those that stand the earliest member wins (a member cannot change when it joined), then the lower hash.
335fn settle(base: &State, set: &[Entry]) -> Entry {
336    let removed_by_other = |e: &Entry| set.iter().any(|o| o != e && matches!(&o.change, Change::Remove { id, .. } if *id == e.signer));
337    let standing: Vec<&Entry> = set.iter().filter(|e| !removed_by_other(e)).collect();
338    let pool: Vec<&Entry> = if standing.is_empty() { set.iter().collect() } else { standing };
339    let rank = |e: &&Entry| (base.joined.get(&e.signer).copied().unwrap_or(u64::MAX), e.hash());
340    pool.into_iter().min_by_key(rank).cloned().unwrap_or_else(|| set[0].clone())
341}
342
343impl Chain {
344    /// The state after all of `entries`, or why the chain is not sound.
345    fn replay(collection: &str, entries: &[Entry]) -> Result<State, MemberError> {
346        let mut state = State::empty(collection);
347        for e in entries {
348            state.apply(e)?;
349        }
350        Ok(state)
351    }
352
353    /// The entries beside the head that this machine has seen and not outgrown.
354    pub fn forks(&self) -> &[Entry] {
355        &self.contested
356    }
357
358    /// Every entry held that is not in the chain: those beside the head, then the older ones.
359    pub fn side(&self) -> impl Iterator<Item = &Entry> {
360        self.contested.iter().chain(self.older.iter())
361    }
362
363    /// A chain read back from the store: the entries are checked in order, and each other entry must be valid on its own
364    /// branch, every entry it follows being held.
365    pub fn restore(collection: &str, entries: Vec<Entry>, side: Vec<Entry>) -> Result<Chain, MemberError> {
366        Chain::replay(collection, &entries)?;
367        if !side.is_empty() && entries.len() < 2 {
368            // Something beside the founding entry, which is never replaced.
369            return Err(MemberError::ForkLost);
370        }
371        let held: Vec<&Entry> = entries.iter().chain(side.iter()).collect();
372        for (i, f) in side.iter().enumerate() {
373            if entries.contains(f) || side[..i].contains(f) {
374                return Err(MemberError::ForkLost);
375            }
376            Chain::before(collection, &held, f)?.apply(f)?;
377        }
378        let mut chain = Chain { entries, contested: Vec::new(), older: Vec::new() };
379        chain.keep(side);
380        Ok(chain)
381    }
382
383    /// A chain from entries received whole: every one is checked in order.
384    pub fn from_entries(collection: &str, entries: Vec<Entry>) -> Result<Chain, MemberError> {
385        Chain::replay(collection, &entries)?;
386        Ok(Chain { entries, contested: Vec::new(), older: Vec::new() })
387    }
388
389    /// The members, epoch and policy the chain leaves, or why the chain is not sound (a chain that was altered
390    /// after it was taken in is an error, not an empty collection).
391    pub fn state(&self, collection: &str) -> Result<State, MemberError> {
392        Chain::replay(collection, &self.entries)
393    }
394
395    /// Whether a removal is in doubt: entries beside the head are held that this machine has not outgrown, and one of
396    /// them, or the head, removes a member. The key epoch that removal makes is not settled, so nothing is sealed at it.
397    pub fn epoch_contested(&self) -> bool {
398        let removes = |e: &Entry| matches!(e.change, Change::Remove { .. });
399        !self.contested.is_empty() && (self.contested.iter().any(removes) || self.entries.last().is_some_and(removes))
400    }
401
402    /// The next entry, signed by `signer` (a machine of this chain) with its key's seed.
403    pub fn next(&self, private: &[u8; 32], collection: &str, signer: &str, change: Change) -> Option<Entry> {
404        let prev = self.entries.last().map(Entry::hash);
405        Entry::sign(private, collection, self.entries.len() as u64 + 1, prev, change, signer)
406    }
407
408    /// The state the entry applies on: the state after the entries it follows, found by the hashes each names among `held`.
409    /// It does not extend anything held when a link is missing.
410    fn before(collection: &str, held: &[&Entry], entry: &Entry) -> Result<State, MemberError> {
411        let by_hash: BTreeMap<String, &Entry> = held.iter().map(|h| (h.hash(), *h)).collect();
412        let mut path: Vec<&Entry> = Vec::new();
413        let mut at = entry;
414        while at.n > 1 {
415            let parent = at.prev.as_ref().and_then(|p| by_hash.get(p)).copied().filter(|h| h.n + 1 == at.n && h.collection == collection);
416            let parent = parent.ok_or(MemberError::DoesNotExtend)?;
417            path.push(parent);
418            at = parent;
419        }
420        if at.prev.is_some() || entry.collection != collection {
421            return Err(MemberError::DoesNotExtend);
422        }
423        let mut state = State::empty(collection);
424        for e in path.iter().rev() {
425            state.apply(e)?;
426        }
427        Ok(state)
428    }
429
430    /// The chain every machine that holds all of `seen` agrees on: from the founding entry, at each position the entries
431    /// that name the head and are valid on it are [`settle`]d. The founding entry already held is never replaced.
432    fn walk(collection: &str, seen: &[Entry], founder: Option<&Entry>) -> Vec<Entry> {
433        let mut state = State::empty(collection);
434        let mut chain: Vec<Entry> = Vec::new();
435        loop {
436            let at = state.clone();
437            // The entries that name the head and are valid on it, each with the state it leaves.
438            let next: Vec<(Entry, State)> = seen
439                .iter()
440                .filter(|e| e.n == at.n + 1 && e.prev == at.head)
441                .filter_map(|e| {
442                    let mut after = at.clone();
443                    after.apply(e).ok().map(|_| (e.clone(), after))
444                })
445                .collect();
446            let entries: Vec<Entry> = next.iter().map(|(e, _)| e.clone()).collect();
447            let winner = match founder {
448                Some(f) if at.n == 0 && entries.contains(f) => f.clone(),
449                _ if entries.is_empty() => return chain,
450                _ => settle(&at, &entries),
451            };
452            let Some((_, after)) = next.into_iter().find(|(e, _)| *e == winner) else { return chain };
453            state = after;
454            chain.push(winner);
455        }
456    }
457
458    /// Keeps the entries that are not in the chain: those beside the head apart, the older ones by position, no more than
459    /// [`MAX_SIDE`] and only those still joined to the chain through entries kept.
460    fn keep(&mut self, mut rest: Vec<Entry>) {
461        rest.sort_by_key(|e| (e.n, e.hash()));
462        rest.dedup();
463        let joined = |chain: &[Entry], rest: Vec<Entry>| -> Vec<Entry> {
464            let mut linked: Vec<String> = chain.iter().map(Entry::hash).collect();
465            let mut kept = Vec::new();
466            for e in rest {
467                if e.prev.as_ref().is_some_and(|p| linked.contains(p)) {
468                    linked.push(e.hash());
469                    kept.push(e);
470                }
471            }
472            kept
473        };
474        let mut kept = joined(&self.entries, rest);
475        if kept.len() > MAX_SIDE {
476            kept.drain(..kept.len() - MAX_SIDE);
477            // What followed an entry dropped no longer joins the chain.
478            kept = joined(&self.entries, kept);
479        }
480        let place = self.entries.len() as u64;
481        let before = self.entries.len().checked_sub(2).and_then(|i| self.entries.get(i)).map(Entry::hash);
482        let (mut beside, older): (Vec<Entry>, Vec<Entry>) = kept.into_iter().partition(|e| place > 1 && e.n == place && e.prev == before);
483        beside.sort_by_key(Entry::hash);
484        self.contested = beside;
485        self.older = older;
486    }
487
488    /// Takes in an entry from anywhere. It must verify on the entries it follows, which must be held. One that extends the
489    /// head extends the chain. One that follows an earlier entry (a fork at the head, or further back where the chain has
490    /// gone on) is held beside it, and the chain is settled again over everything held: the same on every machine that
491    /// sees it all. When the entry's branch wins, the entries of the branch it displaces are returned; what was signed on
492    /// top of the branch that lost stays off the chain, hash-linked to an entry no longer in it, until its branch wins.
493    /// The founding entry is never replaced: a second one is a different collection, and who founded this one is anchored
494    /// by the joiner's own trust (`State::anchored`).
495    pub fn take(&mut self, collection: &str, entry: Entry) -> Result<Taken, MemberError> {
496        if self.entries.contains(&entry) || self.contested.contains(&entry) || self.older.contains(&entry) {
497            return Ok(Taken::Duplicate);
498        }
499        if entry.collection != collection {
500            return Err(MemberError::DoesNotExtend);
501        }
502        if entry.n <= 1 {
503            if !self.entries.is_empty() {
504                return Err(MemberError::ForkLost);
505            }
506            State::empty(collection).apply(&entry)?;
507            self.entries.push(entry);
508            return Ok(Taken::Extended);
509        }
510        let mut seen: Vec<Entry> = self.entries.iter().chain(self.side()).cloned().collect();
511        {
512            let held: Vec<&Entry> = seen.iter().collect();
513            Chain::before(collection, &held, &entry)?.apply(&entry)?;
514        }
515        if self.entries.last().map(Entry::hash) == entry.prev && entry.n == self.entries.len() as u64 + 1 {
516            // The usual case: it goes on from the head, and nothing held can change what stands before it.
517            let rest: Vec<Entry> = self.side().cloned().collect();
518            self.entries.push(entry);
519            self.keep(rest);
520            return Ok(Taken::Extended);
521        }
522        seen.push(entry);
523        let now = Chain::walk(collection, &seen, self.entries.first());
524        let common = self.entries.iter().zip(&now).take_while(|(a, b)| a == b).count();
525        let displaced: Vec<Entry> = self.entries[common..].to_vec();
526        let extended = displaced.is_empty() && now.len() > self.entries.len();
527        let rest: Vec<Entry> = seen.into_iter().filter(|e| !now.contains(e)).collect();
528        self.entries = now;
529        self.keep(rest);
530        if extended {
531            Ok(Taken::Extended)
532        } else if displaced.is_empty() {
533            Err(MemberError::ForkLost)
534        } else {
535            Ok(Taken::Replaced(displaced))
536        }
537    }
538}