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