link-cli 3.0.1

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! Optional version-control layer for the Rust link-cli.
//!
//! Mirrors the C# `VersionControlDecorator` in
//! `csharp/Foundation.Data.Doublets.Cli.Library/VersionControlDecorator.cs`.
//!
//! Sits above the [`TransactionsDecorator`]
//! and adds *time travel* ([`checkout`](VersionControlDecorator::checkout)),
//! *branching* ([`branch`](VersionControlDecorator::branch),
//! [`switch_branch`](VersionControlDecorator::switch_branch)), and
//! *tagging* ([`tag`](VersionControlDecorator::tag)) over the transitions
//! log. Optional — when not instantiated the underlying transactions
//! decorator behaves identically (R17).

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};

use anyhow::{bail, Result};

use crate::link::Link;
use crate::link_storage::ChangeObserver;
use crate::named_type_links::NamedTypeLinks;
use crate::named_types::NamedTypesDecorator;

mod movement;
#[cfg(test)]
mod path_contract_tests;
mod publication;
use crate::transactions::{TransactionHandle, TransactionsDecorator};
use movement::{MovementIntent, MovementState, MOVEMENT_PREFIX};
use publication::{PublicationIntent, PUBLICATION_PREFIX};

/// Default name of the initial branch (analogous to git's `main`).
pub const DEFAULT_BRANCH_NAME: &str = "main";

const BRANCH_PREFIX: &str = "__vc:branch:";
const TAG_PREFIX: &str = "__vc:tag:";
const CURRENT_PREFIX: &str = "__vc:current=";
const APPLIED_PREFIX: &str = "__vc:applied=";
const TRANSITION_PREFIX: &str = "__vc:trans:";

/// Metadata describing one branch in the version-control DAG.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchInfo {
    pub name: String,
    pub parent: Option<String>,
    pub fork_seq: i64,
    pub head: i64,
}

impl BranchInfo {
    pub fn new(name: String, parent: Option<String>, fork_seq: i64, head: i64) -> Self {
        Self {
            name,
            parent,
            fork_seq,
            head,
        }
    }
}

/// Decorator that adds *time travel*, *branching*, and *tagging* over the
/// transitions log produced by a [`TransactionsDecorator`].
pub type VersionControlDecorator = GenericVersionControlDecorator<NamedTypesDecorator>;

/// Version control over a replaceable metadata store using the common links API.
/// The default alias keeps the existing mapped metadata store and public API.
pub struct GenericVersionControlDecorator<B: NamedTypeLinks> {
    transactions: TransactionsDecorator,
    branches_store: B,
    branches: HashMap<String, BranchInfo>,
    tags: BTreeMap<String, i64>,
    transition_branches: BTreeMap<i64, String>,
    branch_links: HashMap<String, u32>,
    tag_links: HashMap<String, u32>,
    current_branch_link: u32,
    applied_link: u32,
    current_branch: String,
    current_applied: i64,
    active_transaction: Option<VersionControlTransactionState>,
    active_movement: Option<MovementState>,
    trace: bool,
}

#[derive(Debug, Clone)]
struct VersionControlTransactionState {
    id: u128,
    branch_name: String,
    before_sequence: i64,
    after_sequence: Option<i64>,
    intent_link: u32,
}

impl<B: NamedTypeLinks> GenericVersionControlDecorator<B> {
    pub fn new(
        transactions: TransactionsDecorator,
        branches_store: B,
        trace: bool,
    ) -> Result<Self> {
        let mut decorator = Self {
            transactions,
            branches_store,
            branches: HashMap::new(),
            tags: BTreeMap::new(),
            transition_branches: BTreeMap::new(),
            branch_links: HashMap::new(),
            tag_links: HashMap::new(),
            current_branch_link: 0,
            applied_link: 0,
            current_branch: DEFAULT_BRANCH_NAME.to_string(),
            current_applied: 0,
            active_transaction: None,
            active_movement: None,
            trace,
        };
        decorator.recover()?;
        decorator.ensure_default_branch()?;
        Ok(decorator)
    }

    /// Conventional sidecar filename for the version-control store.
    pub fn make_version_control_database_filename<P: AsRef<Path>>(p: P) -> PathBuf {
        let path = p.as_ref();
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default();
        let name = format!("{stem}.versioncontrol.links");
        match path.parent() {
            Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
            _ => PathBuf::from(name),
        }
    }

    pub fn current_branch(&self) -> &str {
        &self.current_branch
    }

    pub fn current_sequence(&self) -> i64 {
        self.current_applied
    }

    pub fn list_branches(&self) -> Vec<BranchInfo> {
        let mut branches: Vec<BranchInfo> = self.branches.values().cloned().collect();
        branches.sort_by(|a, b| a.name.cmp(&b.name));
        branches
    }

    pub fn list_tags(&self) -> BTreeMap<String, i64> {
        self.tags.clone()
    }

    pub fn try_get_tag(&self, name: &str) -> Option<i64> {
        self.tags.get(name).copied()
    }

    pub fn save(&mut self) -> Result<()> {
        self.finish_movement()?;
        if self.has_pending_publication() {
            self.commit()?;
        }
        self.transactions.save()?;
        self.branches_store.save()?;
        Ok(())
    }

    pub fn transactions(&self) -> &TransactionsDecorator {
        &self.transactions
    }

    pub fn transactions_mut(&mut self) -> &mut TransactionsDecorator {
        &mut self.transactions
    }

    pub fn branches_store(&self) -> &B {
        &self.branches_store
    }

    pub fn begin_transaction(&mut self) -> Result<TransactionHandle> {
        if self.active_transaction.is_some() || self.active_movement.is_some() {
            bail!("Nested version-control transactions are not supported.");
        }
        let before_sequence = self.transactions.last_logged_sequence();
        let branch_name = self.current_branch.clone();
        let handle = self.transactions.begin_transaction()?;
        self.active_transaction = Some(VersionControlTransactionState {
            id: handle.id,
            branch_name,
            before_sequence,
            after_sequence: None,
            intent_link: 0,
        });
        Ok(handle)
    }

    pub fn commit(&mut self) -> Result<()> {
        let state = self
            .active_transaction
            .as_ref()
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("No version-control transaction is open."))?;
        if self.transactions.is_transaction_rolled_back(state.id) {
            return self.finish_aborted_publication(&state);
        }
        let state = self.prepare_publication()?;
        self.transactions.commit()?;
        self.attribute_new_transitions_for_branch(
            state.before_sequence,
            state.after_sequence.expect("publication range is frozen"),
            &state.branch_name,
        )?;
        self.branches_store.save()?;
        self.clear_publication_intent(state.intent_link)?;
        self.active_transaction = None;
        Ok(())
    }

    pub fn rollback(&mut self) -> Result<()> {
        if self.has_pending_commit() {
            // An uncertain/durable decision must finish before publication.
            return self.commit();
        }
        let state = self
            .active_transaction
            .as_ref()
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("No version-control transaction is open."))?;
        let outcome = self.transactions.rollback();
        if outcome.is_ok() || self.transactions.is_transaction_rolled_back(state.id) {
            self.finish_aborted_publication(&state)?;
        }
        Ok(outcome?)
    }

    // -- Write API (attribute new transitions to the current branch) ----

    pub fn create(&mut self, source: u32, target: u32) -> Result<u32> {
        self.run_version_write(|transactions| transactions.create(source, target))
    }

    pub fn update(&mut self, id: u32, source: u32, target: u32) -> Result<Link> {
        self.update_observed(id, source, target, &mut |_, _| {})
    }

    /// [`Self::update`], reporting every change the decorator stack made —
    /// the deletion of a link merged into its duplicate included.
    pub fn update_observed(
        &mut self,
        id: u32,
        source: u32,
        target: u32,
        observer: ChangeObserver<'_>,
    ) -> Result<Link> {
        self.run_version_write(|transactions| {
            transactions.update_observed(id, source, target, observer)
        })
    }

    pub fn delete(&mut self, id: u32) -> Result<Link> {
        self.delete_observed(id, &mut |_, _| {})
    }

    /// [`Self::delete`], reporting every change the decorator stack made —
    /// cascaded deletions of usages included.
    pub fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
        self.run_version_write(|transactions| transactions.delete_observed(id, observer))
    }

    pub fn create_and_update(&mut self, source: u32, target: u32) -> Result<u32> {
        self.run_version_write(|transactions| transactions.create_and_update(source, target))
    }

    pub fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
        self.run_version_write(|transactions| transactions.set_name(id, name))
    }

    pub fn remove_name(&mut self, id: u32) -> Result<()> {
        self.run_version_write(|transactions| transactions.remove_name(id))
    }

    pub fn exists(&self, id: u32) -> bool {
        self.transactions.exists(id)
    }

    pub fn get(&self, id: u32) -> Option<&Link> {
        self.transactions.get(id)
    }

    pub fn all(&self) -> Vec<&Link> {
        self.transactions.all()
    }

    pub fn search(&self, source: u32, target: u32) -> Option<u32> {
        self.transactions.search(source, target)
    }

    pub fn get_or_create(&mut self, source: u32, target: u32) -> Result<u32> {
        self.ensure_write_allowed()?;
        if let Some(existing) = self.transactions.search(source, target) {
            return Ok(existing);
        }
        self.create(source, target)
    }

    pub fn ensure_created(&mut self, id: u32) -> u32 {
        self.try_ensure_created(id)
            .expect("VersionControlDecorator::ensure_created failed")
    }

    /// Fallible explicit-address allocation, attributed like other writes.
    pub fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
        self.ensure_write_allowed()?;
        // Existing and zero addresses remain read-only no-ops: do not open a
        // transaction or write a decision marker for them.
        if id == 0 || self.transactions.exists(id) {
            return Ok(id);
        }
        self.run_version_write(|transactions| transactions.ensure_created(id))
    }

    fn run_version_write<T>(
        &mut self,
        write: impl FnOnce(&mut TransactionsDecorator) -> std::result::Result<T, crate::LinkError>,
    ) -> Result<T> {
        self.ensure_write_allowed()?;
        let automatic = self.active_transaction.is_none();
        if automatic {
            self.begin_transaction()?;
        }
        let result = match write(&mut self.transactions) {
            Ok(result) => result,
            Err(error) => {
                // Pre-commit failures still undo automatic effects. An undo
                // failure leaves the facade owner available for retry.
                if automatic {
                    self.rollback()?;
                }
                return Err(error.into());
            }
        };
        // Never undo a commit error: its decision may already be durable.
        if automatic {
            self.commit()?;
        }
        Ok(result)
    }

    fn attribute_new_transitions_for_branch(
        &mut self,
        before_seq: i64,
        after_seq: i64,
        branch_name: &str,
    ) -> Result<()> {
        if after_seq <= before_seq {
            return Ok(());
        }
        for s in (before_seq + 1)..=after_seq {
            self.transition_branches.insert(s, branch_name.to_string());
            let marker = format!("{TRANSITION_PREFIX}{s}:branch={branch_name}");
            self.write_immutable_marker(&marker)?;
        }
        if let Some(info) = self.branches.get(branch_name).cloned() {
            let updated = BranchInfo {
                head: after_seq,
                ..info
            };
            self.branches
                .insert(branch_name.to_string(), updated.clone());
            self.update_branch_link(&updated)?;
        }
        if self.current_branch == branch_name {
            self.current_applied = after_seq;
            self.set_applied(after_seq)?;
        }
        Ok(())
    }

    // -- Branching ----------------------------------------------------

    pub fn branch(&mut self, name: &str, from: Option<i64>) -> Result<()> {
        self.ensure_no_open_transaction("branch")?;
        if name.trim().is_empty() {
            bail!("Branch name must not be empty.");
        }
        if self.branches.contains_key(name) {
            bail!("Branch '{name}' already exists.");
        }
        let parent = self.current_branch.clone();
        let fork_seq = from.unwrap_or(self.current_applied);
        if fork_seq < 0 {
            bail!("Fork point cannot be negative.");
        }
        if fork_seq > 0 {
            let path = self.build_branch_seqs(&parent);
            if !path.contains(&fork_seq) {
                bail!("Fork point {fork_seq} is not reachable on branch '{parent}'.",);
            }
        }
        self.create_branch(name, Some(parent), fork_seq, fork_seq)?;
        self.trace(&format!(
            "Created branch '{name}' from '{}' at seq {fork_seq}.",
            self.current_branch
        ));
        Ok(())
    }

    pub fn switch_branch(&mut self, name: &str) -> Result<()> {
        self.ensure_no_open_transaction("switch_branch")?;
        if !self.branches.contains_key(name) {
            bail!("Unknown branch '{name}'.");
        }
        let target_path = self.build_branch_seqs(name);
        self.apply_diff_to(target_path, name)?;
        self.trace(&format!(
            "Switched to branch '{name}' at seq {}.",
            self.current_applied
        ));
        Ok(())
    }

    pub fn checkout(&mut self, sequence: i64) -> Result<()> {
        self.ensure_no_open_transaction("checkout")?;
        if sequence < 0 {
            bail!("Sequence must be non-negative.");
        }
        let current = self.current_branch.clone();
        let path = self.build_branch_seqs(&current);
        if sequence > 0 && !path.contains(&sequence) {
            bail!("Sequence {sequence} is not reachable on branch '{current}'.",);
        }
        let target_path: Vec<i64> = path.iter().copied().filter(|s| *s <= sequence).collect();
        self.apply_diff_to(target_path, &current)?;
        self.trace(&format!(
            "Checked out seq {sequence} on branch '{current}'.",
        ));
        Ok(())
    }

    pub fn tag(&mut self, name: &str, sequence: Option<i64>) -> Result<()> {
        self.ensure_no_open_transaction("tag")?;
        if name.trim().is_empty() {
            bail!("Tag name must not be empty.");
        }
        let seq = sequence.unwrap_or(self.current_applied);
        if seq < 0 {
            bail!("Tag sequence must be non-negative.");
        }
        self.tags.insert(name.to_string(), seq);
        self.update_tag_link(name, seq)?;
        self.trace(&format!("Created tag '{name}' at seq {seq}.",));
        Ok(())
    }

    // -- Path / diff helpers -----------------------------------------

    fn apply_diff_to(&mut self, target_path: Vec<i64>, new_branch: &str) -> Result<()> {
        self.start_movement(target_path, new_branch)
    }

    fn ensure_no_open_transaction(&self, operation: &str) -> Result<()> {
        if self.active_transaction.is_some()
            || self.active_movement.is_some()
            || self.transactions.has_open_transaction()
        {
            bail!("{operation} is not allowed while a version-control transaction is open.");
        }
        Ok(())
    }

    fn has_pending_commit(&self) -> bool {
        self.active_transaction
            .as_ref()
            .is_some_and(|state| self.transactions.must_finish_commit(state.id))
    }

    fn has_pending_publication(&self) -> bool {
        self.active_transaction
            .as_ref()
            .is_some_and(|state| state.after_sequence.is_some())
            || self.has_pending_commit()
    }

    pub(crate) fn ensure_write_allowed(&self) -> Result<()> {
        if self.has_pending_publication() || self.active_movement.is_some() {
            bail!(
                "Version publication is incomplete; retry commit, rollback or save before writing."
            );
        }
        self.transactions.ensure_write_allowed()?;
        Ok(())
    }

    fn build_branch_seqs(&self, branch_name: &str) -> Vec<i64> {
        // Walk leaf to root with the minimum descendant fork cutoff. A branch's
        // head limits its own records, not the records inherited from its parent.
        let mut positions = HashMap::new();
        let mut chain: Vec<(i64, Vec<i64>)> = Vec::new();
        let mut current = Some(branch_name);
        let mut cutoff = i64::MAX;
        while let Some(name) = current {
            let Some(info) = self.branches.get(name) else {
                break;
            };
            if positions.contains_key(name) {
                break;
            }
            positions.insert(name, chain.len());
            chain.push((cutoff.min(info.head), Vec::new()));
            cutoff = cutoff.min(info.fork_seq);
            current = info.parent.as_deref();
        }
        // BTreeMap iteration already orders each bucket by sequence. Scan all
        // attribution once rather than once per ancestor; then emit root first.
        for (sequence, owner) in &self.transition_branches {
            if let Some(&position) = positions.get(owner.as_str()) {
                let (limit, records) = &mut chain[position];
                if sequence <= limit {
                    records.push(*sequence);
                }
            }
        }
        chain
            .into_iter()
            .rev()
            .flat_map(|(_, records)| records)
            .collect()
    }

    // -- Persistence helpers -----------------------------------------

    fn ensure_default_branch(&mut self) -> Result<()> {
        if !self.branches.contains_key(DEFAULT_BRANCH_NAME) {
            let mut existing = 0;
            // Aborted and recovered-pending records have sequence numbers,
            // but only a known committed decision makes them versions.
            for transition in self.transactions.log() {
                if !self
                    .transactions
                    .is_transaction_committed(transition.transaction_id)
                {
                    continue;
                }
                let s = transition.sequence;
                existing = existing.max(s);
                if let std::collections::btree_map::Entry::Vacant(entry) =
                    self.transition_branches.entry(s)
                {
                    entry.insert(DEFAULT_BRANCH_NAME.to_string());
                    let marker = format!("{TRANSITION_PREFIX}{s}:branch={DEFAULT_BRANCH_NAME}");
                    self.write_immutable_marker(&marker)?;
                }
            }
            self.create_branch(DEFAULT_BRANCH_NAME, None, 0, existing)?;
            self.current_branch = DEFAULT_BRANCH_NAME.to_string();
            self.current_applied = existing;
            self.set_current_branch(DEFAULT_BRANCH_NAME)?;
            self.set_applied(existing)?;
        } else if self.current_branch_link == 0 {
            let branch = self.current_branch.clone();
            self.set_current_branch(&branch)?;
        }
        Ok(())
    }

    fn create_branch(
        &mut self,
        name: &str,
        parent: Option<String>,
        fork_seq: i64,
        head: i64,
    ) -> Result<()> {
        let info = BranchInfo::new(name.to_string(), parent, fork_seq, head);
        self.branches.insert(name.to_string(), info.clone());
        self.update_branch_link(&info)?;
        Ok(())
    }

    fn update_branch_link(&mut self, info: &BranchInfo) -> Result<()> {
        let marker = encode_branch_marker(info);
        let link = match self.branch_links.get(&info.name).copied() {
            Some(link) => link,
            None => {
                let new_link = self.branches_store.try_create(0, 0)?;
                self.branch_links.insert(info.name.clone(), new_link);
                new_link
            }
        };
        self.branches_store.set_name(link, &marker)?;
        Ok(())
    }

    fn update_tag_link(&mut self, name: &str, seq: i64) -> Result<()> {
        let marker = format!("{TAG_PREFIX}{name}={seq}");
        let link = match self.tag_links.get(name).copied() {
            Some(link) => link,
            None => {
                let new_link = self.branches_store.try_create(0, 0)?;
                self.tag_links.insert(name.to_string(), new_link);
                new_link
            }
        };
        self.branches_store.set_name(link, &marker)?;
        Ok(())
    }

    fn set_current_branch(&mut self, name: &str) -> Result<()> {
        self.current_branch = name.to_string();
        if self.current_branch_link == 0 {
            self.current_branch_link = self.branches_store.try_create(0, 0)?;
        }
        let link = self.current_branch_link;
        let marker = format!("{CURRENT_PREFIX}{name}");
        self.branches_store.set_name(link, &marker)?;
        Ok(())
    }

    fn set_applied(&mut self, seq: i64) -> Result<()> {
        if self.applied_link == 0 {
            self.applied_link = self.branches_store.try_create(0, 0)?;
        }
        let link = self.applied_link;
        let marker = format!("{APPLIED_PREFIX}{seq}");
        self.branches_store.set_name(link, &marker)?;
        Ok(())
    }

    fn write_immutable_marker(&mut self, name: &str) -> Result<()> {
        if self.branches_store.get_by_name(name)?.is_some() {
            return Ok(());
        }
        let link = self.branches_store.try_create(0, 0)?;
        self.branches_store.set_name(link, name)?;
        Ok(())
    }

    pub fn recover(&mut self) -> Result<()> {
        self.ensure_no_open_transaction("recover")?;
        let uncommitted: HashSet<_> = self
            .transactions
            .log()
            .into_iter()
            .filter(|t| !self.transactions.is_transaction_committed(t.transaction_id))
            .map(|t| t.sequence)
            .collect();
        self.branches.clear();
        self.tags.clear();
        self.transition_branches.clear();
        self.branch_links.clear();
        self.tag_links.clear();
        self.current_branch = DEFAULT_BRANCH_NAME.to_string();
        self.current_branch_link = 0;
        self.applied_link = 0;
        self.current_applied = 0;

        let mut pending = Vec::new();
        let mut movements = Vec::new();
        let mut ambiguous_movement_metadata = false;
        let links = self.branches_store.all_links();
        for link in &links {
            let name = match self.branches_store.get_name(link.index)? {
                Some(value) => value,
                None => continue,
            };
            if name.starts_with(MOVEMENT_PREFIX) {
                movements.push((
                    link.index,
                    MovementIntent::decode(&name)
                        .ok_or_else(|| anyhow::anyhow!("Invalid version movement intent."))?,
                ));
            } else if name.starts_with(PUBLICATION_PREFIX) {
                pending.push((
                    link.index,
                    PublicationIntent::decode(&name)
                        .ok_or_else(|| anyhow::anyhow!("Invalid version publication intent."))?,
                ));
            } else if name.starts_with(BRANCH_PREFIX) {
                if let Some(info) = try_decode_branch_marker(&name) {
                    ambiguous_movement_metadata |= self.branches.contains_key(&info.name);
                    self.branches.insert(info.name.clone(), info.clone());
                    self.branch_links.insert(info.name.clone(), link.index);
                } else {
                    ambiguous_movement_metadata = true;
                }
            } else if let Some(rest) = name.strip_prefix(CURRENT_PREFIX) {
                ambiguous_movement_metadata |= self.current_branch_link != 0;
                self.current_branch = rest.to_string();
                self.current_branch_link = link.index;
            } else if let Some(rest) = name.strip_prefix(APPLIED_PREFIX) {
                if let Ok(seq) = rest.parse::<i64>() {
                    ambiguous_movement_metadata |= self.applied_link != 0 || seq < 0;
                    self.current_applied = seq;
                    self.applied_link = link.index;
                } else {
                    ambiguous_movement_metadata = true;
                }
            } else if let Some(rest) = name.strip_prefix(TAG_PREFIX) {
                if let Some(eq) = rest.rfind('=').filter(|&index| index > 0) {
                    let tag_name = &rest[..eq];
                    if let Ok(tag_seq) = rest[eq + 1..].parse::<i64>() {
                        self.tags.insert(tag_name.to_string(), tag_seq);
                        self.tag_links.insert(tag_name.to_string(), link.index);
                    }
                }
            } else if let Some(rest) = name.strip_prefix(TRANSITION_PREFIX) {
                let mut valid = false;
                if let Some(colon) = rest.find(":branch=") {
                    if let Ok(seq) = rest[..colon].parse::<i64>() {
                        if uncommitted.contains(&seq) {
                            bail!("Version metadata references uncommitted transition {seq}.");
                        }
                        let branch_name = &rest[colon + ":branch=".len()..];
                        ambiguous_movement_metadata |=
                            seq <= 0 || self.transition_branches.contains_key(&seq);
                        self.transition_branches
                            .insert(seq, branch_name.to_string());
                        valid = true;
                    }
                }
                ambiguous_movement_metadata |= !valid;
            }
        }
        if !pending.is_empty() && !movements.is_empty() {
            bail!("Version publication and movement intents overlap.");
        }
        if !movements.is_empty()
            && (ambiguous_movement_metadata
                || self.current_branch_link == 0
                || self.applied_link == 0)
        {
            bail!("Ambiguous version movement metadata.");
        }
        self.recover_publications(pending)?;
        self.recover_movements(movements)
    }

    fn trace(&self, message: &str) {
        if self.trace {
            crate::diagnostics::stderr!("[VersionControl] {message}");
        }
    }
}

fn encode_branch_marker(info: &BranchInfo) -> String {
    let parent = info
        .parent
        .as_deref()
        .map(encode_version_name)
        .unwrap_or_else(|| "-".to_string());
    format!(
        "{BRANCH_PREFIX}2|{name}|{parent}|{fork}|{head}",
        name = encode_version_name(&info.name),
        fork = info.fork_seq,
        head = info.head,
    )
}

// Four hexadecimal digits per UTF-16 code unit match the C# sidecar format.
fn encode_version_name(name: &str) -> String {
    const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
    let mut text = String::new();
    for unit in name.encode_utf16() {
        for shift in [12, 8, 4, 0] {
            text.push(DIGITS[((unit >> shift) & 15) as usize] as char);
        }
    }
    text
}

fn decode_version_name(text: &str) -> Option<String> {
    if !text.len().is_multiple_of(4) {
        return None;
    }
    let mut units = Vec::with_capacity(text.len() / 4);
    for digits in text.as_bytes().as_chunks::<4>().0 {
        let mut unit = 0u16;
        for &digit in digits {
            unit = (unit << 4)
                | match digit {
                    b'0'..=b'9' => (digit - b'0') as u16,
                    b'a'..=b'f' => (digit - b'a' + 10) as u16,
                    b'A'..=b'F' => (digit - b'A' + 10) as u16,
                    _ => return None,
                };
        }
        units.push(unit);
    }
    String::from_utf16(&units).ok()
}

fn try_decode_branch_marker(text: &str) -> Option<BranchInfo> {
    let rest = text.strip_prefix(BRANCH_PREFIX)?;
    if rest.starts_with("2|") {
        let fields: Vec<_> = rest.split('|').collect();
        if fields.len() == 5 {
            let decoded = (|| {
                Some(BranchInfo::new(
                    decode_version_name(fields[1])?,
                    if fields[2] == "-" {
                        None
                    } else {
                        Some(decode_version_name(fields[2])?)
                    },
                    fields[3].parse().ok()?,
                    fields[4].parse().ok()?,
                ))
            })();
            if decoded.is_some() {
                return decoded;
            }
        }
        // Legacy names can start with "2|"; their delimiter suffix prevents
        // them from being mistaken for a valid version-two record.
    }
    let parent_idx = rest.find(":parent=")?;
    let name = &rest[..parent_idx];
    let rest = &rest[parent_idx + ":parent=".len()..];
    let fork_idx = rest.find(":fork=")?;
    let parent_text = &rest[..fork_idx];
    let rest = &rest[fork_idx + ":fork=".len()..];
    let head_idx = rest.find(":head=")?;
    let fork_text = &rest[..head_idx];
    let head_text = &rest[head_idx + ":head=".len()..];
    let fork: i64 = fork_text.parse().ok()?;
    let head: i64 = head_text.parse().ok()?;
    let parent = if parent_text.is_empty() {
        None
    } else {
        Some(parent_text.to_string())
    };
    Some(BranchInfo::new(name.to_string(), parent, fork, head))
}

#[cfg(test)]
mod tests;