girt 0.3.0

An incremental, idiomatic Rust implementation of Git
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
use std::num::NonZeroU32;
use std::ops::ControlFlow;
use std::path::Path;
use std::sync::atomic::AtomicBool;

use super::{
    Advertisement, FetchError, FetchInstalled, FetchLimits, FetchUpdateLimits, KnownHistory,
    ReceivedFetch,
};
use crate::refs::{Expected, RefEdit, RefEditOutcome, RefName, ReferenceError, Reflog, Target};
use crate::remote::{Direction, Mapping, MappingError, Refspecs};
use crate::transport::TransportControl;
use crate::{ObjectId, Repository};

/// A synchronous destination snapshot and explicit policy for one fetch.
///
/// # Workflow
///
/// [`Self::prepare`] captures destination values. Choose optional depth, pruning, and reflog
/// policy before [`Self::receive_local`] or a network adapter reads the actual advertisement.
/// [`FetchReady::finish`] installs validated objects and publishes eligible refs; inspect
/// [`FetchReport`] or [`FetchFinishError`] for completed effects and retry decisions. Use
/// [`Self::plan`] only to preview how an advertisement would map, not to reserve its tips.
///
/// Construct with a named remote's [`crate::remote::Remote::fetch_refspecs`] or an explicit list.
/// Endpoint selection and credentials remain separate transport arguments. Only `refs/remotes/*`
/// and `refs/tags/*` destinations are supported by default. A caller may add tag-like namespaces
/// with [`Self::with_tag_destination_namespace`]. Branch and symbolic destinations are rejected.
/// Remote-tracking refs accept all validated object kinds. When both old/new tips peel to commits,
/// non-fast-forward updates require force intent and name authorization; other kind replacements
/// need neither. Replacing a tag requires both `+` and its name in `authorized_force`.
/// Neither source-only selection nor an unchanged tag requires force authorization.
///
/// Preparation performs filesystem work; transport selection subsequently maps the actual
/// advertisement using only this owned snapshot. HTTP/SSH downloads retain owned validation state
/// for caller-controlled worker handoff. No runtime, endpoint discovery or worker is created here.
///
/// Callers must exclude checkout, symbolic-HEAD/branch changes, worktree registration changes and
/// GC/pruning from preparation through publication. Ordinary destination writers may run
/// concurrently: changed destinations use exact expected values in a reference transaction.
/// Unchanged destinations are reported but not written or locked, and may change concurrently after
/// the snapshot. HEAD chains in the main and registered linked worktrees must stay within
/// `refs/heads/*` (or be detached), so rejecting branch destinations also protects checked-out
/// references. Unusual HEAD chains and inaccessible worktree metadata fail closed, even for
/// source-only fetches.
/// Verified known history must include exactly the destination's captured shallow roots, so a
/// depth response cannot silently drop boundaries belonging to other local references.
///
/// Exact selectors missing from the advertisement are reported while other valid selections
/// continue. [`Self::with_prune`] permits scoped remote-tracking and authorized tag-namespace
/// deletion. Shallow depth changes
/// use a conditional metadata lock and are reported separately from object/ref effects.
///
/// This workflow does not write `FETCH_HEAD`, infer tags, clone, check out, edit
/// configuration, discover credentials, or implement the full Git CLI. See
/// `examples/fetch_remote.rs`.
#[derive(Debug)]
pub struct FetchRequest {
    repository: Repository,
    specs: Refspecs,
    snapshot: BTreeMap<RefName, Target>,
    authorized_force: BTreeSet<RefName>,
    reflog: Reflog,
    namespace_reflogs: Vec<(RefName, Reflog, Reflog)>,
    kind_reflogs: Vec<(RefName, FetchUpdateKind, Reflog)>,
    additional_tag_namespaces: Vec<RefName>,
    retained_missing_sources: BTreeSet<Vec<u8>>,
    prune: bool,
    pub(super) depth: Option<NonZeroU32>,
    shallow_before: Vec<ObjectId>,
}

impl FetchRequest {
    /// Captures destination values and validates the supported worktree layout without writing.
    ///
    /// `authorized_force` authorizes replacement only for those exact destination names; it does
    /// not turn an unforced refspec into a forced one. `reflog` chooses the default action for
    /// changed refs; [`Self::with_reflog_for_namespace`] may override it. Reference enumeration has
    /// its existing unbounded metadata allocation contract; transfer and object budgets are
    /// supplied separately.
    ///
    /// # Errors
    ///
    /// Rejects push refspecs, unsupported HEAD chains, inaccessible worktrees, or reference errors.
    /// Mapping-specific failures are returned when the transfer advertisement is available.
    pub fn prepare(
        repository: Repository,
        specs: Refspecs,
        authorized_force: BTreeSet<RefName>,
        reflog: Reflog,
    ) -> Result<Self, FetchPlanError> {
        if specs.direction() != Direction::Fetch {
            return Err(FetchPlanError::Mapping(MappingError::Direction));
        }
        super::worktree::check(&repository)?;
        let snapshot = repository
            .references()?
            .list()?
            .into_iter()
            .map(|reference| (reference.name, reference.target))
            .collect();
        let shallow_before = repository.shallow_roots().iter().collect();
        Ok(Self {
            repository,
            specs,
            snapshot,
            authorized_force,
            reflog,
            namespace_reflogs: Vec::new(),
            kind_reflogs: Vec::new(),
            additional_tag_namespaces: Vec::new(),
            retained_missing_sources: BTreeSet::new(),
            prune: false,
            depth: None,
            shallow_before,
        })
    }

    /// Allows tag-like destinations below one caller-owned reference namespace.
    ///
    /// Only descendants of `namespace` are added; the namespace itself remains unsupported.
    /// Replacements require both force intent and authorization, as for `refs/tags/*`. When
    /// pruning is enabled, absent sources can prune these destinations. The caller must choose
    /// a namespace it owns and keep unrelated references outside it.
    pub fn with_tag_destination_namespace(mut self, namespace: RefName) -> Self {
        self.additional_tag_namespaces.push(namespace);
        self
    }

    /// Chooses reflog actions for changed destinations below one reference namespace.
    ///
    /// `update` applies to creates and updates and must not be [`Reflog::Delete`]. `prune` applies
    /// to deletions requested by
    /// [`Self::with_prune`]. The most specific matching namespace wins. Names outside configured
    /// namespaces keep the policy passed to [`Self::prepare`]. This does not authorize a
    /// destination or alter its update rules. Use [`Reflog::Delete`] for `prune` when a removed
    /// reference should lose its log, as Git does for pruned remote-tracking refs.
    pub fn with_reflog_for_namespace(
        mut self,
        namespace: RefName,
        update: Reflog,
        prune: Reflog,
    ) -> Self {
        self.namespace_reflogs.push((namespace, update, prune));
        self
    }

    /// Overrides a namespace's reflog action for one changed update kind.
    ///
    /// This permits different messages for creation, fast-forward, forced update and other
    /// outcomes. The caller supplies the complete message and identity; this workflow does not
    /// synthesize Git CLI command text. A kind-specific action takes priority over a matching
    /// [`Self::with_reflog_for_namespace`] action, and the most specific matching namespace wins.
    /// `SourceOnly` and `Unchanged` never write a reference or a reflog.
    pub fn with_reflog_for_update_kind(
        mut self,
        namespace: RefName,
        kind: FetchUpdateKind,
        reflog: Reflog,
    ) -> Self {
        self.kind_reflogs.push((namespace, kind, reflog));
        self
    }

    fn reflog_for(&self, name: &RefName, kind: FetchUpdateKind) -> Reflog {
        if let Some((_, _, reflog)) = self
            .kind_reflogs
            .iter()
            .filter(|(namespace, selected, _)| *selected == kind && is_descendant(name, namespace))
            .max_by_key(|(namespace, _, _)| namespace.as_bytes().len())
        {
            return reflog.clone();
        }
        self.namespace_reflogs
            .iter()
            .filter(|(namespace, _, _)| is_descendant(name, namespace))
            .max_by_key(|(namespace, _, _)| namespace.as_bytes().len())
            .map(|(_, update, prune)| {
                if kind == FetchUpdateKind::Prune {
                    prune
                } else {
                    update
                }
            })
            .unwrap_or(&self.reflog)
            .clone()
    }

    fn additional_tag_destination(&self, name: &RefName) -> bool {
        self.additional_tag_namespaces
            .iter()
            .any(|namespace| is_descendant(name, namespace))
    }

    /// Requests a positive commit depth on HTTP/SSH upload-pack or depth one from a native local
    /// source. Local depth requires one selected commit tip and a nonshallow source. This permits
    /// a resulting shallow-boundary change during coordinated publication.
    /// Network validation materializes any reachable known-local dependencies in a nonempty
    /// received pack. An empty object transfer verifies local dependencies during publication;
    /// the caller must continue excluding concurrent collection for that existing history.
    pub fn with_depth(mut self, depth: NonZeroU32) -> Self {
        self.depth = Some(depth);
        self
    }

    /// Enables deletion of stale direct remote-tracking and added tag-namespace destinations
    /// owned by these refspecs. Exact snapshot values are required at publication. Built-in
    /// `refs/tags/*` destinations and excluded sources are retained.
    pub fn with_prune(mut self) -> Self {
        self.prune = true;
        self
    }

    /// Retains destinations for absent exact sources while pruning other stale refs.
    ///
    /// The caller supplies only exact positive source names whose cached destinations Git would
    /// keep after a missing-ref retry. This applies to the advertisement from this transfer, so
    /// no second discovery or fetch is needed. The source remains selected if it is advertised.
    pub fn with_retained_missing_sources(
        mut self,
        sources: impl IntoIterator<Item = RefName>,
    ) -> Self {
        self.retained_missing_sources
            .extend(sources.into_iter().map(|source| source.as_bytes().to_vec()));
        self
    }

    /// Maps an advertisement against the captured destination values, without I/O or mutation.
    ///
    /// Useful for previewing policy. Transfer adapters always recompute this plan from their own
    /// advertisement; a preview cannot substitute IDs from an earlier server connection.
    ///
    /// # Errors
    ///
    /// Rejects mapping collisions/missing sources, unsupported destinations, symbolic stored
    /// values, and tag replacements lacking both force intent and authorization. No objects are
    /// requested.
    pub fn plan(&self, advertisement: &Advertisement) -> Result<Vec<FetchUpdate>, FetchPlanError> {
        let mut updates: Vec<FetchUpdate> = self
            .specs
            .map_advertisement_with_missing(advertisement)?
            .0
            .into_iter()
            .map(|mapping| {
                let Some(name) = &mapping.destination else {
                    return Ok(FetchUpdate {
                        mapping,
                        previous: None,
                        kind: FetchUpdateKind::SourceOnly,
                    });
                };
                let bytes = name.as_bytes();
                let tag_destination =
                    bytes.starts_with(b"refs/tags/") || self.additional_tag_destination(name);
                if !bytes.starts_with(b"refs/remotes/") && !tag_destination {
                    return Err(FetchPlanError::Destination(name.clone()));
                }
                let previous = match self.snapshot.get(name) {
                    Some(Target::Symbolic(_)) => {
                        return Err(FetchPlanError::Symbolic(name.clone()));
                    }
                    Some(Target::Direct(id)) => Some(*id),
                    None => None,
                };
                let new = mapping
                    .source
                    .as_ref()
                    .expect("fetch mapping has a source")
                    .id;
                let kind = update_kind(
                    name,
                    previous,
                    new,
                    mapping.force,
                    self.authorized_force.contains(name),
                    tag_destination,
                )?;
                Ok(FetchUpdate {
                    mapping,
                    previous,
                    kind,
                })
            })
            .collect::<Result<_, _>>()?;
        if self.prune {
            let advertised: BTreeSet<_> = advertisement
                .refs
                .iter()
                .filter(|reference| !reference.peeled)
                .map(|reference| reference.name.as_bytes().to_vec())
                .collect();
            let selected: BTreeSet<_> = updates
                .iter()
                .filter_map(|update| update.mapping.destination.as_ref())
                .cloned()
                .collect();
            for (name, target) in &self.snapshot {
                if !(name.as_bytes().starts_with(b"refs/remotes/")
                    || self.additional_tag_destination(name))
                    || selected.contains(name)
                {
                    continue;
                }
                let sources = self.specs.prune_sources(name);
                if sources.is_empty()
                    || sources.iter().any(|source| {
                        advertised.contains(source)
                            || self.retained_missing_sources.contains(source.as_slice())
                    })
                {
                    continue;
                }
                let Target::Direct(previous) = target else {
                    // Remote HEAD aliases are local symbolic policy, not stale remote tips.
                    continue;
                };
                updates.push(FetchUpdate {
                    mapping: Mapping {
                        source: None,
                        destination: Some(name.clone()),
                        force: false,
                    },
                    previous: Some(*previous),
                    kind: FetchUpdateKind::Prune,
                });
            }
        }
        Ok(updates)
    }

    /// Transfers and validates synchronously using a caller-selected local upload-pack endpoint.
    ///
    /// Pass explicit verified `known` history for incremental negotiation, or an empty history for
    /// a full transfer. The transport control bounds network/process lifetime, not later install.
    /// Mapping failures select no wants, then return the saved planning error; no storage changes.
    ///
    /// # Errors
    ///
    /// Returns mapping/policy failures or [`super::receive_local_with_known`]'s transfer failures.
    pub fn receive_local(
        self,
        source: impl AsRef<Path>,
        known: &KnownHistory,
        limits: FetchLimits,
        control: TransportControl<'_>,
        progress: impl FnMut(&[u8]) -> ControlFlow<()>,
    ) -> Result<FetchReady, FetchWorkflowError> {
        self.receive_local_with_progress(source, known, limits, control, progress, |_| {})
    }

    /// Constructs a local fetch while reporting completed source reads and pack entries.
    ///
    /// Uses [`Self::receive_local`]'s planning and storage contract and
    /// [`super::receive_local_with_known_and_progress`]'s callback contract. Completion describes
    /// construction, not installation or reference publication. Observers must return promptly.
    ///
    /// # Errors
    ///
    /// Returns [`Self::receive_local`]'s failures without a completion notification.
    pub fn receive_local_with_progress(
        self,
        source: impl AsRef<Path>,
        known: &KnownHistory,
        limits: FetchLimits,
        control: TransportControl<'_>,
        progress: impl FnMut(&[u8]) -> ControlFlow<()>,
        mut observe: impl FnMut(super::LocalFetchProgress),
    ) -> Result<FetchReady, FetchWorkflowError> {
        self.check_known(known)?;
        let mut plan = None;
        let received = super::local::receive_local_with_known_depth_and_progress(
            source,
            |advertisement| select(self.plan(advertisement), &mut plan),
            known,
            self.depth,
            limits,
            control,
            progress,
            |event| {
                if event != super::LocalFetchProgress::Complete {
                    observe(event);
                }
            },
        );
        let updates = selected(plan, &received)?;
        let ready = FetchReady {
            request: self,
            updates,
            received: received?,
        };
        control.check().map_err(FetchError::from)?;
        observe(super::LocalFetchProgress::Complete);
        Ok(ready)
    }

    /// Transfers from a caller-owned v0/v1 upload-pack stream using this request's depth policy.
    /// The caller owns process/network lifetime and must close and reap it on every outcome.
    ///
    /// # Errors
    ///
    /// Returns planning or wire/pack validation errors without destination changes.
    pub fn receive_session(
        self,
        reader: &mut impl Read,
        writer: &mut impl Write,
        known: &KnownHistory,
        limits: FetchLimits,
        cancel: &AtomicBool,
        progress: impl FnMut(&[u8]) -> ControlFlow<()>,
    ) -> Result<FetchReady, FetchWorkflowError> {
        self.check_known(known)?;
        let mut plan = None;
        let received = super::receive_with_known_depth(
            reader,
            writer,
            |advertisement| select(self.plan(advertisement), &mut plan),
            known,
            super::FetchOptions {
                limits,
                depth: self.depth,
            },
            cancel,
            progress,
        );
        let updates = selected(plan, &received)?;
        Ok(FetchReady {
            request: self,
            updates,
            received: received?,
        })
    }

    pub(super) fn check_known(&self, known: &KnownHistory) -> Result<(), FetchError> {
        if known.shallow != self.shallow_before {
            return Err(FetchError::Unsupported(
                "known shallow boundaries differ from destination",
            ));
        }
        Ok(())
    }
}

fn is_descendant(name: &RefName, namespace: &RefName) -> bool {
    name.as_bytes()
        .strip_prefix(namespace.as_bytes())
        .is_some_and(|suffix| suffix.starts_with(b"/") && suffix.len() > 1)
}

fn update_kind(
    name: &RefName,
    previous: Option<ObjectId>,
    new: ObjectId,
    force: bool,
    authorized: bool,
    tag_destination: bool,
) -> Result<FetchUpdateKind, FetchPlanError> {
    match previous {
        None => Ok(FetchUpdateKind::Create),
        Some(old) if old == new => Ok(FetchUpdateKind::Unchanged),
        Some(_) if tag_destination => {
            if !force || !authorized {
                return Err(FetchPlanError::TagReplacement(name.clone()));
            }
            Ok(FetchUpdateKind::ForcedTag)
        }
        Some(_) => Ok(FetchUpdateKind::Replace),
    }
}

pub(super) fn select(
    result: Result<Vec<FetchUpdate>, FetchPlanError>,
    saved: &mut Option<Result<Vec<FetchUpdate>, FetchPlanError>>,
) -> Vec<ObjectId> {
    let wants = result
        .as_ref()
        .map(|updates| {
            updates
                .iter()
                .filter_map(|update| update.mapping.source.as_ref().map(|s| s.id))
                .collect()
        })
        .unwrap_or_default();
    *saved = Some(result);
    wants
}

pub(super) fn selected<T>(
    plan: Option<Result<Vec<FetchUpdate>, FetchPlanError>>,
    transfer: &Result<T, FetchError>,
) -> Result<Vec<FetchUpdate>, FetchWorkflowError> {
    match plan {
        Some(plan) => Ok(plan?),
        None if transfer.is_err() => Ok(Vec::new()),
        None => Err(FetchError::Protocol("selection callback was not invoked").into()),
    }
}

/// A validated transfer tied to its actual advertisement, destination snapshot and repository.
///
/// Owns all state needed for synchronous installation/publication; can move to a caller's worker.
/// Dropping it has no storage side effects. No public API permits substituting a different
/// transfer, destination or mapping after validation.
#[derive(Debug)]
pub struct FetchReady {
    pub(super) request: FetchRequest,
    pub(super) updates: Vec<FetchUpdate>,
    pub(super) received: ReceivedFetch,
}

impl FetchReady {
    // Clone supplies a fresh repository; use only the actual transfer advertisement.
    pub(crate) fn for_clone(
        request: FetchRequest,
        received: ReceivedFetch,
    ) -> Result<Self, FetchPlanError> {
        let updates = request.plan(received.advertisement())?;
        Ok(Self {
            request,
            updates,
            received,
        })
    }

    /// The mapping and decisions derived from the advertisement used by this transfer.
    pub fn updates(&self) -> &[FetchUpdate] {
        &self.updates
    }

    /// Validated object response, available for inspecting advertisement and transfer statistics.
    pub fn received(&self) -> &ReceivedFetch {
        &self.received
    }

    /// Installs a self-contained pack under retention before publishing shallow metadata or refs.
    ///
    /// Supports self-contained complete and depth-limited transfers, including refresh of an
    /// existing shallow destination. Known-local dependencies and empty transfers are refused.
    /// Holds the conditional shallow lock from installation through the returned phase's
    /// publication, including depth requests whose response has no boundaries. An existing pack or
    /// index is refused because a collector may already have selected it for removal.
    ///
    /// The returned phase permits caller-specific object checks before any shallow or reference
    /// publication. Call [`RetainedFetchReady::finish`] to publish, or
    /// [`RetainedFetchReady::into_recovery`] to abandon the phase with its effects and retention.
    /// Dropping the phase releases its shallow lock but leaves the retention marker on disk.
    /// The caller still owns the GC and HEAD/worktree exclusions on [`FetchRequest`]; retention
    /// protects only this newly installed pack. No references or reflogs change in this method.
    ///
    /// # Errors
    ///
    /// Returns validation, shallow-lock, or installation failures with completed effects. Once
    /// retention is acquired, errors retain its handle; a failed installation can leave partial
    /// pack artifacts even when the report has no successful installation. Do not retry through
    /// another fetch implementation after acquiring retention without inspecting those effects.
    pub fn install_retained(
        mut self,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
    ) -> Result<RetainedFetchReady, RetainedFetchFinishError> {
        let mut report = self.take_report();
        let prepare = || {
            let checksum = self
                .received
                .retention_checksum(&self.request.repository, cancel)
                .map_err(FetchFinishFailure::Installation)?;
            let shallow_lock = self.lock_shallow(true, cancel)?;
            Ok((checksum, shallow_lock))
        };
        let (checksum, shallow_lock) = match prepare() {
            Ok(prepared) => prepared,
            Err(source) => {
                return Err(RetainedFetchFinishError {
                    report: Box::new(report),
                    source,
                    retention: None,
                });
            }
        };
        let installation =
            super::retention::install_with(&self.request.repository, checksum, || {
                self.received.install_for_workflow(
                    &self.request.repository,
                    limits.snapshot,
                    cancel,
                    shallow_lock.is_some(),
                )
            });
        let (installed, retention) = match installation {
            Ok(result) => result,
            Err(error) => {
                return Err(RetainedFetchFinishError {
                    report: Box::new(report),
                    source: FetchFinishFailure::Installation(*error.source).into(),
                    retention: error.retention,
                });
            }
        };
        report.installed = Some(installed);
        Ok(RetainedFetchReady {
            ready: self,
            report,
            limits,
            shallow_lock,
            retention,
        })
    }

    /// Installs validated objects and shallow metadata, then publishes changed destinations.
    ///
    /// Rechecks known-local dependencies during installation, installed selected-tip readability,
    /// update ancestry and supported HEAD
    /// layout before publication. All changed destinations use the exact values captured by
    /// preparation, including absence. Source-only and unchanged entries produce no reference
    /// edits or reflog entries. Object installation can succeed even when later checks or
    /// reference publication fail. A shallow metadata change can also remain after a later
    /// reference failure. Cancellation is checked before installation and before the
    /// transaction, but does not interrupt a started reference transaction. Observe completion
    /// before releasing worker resources.
    ///
    /// The caller must coordinate GC and worktree/HEAD changes as described on [`FetchRequest`].
    /// Transaction locks do not protect objects from external deletion. Readers can observe partial
    /// reference publication; neither whole-operation rollback nor crash durability is promised.
    ///
    /// # Errors
    ///
    /// The returned report distinguishes installation success from publication. An installation
    /// failure can leave an unindexed pack (see [`ReceivedFetch::install`]); no ref edits were
    /// made. After successful installation, all installed objects remain on error. Transaction
    /// errors retain exact per-ref/per-log partial effects. No automatic cleanup, rollback or
    /// retry occurs.
    pub fn finish(
        mut self,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
    ) -> Result<FetchReport, FetchFinishError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "fetch.finish",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            let mut report = self.take_report();
            let result = self.install_publish(limits, cancel, &mut report);
            match result {
                Ok(()) => Ok(report),
                Err(source) => Err(FetchFinishError {
                    report: Box::new(report),
                    source,
                }),
            }
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| {
            crate::trace::fetch_finish(error, &span)
        });

        result
    }

    fn install_publish(
        &self,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
        report: &mut FetchReport,
    ) -> Result<(), Box<FetchFinishFailure>> {
        let mut shallow_lock = self.lock_shallow(false, cancel)?;
        report.installed = Some(
            self.received
                .install_for_workflow(
                    &self.request.repository,
                    limits.snapshot,
                    cancel,
                    shallow_lock.is_some(),
                )
                .map_err(FetchFinishFailure::Installation)?,
        );
        self.publish_installed(limits, cancel, &mut shallow_lock, report)
    }

    fn take_report(&mut self) -> FetchReport {
        FetchReport {
            updates: std::mem::take(&mut self.updates),
            pack_bytes: self.received.pack_bytes(),
            objects: self.received.object_count(),
            installed: None,
            references: Vec::new(),
            shallow_published: false,
            missing: self
                .request
                .specs
                .map_advertisement_with_missing(self.received.advertisement())
                .expect("validated fetch mapping")
                .1,
        }
    }

    fn lock_shallow(
        &self,
        retained: bool,
        cancel: &AtomicBool,
    ) -> Result<Option<super::shallow::Lock>, Box<FetchFinishFailure>> {
        let resulting_roots = self.received.shallow_roots();
        if self.received.wants().is_empty() && self.request.shallow_before != resulting_roots {
            return Err(FetchFinishFailure::Safety(FetchPlanError::Shallow).into());
        }
        if self.request.depth.is_none() && self.request.shallow_before != resulting_roots {
            return Err(FetchFinishFailure::Safety(FetchPlanError::Shallow).into());
        }
        let shallow_lock =
            if retained || !self.request.shallow_before.is_empty() || !resulting_roots.is_empty() {
                Some(
                    super::shallow::Lock::acquire(
                        self.request.repository.common_dir(),
                        self.request.repository.object_format(),
                        &self.request.shallow_before,
                        cancel,
                    )
                    .map_err(FetchFinishFailure::Shallow)?,
                )
            } else {
                None
            };
        Ok(shallow_lock)
    }

    fn publish_installed(
        &self,
        limits: FetchUpdateLimits,
        cancel: &AtomicBool,
        shallow_lock: &mut Option<super::shallow::Lock>,
        report: &mut FetchReport,
    ) -> Result<(), Box<FetchFinishFailure>> {
        let resulting_roots = self.received.shallow_roots();
        if !self.received.wants().is_empty() && self.request.shallow_before != resulting_roots {
            let objects = self
                .request
                .repository
                .objects(limits.snapshot)
                .map_err(|error| {
                    FetchFinishFailure::BeforePublication(FetchError::Destination(error))
                })?;
            let mut verify_roots = self.received.wants().to_vec();
            verify_roots.extend(self.request.shallow_before.iter().copied());
            let verified = KnownHistory::new_with_boundaries(
                &objects,
                &verify_roots,
                resulting_roots,
                limits.verification,
                cancel,
            )
            .map_err(FetchFinishFailure::BeforePublication)?;
            if resulting_roots
                .iter()
                .any(|root| !verified.objects.contains_key(root))
            {
                return Err(FetchFinishFailure::BeforePublication(FetchError::Protocol(
                    "unrelated shallow boundary",
                ))
                .into());
            }
        }
        if let Some(lock) = shallow_lock {
            report.shallow_published = lock
                .publish(resulting_roots)
                .map_err(FetchFinishFailure::Shallow)?;
        }
        super::check_cancelled(cancel).map_err(FetchFinishFailure::BeforePublication)?;
        super::worktree::check(&self.request.repository).map_err(FetchFinishFailure::Safety)?;
        if !self.received.wants().is_empty() {
            let reopened = Repository::open(self.request.repository.git_dir())
                .map_err(FetchFinishFailure::Reopen)?;
            let objects = reopened.objects(limits.snapshot).map_err(|error| {
                FetchFinishFailure::BeforePublication(FetchError::Destination(error))
            })?;
            // Installation does not repair corrupt loose objects shadowing the pack. Read through
            // the destination's actual lookup precedence before any ref can name this graph.
            let mut verify_roots = self.received.wants().to_vec();
            verify_roots.extend(self.request.shallow_before.iter().copied());
            KnownHistory::new(&objects, &verify_roots, limits.verification, cancel)
                .map_err(FetchFinishFailure::BeforePublication)?;
            let validation = super::update::validate(
                &mut report.updates,
                &objects,
                &self.request.authorized_force,
                limits,
                cancel,
            );
            validation.map_err(FetchFinishFailure::Update)?;
        }
        super::check_cancelled(cancel).map_err(FetchFinishFailure::BeforePublication)?;
        let edits: Vec<_> = report
            .updates
            .iter()
            .filter(|update| update.kind.changes_ref())
            .map(|update| {
                let name = update
                    .mapping
                    .destination
                    .as_ref()
                    .expect("changed destination");
                RefEdit {
                    name: name.clone(),
                    dereference: false,
                    target: update
                        .mapping
                        .source
                        .as_ref()
                        .map(|source| Target::Direct(source.id)),
                    expected: update
                        .previous
                        .map(|id| Expected::Value(Target::Direct(id)))
                        .unwrap_or(Expected::Absent),
                    reflog: self.request.reflog_for(name, update.kind),
                }
            })
            .collect();
        let refs = self
            .request
            .repository
            .references()
            .map_err(FetchPlanError::from)
            .map_err(FetchFinishFailure::Safety)?;
        // Like `git fetch --prune`, prune before updating so a pruned name can become a
        // namespace for new references (or the reverse).
        let (prunes, updates): (Vec<_>, Vec<_>) =
            edits.into_iter().partition(|edit| edit.target.is_none());
        report.references = refs
            .transaction(&prunes)
            .map_err(FetchFinishFailure::Publication)?;
        match refs.transaction(&updates) {
            Ok(outcomes) => report.references.extend(outcomes),
            Err(crate::refs::TransactionError::Prepare { source, .. })
                if !report.references.is_empty() =>
            {
                return Err(Box::new(FetchFinishFailure::Publication(
                    crate::refs::TransactionError::Publish {
                        outcomes: std::mem::take(&mut report.references),
                        source,
                    },
                )));
            }
            Err(crate::refs::TransactionError::Publish {
                mut outcomes,
                source,
            }) => {
                let mut all = std::mem::take(&mut report.references);
                all.append(&mut outcomes);
                return Err(Box::new(FetchFinishFailure::Publication(
                    crate::refs::TransactionError::Publish {
                        outcomes: all,
                        source,
                    },
                )));
            }
            Err(error) => return Err(Box::new(FetchFinishFailure::Publication(error))),
        }
        Ok(())
    }
}

/// An installed pack retained through caller validation and shallow/reference publication.
///
/// Owns the same shallow lock acquired before installation. No shallow metadata, refs, or reflogs
/// have changed yet. Read [`Self::updates`] and installed objects to apply caller-specific checks,
/// then consume this phase with [`Self::finish`] or [`Self::into_recovery`]. Dropping it releases
/// the lock but deliberately leaves its Git `.keep` marker for recovery.
#[derive(Debug)]
#[must_use = "publish references or recover the retained installation explicitly"]
pub struct RetainedFetchReady {
    ready: FetchReady,
    report: FetchReport,
    limits: FetchUpdateLimits,
    shallow_lock: Option<super::shallow::Lock>,
    retention: super::FetchRetention,
}

impl RetainedFetchReady {
    /// Original planned updates, before final object-kind and ancestry validation.
    pub fn updates(&self) -> &[FetchUpdate] {
        &self.report.updates
    }

    /// Completed installation effects; shallow and reference publication have not started.
    pub fn report(&self) -> &FetchReport {
        &self.report
    }

    /// Owned pack retention, available for recording its recovery path.
    pub fn retention(&self) -> &super::FetchRetention {
        &self.retention
    }

    /// Publishes shallow boundaries and conditional refs while holding the installation's lock.
    ///
    /// Performs the same installed-object, ancestry, worktree and reference checks as
    /// [`FetchReady::finish`], without installing again or reacquiring the shallow lock.
    /// Returns retention for explicit release after persistent roots are established. Source-only
    /// callers must establish their own roots before releasing it.
    ///
    /// # Errors
    ///
    /// Returns completed installation/shallow effects, exact transaction failure details, and
    /// retention. Objects and published boundaries remain on failure; dropping the error leaves
    /// the marker intact. No rollback or retry occurs. See [`FetchReady::finish`] for the
    /// reference transaction's cancellation and partial-publication contract.
    pub fn finish(
        mut self,
        cancel: &AtomicBool,
    ) -> Result<(FetchReport, super::FetchRetention), RetainedFetchFinishError> {
        let result = self.ready.publish_installed(
            self.limits,
            cancel,
            &mut self.shallow_lock,
            &mut self.report,
        );
        match result {
            Ok(()) => Ok((self.report, self.retention)),
            Err(source) => Err(RetainedFetchFinishError {
                report: Box::new(self.report),
                source,
                retention: Some(self.retention),
            }),
        }
    }

    /// Abandons publication and releases the shallow lock, preserving effects and pack retention.
    ///
    /// No shallow metadata or references have changed. The caller can retain the returned marker
    /// while inspecting objects, or explicitly release it when abandoning the installation.
    pub fn into_recovery(self) -> (FetchReport, super::FetchRetention) {
        (self.report, self.retention)
    }
}

/// Retained workflow failure with completed effects and ownership of any acquired marker.
#[derive(Debug, thiserror::Error)]
#[error("fetch finish failed")]
pub struct RetainedFetchFinishError {
    /// Completed effects. No successful installation does not exclude partial pack artifacts.
    pub report: Box<FetchReport>,
    /// Failed phase, including exact partial reference and reflog effects on transaction failure.
    #[source]
    pub source: Box<FetchFinishFailure>,
    /// Acquired retention; dropping this error leaves its marker on disk for recovery.
    pub retention: Option<super::FetchRetention>,
}

/// One advertised source and its proposed local effect, preserving refspec order.
#[derive(Clone, Debug)]
pub struct FetchUpdate {
    /// Actual advertised source, optional destination and force intent.
    pub mapping: Mapping,
    /// Captured direct destination value, or absence (also `None` for source-only selections).
    pub previous: Option<ObjectId>,
    /// Update rule applied to the captured values.
    pub kind: FetchUpdateKind,
}

/// Decision based on the advertised identity and captured destination, before publication.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FetchUpdateKind {
    /// Objects selected without a reference destination; no `FETCH_HEAD` is written.
    SourceOnly,
    /// Destination was absent.
    Create,
    /// Destination already named the advertised ID; it will not be locked or rewritten.
    Unchanged,
    /// Remote-tracking replacement awaiting object checks; after successful finish, at least one
    /// tip does not peel to a commit, so no ancestry rule applies.
    Replace,
    /// Both tips peel to commits and the old commit is an ancestor of the new commit.
    FastForward,
    /// Non-fast-forward commit-valued remote-tracking replacement with intent and authorization.
    ForcedTracking,
    /// Explicitly authorized replacement of a tag with a forced refspec.
    ForcedTag,
    /// Delete a stale direct remote-tracking reference in the requested prune scope.
    Prune,
}
impl FetchUpdateKind {
    fn changes_ref(self) -> bool {
        matches!(
            self,
            Self::Create
                | Self::Replace
                | Self::FastForward
                | Self::ForcedTracking
                | Self::ForcedTag
                | Self::Prune
        )
    }
}

/// Transfer statistics and separately observable installation/publication effects.
#[derive(Debug)]
pub struct FetchReport {
    /// Decisions against the captured local values; not evidence of publication by themselves.
    pub updates: Vec<FetchUpdate>,
    /// Validated pack bytes, zero for an empty or known-only selection.
    pub pack_bytes: usize,
    /// Verified received objects, including extras; not a count of newly stored objects.
    pub objects: usize,
    /// Successful installation/reuse, including known-only installation with no pack.
    /// `None` on failure does not exclude an unindexed residual pack.
    pub installed: Option<FetchInstalled>,
    /// Shallow metadata was replaced after object installation, before reference publication.
    pub shallow_published: bool,
    /// Successful transaction effects for changed entries only. On transaction failure, consult
    /// [`FetchFinishFailure::Publication`] for partial effects instead.
    pub references: Vec<RefEditOutcome>,
    /// Exact positive sources absent from the advertisement; other valid selections continue.
    pub missing: Vec<Vec<u8>>,
}

/// Planning failed without changing repository contents.
#[derive(Debug, thiserror::Error)]
pub enum FetchPlanError {
    /// Received boundaries differ without an explicit depth request.
    #[error("shallow boundary change requires explicit depth request")]
    Shallow,
    /// Invalid or ambiguous advertisement/refspec mapping.
    #[error(transparent)]
    Mapping(#[from] MappingError),
    /// A destination is outside the supported remote-tracking and tag namespaces.
    #[error("unsupported fetch destination: {0:?}")]
    Destination(RefName),
    /// Updating a symbolic destination could bypass namespace rules.
    #[error("symbolic fetch destination: {0:?}")]
    Symbolic(RefName),
    /// Existing tag replacement requires both force intent and explicit name authorization.
    #[error("tag replacement requires force intent and authorization: {0:?}")]
    TagReplacement(RefName),
    /// Reference metadata could not be read.
    #[error(transparent)]
    Reference(#[from] ReferenceError),
    /// A main/linked worktree could not be opened; stale registrations fail closed.
    #[error(transparent)]
    Worktree(#[from] crate::OpenError),
    /// Worktree enumeration failed.
    #[error("worktree enumeration")]
    Io(#[from] std::io::Error),
    /// HEAD or its symbolic branch chain escapes the protected branch namespace.
    #[error("unsupported HEAD chain at {0:?}")]
    Head(RefName),
}

/// A failure before any installation or reference publication.
#[derive(Debug, thiserror::Error)]
pub enum FetchWorkflowError {
    /// Mapping or destination policy rejected the actual advertisement.
    #[error(transparent)]
    Plan(#[from] FetchPlanError),
    /// Transfer or synchronous validation failed, with no installed objects.
    #[error(transparent)]
    Transfer(#[from] FetchError),
}

/// Installation/publication failure retaining completed effects.
#[derive(Debug, thiserror::Error)]
#[error("fetch finish failed")]
pub struct FetchFinishError {
    /// Transfer and installation effects before failure; installed objects are never rolled back.
    pub report: Box<FetchReport>,
    /// Failed phase, including the existing transaction's partial-effect contract.
    /// Boxed to keep the returned error compact across platforms.
    #[source]
    pub source: Box<FetchFinishFailure>,
}

/// Failed phase after validated transfer.
#[derive(Debug, thiserror::Error)]
pub enum FetchFinishFailure {
    /// Installation failed; refs unchanged, possibly leaving an unindexed pack.
    #[error("fetch installation")]
    Installation(#[source] FetchError),
    /// Shallow lock, snapshot comparison, or metadata publication failed.
    #[error("fetch shallow publication")]
    Shallow(#[from] super::FetchShallowError),
    /// Repository could not be reopened with freshly published shallow boundaries.
    #[error("fetch repository reopen")]
    Reopen(#[from] crate::OpenError),
    /// Cancellation or installed-object verification failed before the reference transaction.
    #[error("before fetch publication")]
    BeforePublication(#[source] FetchError),
    /// Worktree/HEAD safety recheck failed after installation; refs unchanged.
    #[error("fetch publication safety")]
    Safety(#[from] FetchPlanError),
    /// Object-kind/ancestry validation or update authorization failed; installed objects remain,
    /// but no refs have changed.
    #[error("fetch update validation")]
    Update(#[from] super::FetchUpdateError),
    /// Exact transaction preparation or partial publication failure; objects remain installed.
    #[error("fetch reference publication")]
    Publication(#[from] crate::refs::TransactionError),
}

#[cfg(test)]
#[path = "workflow_tests.rs"]
mod tests;