Skip to main content

link_cli/version_control/
mod.rs

1//! Optional version-control layer for the Rust link-cli.
2//!
3//! Mirrors the C# `VersionControlDecorator` in
4//! `csharp/Foundation.Data.Doublets.Cli.Library/VersionControlDecorator.cs`.
5//!
6//! Sits above the [`TransactionsDecorator`]
7//! and adds *time travel* ([`checkout`](VersionControlDecorator::checkout)),
8//! *branching* ([`branch`](VersionControlDecorator::branch),
9//! [`switch_branch`](VersionControlDecorator::switch_branch)), and
10//! *tagging* ([`tag`](VersionControlDecorator::tag)) over the transitions
11//! log. Optional — when not instantiated the underlying transactions
12//! decorator behaves identically (R17).
13
14use std::collections::{BTreeMap, HashMap, HashSet};
15use std::path::{Path, PathBuf};
16
17use anyhow::{bail, Result};
18
19use crate::link::Link;
20use crate::link_storage::ChangeObserver;
21use crate::named_type_links::NamedTypeLinks;
22use crate::named_types::NamedTypesDecorator;
23
24mod movement;
25#[cfg(test)]
26mod path_contract_tests;
27mod publication;
28use crate::transactions::{GenericTransactionsDecorator, TransactionHandle, TransitionLogStore};
29use movement::{MovementIntent, MovementState, MOVEMENT_PREFIX};
30use publication::{PublicationIntent, PUBLICATION_PREFIX};
31
32/// Default name of the initial branch (analogous to git's `main`).
33pub const DEFAULT_BRANCH_NAME: &str = "main";
34
35const BRANCH_PREFIX: &str = "__vc:branch:";
36const TAG_PREFIX: &str = "__vc:tag:";
37const CURRENT_PREFIX: &str = "__vc:current=";
38const APPLIED_PREFIX: &str = "__vc:applied=";
39const TRANSITION_PREFIX: &str = "__vc:trans:";
40
41/// Metadata describing one branch in the version-control DAG.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct BranchInfo {
44    pub name: String,
45    pub parent: Option<String>,
46    pub fork_seq: i64,
47    pub head: i64,
48}
49
50impl BranchInfo {
51    pub fn new(name: String, parent: Option<String>, fork_seq: i64, head: i64) -> Self {
52        Self {
53            name,
54            parent,
55            fork_seq,
56            head,
57        }
58    }
59}
60
61/// Decorator that adds *time travel*, *branching*, and *tagging* over the
62/// transitions log produced by a [`TransactionsDecorator`].
63pub type VersionControlDecorator = GenericVersionControlDecorator<NamedTypesDecorator>;
64
65/// Version control over the append-only journal `clink` uses (issue #195).
66pub type FileVersionControlDecorator =
67    GenericVersionControlDecorator<NamedTypesDecorator, crate::FileTransitionLog>;
68
69/// Version control over a replaceable metadata store using the common links API.
70/// The default alias keeps the existing mapped metadata store and public API.
71///
72/// `L` is the transitions log of the wrapped transactions layer; `clink`
73/// uses the append-only [`FileTransitionLog`](crate::FileTransitionLog).
74pub struct GenericVersionControlDecorator<
75    B: NamedTypeLinks,
76    L: TransitionLogStore = NamedTypesDecorator,
77> {
78    transactions: GenericTransactionsDecorator<u32, NamedTypesDecorator, L>,
79    branches_store: B,
80    branches: HashMap<String, BranchInfo>,
81    tags: BTreeMap<String, i64>,
82    transition_branches: BTreeMap<i64, String>,
83    branch_links: HashMap<String, u32>,
84    tag_links: HashMap<String, u32>,
85    current_branch_link: u32,
86    applied_link: u32,
87    current_branch: String,
88    current_applied: i64,
89    active_transaction: Option<VersionControlTransactionState>,
90    active_movement: Option<MovementState>,
91    trace: bool,
92}
93
94#[derive(Debug, Clone)]
95struct VersionControlTransactionState {
96    id: u128,
97    branch_name: String,
98    before_sequence: i64,
99    after_sequence: Option<i64>,
100    intent_link: u32,
101}
102
103impl<B: NamedTypeLinks, L: TransitionLogStore> GenericVersionControlDecorator<B, L> {
104    pub fn new(
105        transactions: GenericTransactionsDecorator<u32, NamedTypesDecorator, L>,
106        branches_store: B,
107        trace: bool,
108    ) -> Result<Self> {
109        let mut decorator = Self {
110            transactions,
111            branches_store,
112            branches: HashMap::new(),
113            tags: BTreeMap::new(),
114            transition_branches: BTreeMap::new(),
115            branch_links: HashMap::new(),
116            tag_links: HashMap::new(),
117            current_branch_link: 0,
118            applied_link: 0,
119            current_branch: DEFAULT_BRANCH_NAME.to_string(),
120            current_applied: 0,
121            active_transaction: None,
122            active_movement: None,
123            trace,
124        };
125        decorator.recover()?;
126        decorator.ensure_default_branch()?;
127        Ok(decorator)
128    }
129
130    /// Conventional sidecar filename for the version-control store.
131    pub fn make_version_control_database_filename<P: AsRef<Path>>(p: P) -> PathBuf {
132        let path = p.as_ref();
133        let stem = path
134            .file_stem()
135            .and_then(|s| s.to_str())
136            .unwrap_or_default();
137        let name = format!("{stem}.versioncontrol.links");
138        match path.parent() {
139            Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
140            _ => PathBuf::from(name),
141        }
142    }
143
144    pub fn current_branch(&self) -> &str {
145        &self.current_branch
146    }
147
148    pub fn current_sequence(&self) -> i64 {
149        self.current_applied
150    }
151
152    pub fn list_branches(&self) -> Vec<BranchInfo> {
153        let mut branches: Vec<BranchInfo> = self.branches.values().cloned().collect();
154        branches.sort_by(|a, b| a.name.cmp(&b.name));
155        branches
156    }
157
158    pub fn list_tags(&self) -> BTreeMap<String, i64> {
159        self.tags.clone()
160    }
161
162    pub fn try_get_tag(&self, name: &str) -> Option<i64> {
163        self.tags.get(name).copied()
164    }
165
166    pub fn save(&mut self) -> Result<()> {
167        self.finish_movement()?;
168        if self.has_pending_publication() {
169            self.commit()?;
170        }
171        self.transactions.save()?;
172        self.branches_store.save()?;
173        Ok(())
174    }
175
176    pub fn transactions(&self) -> &GenericTransactionsDecorator<u32, NamedTypesDecorator, L> {
177        &self.transactions
178    }
179
180    pub fn transactions_mut(
181        &mut self,
182    ) -> &mut GenericTransactionsDecorator<u32, NamedTypesDecorator, L> {
183        &mut self.transactions
184    }
185
186    pub fn branches_store(&self) -> &B {
187        &self.branches_store
188    }
189
190    pub fn begin_transaction(&mut self) -> Result<TransactionHandle> {
191        if self.active_transaction.is_some() || self.active_movement.is_some() {
192            bail!("Nested version-control transactions are not supported.");
193        }
194        let before_sequence = self.transactions.last_logged_sequence();
195        let branch_name = self.current_branch.clone();
196        let handle = self.transactions.begin_transaction()?;
197        self.active_transaction = Some(VersionControlTransactionState {
198            id: handle.id,
199            branch_name,
200            before_sequence,
201            after_sequence: None,
202            intent_link: 0,
203        });
204        Ok(handle)
205    }
206
207    pub fn commit(&mut self) -> Result<()> {
208        let state = self
209            .active_transaction
210            .as_ref()
211            .cloned()
212            .ok_or_else(|| anyhow::anyhow!("No version-control transaction is open."))?;
213        if self.transactions.is_transaction_rolled_back(state.id) {
214            return self.finish_aborted_publication(&state);
215        }
216        let state = self.prepare_publication()?;
217        self.transactions.commit()?;
218        self.attribute_new_transitions_for_branch(
219            state.before_sequence,
220            state.after_sequence.expect("publication range is frozen"),
221            &state.branch_name,
222        )?;
223        self.branches_store.save()?;
224        self.clear_publication_intent(state.intent_link)?;
225        self.active_transaction = None;
226        Ok(())
227    }
228
229    pub fn rollback(&mut self) -> Result<()> {
230        if self.has_pending_commit() {
231            // An uncertain/durable decision must finish before publication.
232            return self.commit();
233        }
234        let state = self
235            .active_transaction
236            .as_ref()
237            .cloned()
238            .ok_or_else(|| anyhow::anyhow!("No version-control transaction is open."))?;
239        let outcome = self.transactions.rollback();
240        if outcome.is_ok() || self.transactions.is_transaction_rolled_back(state.id) {
241            self.finish_aborted_publication(&state)?;
242        }
243        Ok(outcome?)
244    }
245
246    // -- Write API (attribute new transitions to the current branch) ----
247
248    pub fn create(&mut self, source: u32, target: u32) -> Result<u32> {
249        self.run_version_write(|transactions| transactions.create(source, target))
250    }
251
252    pub fn update(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
253        self.update_observed(id, source, target, &mut |_, _| {})
254    }
255
256    /// [`Self::update`], reporting every change the decorator stack made —
257    /// the deletion of a link merged into its duplicate included.
258    pub fn update_observed(
259        &mut self,
260        id: u32,
261        source: u32,
262        target: u32,
263        observer: ChangeObserver<'_>,
264    ) -> Result<Link> {
265        self.run_version_write(|transactions| {
266            transactions.update_observed(id, source, target, observer)
267        })
268    }
269
270    pub fn delete(&mut self, id: u32) -> Result<Link> {
271        self.delete_observed(id, &mut |_, _| {})
272    }
273
274    /// [`Self::delete`], reporting every change the decorator stack made —
275    /// cascaded deletions of usages included.
276    pub fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
277        self.run_version_write(|transactions| transactions.delete_observed(id, observer))
278    }
279
280    pub fn create_and_update(&mut self, source: u32, target: u32) -> Result<u32> {
281        self.run_version_write(|transactions| transactions.create_and_update(source, target))
282    }
283
284    pub fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
285        self.run_version_write(|transactions| transactions.set_name(id, name))
286    }
287
288    pub fn remove_name(&mut self, id: u32) -> Result<()> {
289        self.run_version_write(|transactions| transactions.remove_name(id))
290    }
291
292    pub fn exists(&self, id: u32) -> bool {
293        self.transactions.exists(id)
294    }
295
296    pub fn get(&self, id: u32) -> Option<&Link> {
297        self.transactions.get(id)
298    }
299
300    pub fn all(&self) -> Vec<&Link> {
301        self.transactions.all()
302    }
303
304    pub fn search(&self, source: u32, target: u32) -> Option<u32> {
305        self.transactions.search(source, target)
306    }
307
308    pub fn get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
309        self.ensure_write_allowed()?;
310        if let Some(existing) = self.transactions.search(source, target) {
311            return Ok(existing);
312        }
313        self.create(source, target)
314    }
315
316    pub fn ensure_created(&mut self, id: u32) -> u32 {
317        self.try_ensure_created(id)
318            .expect("VersionControlDecorator::ensure_created failed")
319    }
320
321    /// Fallible explicit-address allocation, attributed like other writes.
322    pub fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
323        self.ensure_write_allowed()?;
324        // Existing and zero addresses remain read-only no-ops: do not open a
325        // transaction or write a decision marker for them.
326        if id == 0 || self.transactions.exists(id) {
327            return Ok(id);
328        }
329        self.run_version_write(|transactions| transactions.ensure_created(id))
330    }
331
332    fn run_version_write<T>(
333        &mut self,
334        write: impl FnOnce(
335            &mut GenericTransactionsDecorator<u32, NamedTypesDecorator, L>,
336        ) -> std::result::Result<T, crate::LinkError>,
337    ) -> Result<T> {
338        self.ensure_write_allowed()?;
339        let automatic = self.active_transaction.is_none();
340        if automatic {
341            self.begin_transaction()?;
342        }
343        let result = match write(&mut self.transactions) {
344            Ok(result) => result,
345            Err(error) => {
346                // Pre-commit failures still undo automatic effects. An undo
347                // failure leaves the facade owner available for retry.
348                if automatic {
349                    self.rollback()?;
350                }
351                return Err(error.into());
352            }
353        };
354        // Never undo a commit error: its decision may already be durable.
355        if automatic {
356            self.commit()?;
357        }
358        Ok(result)
359    }
360
361    fn attribute_new_transitions_for_branch(
362        &mut self,
363        before_seq: i64,
364        after_seq: i64,
365        branch_name: &str,
366    ) -> Result<()> {
367        if after_seq <= before_seq {
368            return Ok(());
369        }
370        for s in (before_seq + 1)..=after_seq {
371            self.transition_branches.insert(s, branch_name.to_string());
372            let marker = format!("{TRANSITION_PREFIX}{s}:branch={branch_name}");
373            self.write_immutable_marker(&marker)?;
374        }
375        if let Some(info) = self.branches.get(branch_name).cloned() {
376            let updated = BranchInfo {
377                head: after_seq,
378                ..info
379            };
380            self.branches
381                .insert(branch_name.to_string(), updated.clone());
382            self.update_branch_link(&updated)?;
383        }
384        if self.current_branch == branch_name {
385            self.current_applied = after_seq;
386            self.set_applied(after_seq)?;
387        }
388        Ok(())
389    }
390
391    // -- Branching ----------------------------------------------------
392
393    pub fn branch(&mut self, name: &str, from: Option<i64>) -> Result<()> {
394        self.ensure_no_open_transaction("branch")?;
395        if name.trim().is_empty() {
396            bail!("Branch name must not be empty.");
397        }
398        if self.branches.contains_key(name) {
399            bail!("Branch '{name}' already exists.");
400        }
401        let parent = self.current_branch.clone();
402        let fork_seq = from.unwrap_or(self.current_applied);
403        if fork_seq < 0 {
404            bail!("Fork point cannot be negative.");
405        }
406        if fork_seq > 0 {
407            let path = self.build_branch_seqs(&parent);
408            if !path.contains(&fork_seq) {
409                bail!("Fork point {fork_seq} is not reachable on branch '{parent}'.",);
410            }
411        }
412        self.create_branch(name, Some(parent), fork_seq, fork_seq)?;
413        self.trace(&format!(
414            "Created branch '{name}' from '{}' at seq {fork_seq}.",
415            self.current_branch
416        ));
417        Ok(())
418    }
419
420    pub fn switch_branch(&mut self, name: &str) -> Result<()> {
421        self.ensure_no_open_transaction("switch_branch")?;
422        if !self.branches.contains_key(name) {
423            bail!("Unknown branch '{name}'.");
424        }
425        let target_path = self.build_branch_seqs(name);
426        self.apply_diff_to(target_path, name)?;
427        self.trace(&format!(
428            "Switched to branch '{name}' at seq {}.",
429            self.current_applied
430        ));
431        Ok(())
432    }
433
434    pub fn checkout(&mut self, sequence: i64) -> Result<()> {
435        self.ensure_no_open_transaction("checkout")?;
436        if sequence < 0 {
437            bail!("Sequence must be non-negative.");
438        }
439        let current = self.current_branch.clone();
440        let path = self.build_branch_seqs(&current);
441        if sequence > 0 && !path.contains(&sequence) {
442            bail!("Sequence {sequence} is not reachable on branch '{current}'.",);
443        }
444        let target_path: Vec<i64> = path.iter().copied().filter(|s| *s <= sequence).collect();
445        self.apply_diff_to(target_path, &current)?;
446        self.trace(&format!(
447            "Checked out seq {sequence} on branch '{current}'.",
448        ));
449        Ok(())
450    }
451
452    pub fn tag(&mut self, name: &str, sequence: Option<i64>) -> Result<()> {
453        self.ensure_no_open_transaction("tag")?;
454        if name.trim().is_empty() {
455            bail!("Tag name must not be empty.");
456        }
457        let seq = sequence.unwrap_or(self.current_applied);
458        if seq < 0 {
459            bail!("Tag sequence must be non-negative.");
460        }
461        self.tags.insert(name.to_string(), seq);
462        self.update_tag_link(name, seq)?;
463        self.trace(&format!("Created tag '{name}' at seq {seq}.",));
464        Ok(())
465    }
466
467    // -- Path / diff helpers -----------------------------------------
468
469    fn apply_diff_to(&mut self, target_path: Vec<i64>, new_branch: &str) -> Result<()> {
470        self.start_movement(target_path, new_branch)
471    }
472
473    fn ensure_no_open_transaction(&self, operation: &str) -> Result<()> {
474        if self.active_transaction.is_some()
475            || self.active_movement.is_some()
476            || self.transactions.has_open_transaction()
477        {
478            bail!("{operation} is not allowed while a version-control transaction is open.");
479        }
480        Ok(())
481    }
482
483    fn has_pending_commit(&self) -> bool {
484        self.active_transaction
485            .as_ref()
486            .is_some_and(|state| self.transactions.must_finish_commit(state.id))
487    }
488
489    fn has_pending_publication(&self) -> bool {
490        self.active_transaction
491            .as_ref()
492            .is_some_and(|state| state.after_sequence.is_some())
493            || self.has_pending_commit()
494    }
495
496    pub(crate) fn ensure_write_allowed(&self) -> Result<()> {
497        if self.has_pending_publication() || self.active_movement.is_some() {
498            bail!(
499                "Version publication is incomplete; retry commit, rollback or save before writing."
500            );
501        }
502        self.transactions.ensure_write_allowed()?;
503        Ok(())
504    }
505
506    fn build_branch_seqs(&self, branch_name: &str) -> Vec<i64> {
507        // Walk leaf to root with the minimum descendant fork cutoff. A branch's
508        // head limits its own records, not the records inherited from its parent.
509        let mut positions = HashMap::new();
510        let mut chain: Vec<(i64, Vec<i64>)> = Vec::new();
511        let mut current = Some(branch_name);
512        let mut cutoff = i64::MAX;
513        while let Some(name) = current {
514            let Some(info) = self.branches.get(name) else {
515                break;
516            };
517            if positions.contains_key(name) {
518                break;
519            }
520            positions.insert(name, chain.len());
521            chain.push((cutoff.min(info.head), Vec::new()));
522            cutoff = cutoff.min(info.fork_seq);
523            current = info.parent.as_deref();
524        }
525        // BTreeMap iteration already orders each bucket by sequence. Scan all
526        // attribution once rather than once per ancestor; then emit root first.
527        for (sequence, owner) in &self.transition_branches {
528            if let Some(&position) = positions.get(owner.as_str()) {
529                let (limit, records) = &mut chain[position];
530                if sequence <= limit {
531                    records.push(*sequence);
532                }
533            }
534        }
535        chain
536            .into_iter()
537            .rev()
538            .flat_map(|(_, records)| records)
539            .collect()
540    }
541
542    // -- Persistence helpers -----------------------------------------
543
544    fn ensure_default_branch(&mut self) -> Result<()> {
545        if !self.branches.contains_key(DEFAULT_BRANCH_NAME) {
546            let mut existing = 0;
547            // Aborted and recovered-pending records have sequence numbers,
548            // but only a known committed decision makes them versions.
549            for transition in self.transactions.log() {
550                if !self
551                    .transactions
552                    .is_transaction_committed(transition.transaction_id)
553                {
554                    continue;
555                }
556                let s = transition.sequence;
557                existing = existing.max(s);
558                if let std::collections::btree_map::Entry::Vacant(entry) =
559                    self.transition_branches.entry(s)
560                {
561                    entry.insert(DEFAULT_BRANCH_NAME.to_string());
562                    let marker = format!("{TRANSITION_PREFIX}{s}:branch={DEFAULT_BRANCH_NAME}");
563                    self.write_immutable_marker(&marker)?;
564                }
565            }
566            self.create_branch(DEFAULT_BRANCH_NAME, None, 0, existing)?;
567            self.current_branch = DEFAULT_BRANCH_NAME.to_string();
568            self.current_applied = existing;
569            self.set_current_branch(DEFAULT_BRANCH_NAME)?;
570            self.set_applied(existing)?;
571        } else if self.current_branch_link == 0 {
572            let branch = self.current_branch.clone();
573            self.set_current_branch(&branch)?;
574        }
575        Ok(())
576    }
577
578    fn create_branch(
579        &mut self,
580        name: &str,
581        parent: Option<String>,
582        fork_seq: i64,
583        head: i64,
584    ) -> Result<()> {
585        let info = BranchInfo::new(name.to_string(), parent, fork_seq, head);
586        self.branches.insert(name.to_string(), info.clone());
587        self.update_branch_link(&info)?;
588        Ok(())
589    }
590
591    fn update_branch_link(&mut self, info: &BranchInfo) -> Result<()> {
592        let marker = encode_branch_marker(info);
593        let link = match self.branch_links.get(&info.name).copied() {
594            Some(link) => link,
595            None => {
596                let new_link = self.branches_store.try_create(0, 0)?;
597                self.branch_links.insert(info.name.clone(), new_link);
598                new_link
599            }
600        };
601        self.branches_store.set_name(link, &marker)?;
602        Ok(())
603    }
604
605    fn update_tag_link(&mut self, name: &str, seq: i64) -> Result<()> {
606        let marker = format!("{TAG_PREFIX}{name}={seq}");
607        let link = match self.tag_links.get(name).copied() {
608            Some(link) => link,
609            None => {
610                let new_link = self.branches_store.try_create(0, 0)?;
611                self.tag_links.insert(name.to_string(), new_link);
612                new_link
613            }
614        };
615        self.branches_store.set_name(link, &marker)?;
616        Ok(())
617    }
618
619    fn set_current_branch(&mut self, name: &str) -> Result<()> {
620        self.current_branch = name.to_string();
621        if self.current_branch_link == 0 {
622            self.current_branch_link = self.branches_store.try_create(0, 0)?;
623        }
624        let link = self.current_branch_link;
625        let marker = format!("{CURRENT_PREFIX}{name}");
626        self.branches_store.set_name(link, &marker)?;
627        Ok(())
628    }
629
630    fn set_applied(&mut self, seq: i64) -> Result<()> {
631        if self.applied_link == 0 {
632            self.applied_link = self.branches_store.try_create(0, 0)?;
633        }
634        let link = self.applied_link;
635        let marker = format!("{APPLIED_PREFIX}{seq}");
636        self.branches_store.set_name(link, &marker)?;
637        Ok(())
638    }
639
640    fn write_immutable_marker(&mut self, name: &str) -> Result<()> {
641        if self.branches_store.get_by_name(name)?.is_some() {
642            return Ok(());
643        }
644        let link = self.branches_store.try_create(0, 0)?;
645        self.branches_store.set_name(link, name)?;
646        Ok(())
647    }
648
649    pub fn recover(&mut self) -> Result<()> {
650        self.ensure_no_open_transaction("recover")?;
651        let uncommitted: HashSet<_> = self
652            .transactions
653            .log()
654            .into_iter()
655            .filter(|t| !self.transactions.is_transaction_committed(t.transaction_id))
656            .map(|t| t.sequence)
657            .collect();
658        self.branches.clear();
659        self.tags.clear();
660        self.transition_branches.clear();
661        self.branch_links.clear();
662        self.tag_links.clear();
663        self.current_branch = DEFAULT_BRANCH_NAME.to_string();
664        self.current_branch_link = 0;
665        self.applied_link = 0;
666        self.current_applied = 0;
667
668        let mut pending = Vec::new();
669        let mut movements = Vec::new();
670        let mut ambiguous_movement_metadata = false;
671        let links = self.branches_store.all_links();
672        for link in &links {
673            let name = match self.branches_store.get_name(link.index)? {
674                Some(value) => value,
675                None => continue,
676            };
677            if name.starts_with(MOVEMENT_PREFIX) {
678                movements.push((
679                    link.index,
680                    MovementIntent::decode(&name)
681                        .ok_or_else(|| anyhow::anyhow!("Invalid version movement intent."))?,
682                ));
683            } else if name.starts_with(PUBLICATION_PREFIX) {
684                pending.push((
685                    link.index,
686                    PublicationIntent::decode(&name)
687                        .ok_or_else(|| anyhow::anyhow!("Invalid version publication intent."))?,
688                ));
689            } else if name.starts_with(BRANCH_PREFIX) {
690                if let Some(info) = try_decode_branch_marker(&name) {
691                    ambiguous_movement_metadata |= self.branches.contains_key(&info.name);
692                    self.branches.insert(info.name.clone(), info.clone());
693                    self.branch_links.insert(info.name.clone(), link.index);
694                } else {
695                    ambiguous_movement_metadata = true;
696                }
697            } else if let Some(rest) = name.strip_prefix(CURRENT_PREFIX) {
698                ambiguous_movement_metadata |= self.current_branch_link != 0;
699                self.current_branch = rest.to_string();
700                self.current_branch_link = link.index;
701            } else if let Some(rest) = name.strip_prefix(APPLIED_PREFIX) {
702                if let Ok(seq) = rest.parse::<i64>() {
703                    ambiguous_movement_metadata |= self.applied_link != 0 || seq < 0;
704                    self.current_applied = seq;
705                    self.applied_link = link.index;
706                } else {
707                    ambiguous_movement_metadata = true;
708                }
709            } else if let Some(rest) = name.strip_prefix(TAG_PREFIX) {
710                if let Some(eq) = rest.rfind('=').filter(|&index| index > 0) {
711                    let tag_name = &rest[..eq];
712                    if let Ok(tag_seq) = rest[eq + 1..].parse::<i64>() {
713                        self.tags.insert(tag_name.to_string(), tag_seq);
714                        self.tag_links.insert(tag_name.to_string(), link.index);
715                    }
716                }
717            } else if let Some(rest) = name.strip_prefix(TRANSITION_PREFIX) {
718                let mut valid = false;
719                if let Some(colon) = rest.find(":branch=") {
720                    if let Ok(seq) = rest[..colon].parse::<i64>() {
721                        if uncommitted.contains(&seq) {
722                            bail!("Version metadata references uncommitted transition {seq}.");
723                        }
724                        let branch_name = &rest[colon + ":branch=".len()..];
725                        ambiguous_movement_metadata |=
726                            seq <= 0 || self.transition_branches.contains_key(&seq);
727                        self.transition_branches
728                            .insert(seq, branch_name.to_string());
729                        valid = true;
730                    }
731                }
732                ambiguous_movement_metadata |= !valid;
733            }
734        }
735        if !pending.is_empty() && !movements.is_empty() {
736            bail!("Version publication and movement intents overlap.");
737        }
738        if !movements.is_empty()
739            && (ambiguous_movement_metadata
740                || self.current_branch_link == 0
741                || self.applied_link == 0)
742        {
743            bail!("Ambiguous version movement metadata.");
744        }
745        self.recover_publications(pending)?;
746        self.recover_movements(movements)
747    }
748
749    fn trace(&self, message: &str) {
750        if self.trace {
751            crate::diagnostics::stderr!("[VersionControl] {message}");
752        }
753    }
754}
755
756fn encode_branch_marker(info: &BranchInfo) -> String {
757    let parent = info
758        .parent
759        .as_deref()
760        .map(encode_version_name)
761        .unwrap_or_else(|| "-".to_string());
762    format!(
763        "{BRANCH_PREFIX}2|{name}|{parent}|{fork}|{head}",
764        name = encode_version_name(&info.name),
765        fork = info.fork_seq,
766        head = info.head,
767    )
768}
769
770// Four hexadecimal digits per UTF-16 code unit match the C# sidecar format.
771fn encode_version_name(name: &str) -> String {
772    const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
773    let mut text = String::new();
774    for unit in name.encode_utf16() {
775        for shift in [12, 8, 4, 0] {
776            text.push(DIGITS[((unit >> shift) & 15) as usize] as char);
777        }
778    }
779    text
780}
781
782fn decode_version_name(text: &str) -> Option<String> {
783    if !text.len().is_multiple_of(4) {
784        return None;
785    }
786    let mut units = Vec::with_capacity(text.len() / 4);
787    for digits in text.as_bytes().as_chunks::<4>().0 {
788        let mut unit = 0u16;
789        for &digit in digits {
790            unit = (unit << 4)
791                | match digit {
792                    b'0'..=b'9' => (digit - b'0') as u16,
793                    b'a'..=b'f' => (digit - b'a' + 10) as u16,
794                    b'A'..=b'F' => (digit - b'A' + 10) as u16,
795                    _ => return None,
796                };
797        }
798        units.push(unit);
799    }
800    String::from_utf16(&units).ok()
801}
802
803fn try_decode_branch_marker(text: &str) -> Option<BranchInfo> {
804    let rest = text.strip_prefix(BRANCH_PREFIX)?;
805    if rest.starts_with("2|") {
806        let fields: Vec<_> = rest.split('|').collect();
807        if fields.len() == 5 {
808            let decoded = (|| {
809                Some(BranchInfo::new(
810                    decode_version_name(fields[1])?,
811                    if fields[2] == "-" {
812                        None
813                    } else {
814                        Some(decode_version_name(fields[2])?)
815                    },
816                    fields[3].parse().ok()?,
817                    fields[4].parse().ok()?,
818                ))
819            })();
820            if decoded.is_some() {
821                return decoded;
822            }
823        }
824        // Legacy names can start with "2|"; their delimiter suffix prevents
825        // them from being mistaken for a valid version-two record.
826    }
827    let parent_idx = rest.find(":parent=")?;
828    let name = &rest[..parent_idx];
829    let rest = &rest[parent_idx + ":parent=".len()..];
830    let fork_idx = rest.find(":fork=")?;
831    let parent_text = &rest[..fork_idx];
832    let rest = &rest[fork_idx + ":fork=".len()..];
833    let head_idx = rest.find(":head=")?;
834    let fork_text = &rest[..head_idx];
835    let head_text = &rest[head_idx + ":head=".len()..];
836    let fork: i64 = fork_text.parse().ok()?;
837    let head: i64 = head_text.parse().ok()?;
838    let parent = if parent_text.is_empty() {
839        None
840    } else {
841        Some(parent_text.to_string())
842    };
843    Some(BranchInfo::new(name.to_string(), parent, fork, head))
844}
845
846#[cfg(test)]
847mod tests;