Skip to main content

brygge_decode_git/
decode.rs

1//! The decode orchestration (RFC 004 D-2/D-3/D-5): read a Git object database and build a
2//! [`brygge_ir::Ir`], entirely *Stated* except opt-in marked-*Derived* copy records. Every object read
3//! — commit, tree, blob, annotated tag — is re-hashed against its claimed id before use (batch-2 handoff
4//! §1.1, RFC 004 batch-2 corrections).
5//!
6//! History is walked **parent-first** (an atom's `AtomId` is computed from its parents' `AtomId`s), and
7//! per-commit path operations are computed by diffing full tree **snapshots** (child against first
8//! parent) — auditable, deterministic, and explicit about modes and submodules.
9
10use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::path::Path;
12
13use gix::ObjectId;
14use gix::bstr::ByteSlice;
15
16use brygge_ir::builder::{AtomDraft, IrBuilder};
17use brygge_ir::model::{
18    Annotation, AtomId, CopyRecord, DropRecord, Extra, Identity, ImportProvenance, Ir,
19    LossBoundary, LossClass, MetadataClaims, PathOp, RefKind, RefRecord, Signature, SourceIdentity,
20    SourceKind, Text, Time,
21};
22use brygge_ir::status::{Derivation, DerivationKind, EpistemicStatus};
23
24use crate::{Error, Options, decoder_version, floor, open};
25
26/// The full path → (blob/link/gitlink object id, mode) contents of a tree.
27type Snapshot = BTreeMap<String, (ObjectId, u32)>;
28
29/// An annotated tag's opaque object id, any signatures, and its tagger/time/message, preserved in a ref's
30/// `source`/`annotation` (`PR-4`, batch-2 handoff §1.6).
31type TagIdentity = (ObjectId, Vec<Signature>, Option<Annotation>);
32
33const DECODER: &str = "brygge-decode-git";
34
35/// Resource ceilings (RFC 010 D-4). One place for every Git ceiling; tests construct a small instance
36/// instead of needing gigabytes.
37#[derive(Debug, Clone, Copy)]
38pub(crate) struct Limits {
39    /// The maximum size of one blob, checked from the object **header** (no inflation) before it is
40    /// read.
41    pub(crate) max_blob_bytes: u64,
42    /// The maximum number of commits imported from one repository, checked during the walk, before any
43    /// atom is built.
44    pub(crate) max_commits: u64,
45    /// The maximum length of one path, checked while walking trees.
46    pub(crate) max_path_bytes: usize,
47    /// The maximum tree nesting depth, checked while walking trees (`walk_tree` is iterative — an
48    /// explicit stack — precisely so a deep tree cannot overflow the process stack; RFC 010 CR-10).
49    pub(crate) max_tree_depth: usize,
50    /// The maximum number of tag objects peeled through for one ref (a tag pointing at a tag, and so
51    /// on), checked while peeling (batch-2 handoff §1.1, review 011 R-2) — an attacker-chosen chain of
52    /// tag objects cannot force unbounded verified reads for one ref.
53    pub(crate) max_tag_chain: usize,
54}
55
56impl Default for Limits {
57    fn default() -> Self {
58        Self {
59            max_blob_bytes: 1024 * 1024 * 1024,
60            max_commits: 10_000_000,
61            max_path_bytes: 4096,
62            max_tree_depth: 256,
63            max_tag_chain: 32,
64        }
65    }
66}
67
68fn resource_limit(what: &str, ceiling: impl std::fmt::Display) -> Error {
69    Error::ResourceLimit {
70        what: what.to_string(),
71        ceiling: ceiling.to_string(),
72    }
73}
74
75fn read_err(e: impl std::fmt::Display) -> Error {
76    Error::Read(e.to_string())
77}
78
79/// Look up `id` and verify its content actually hashes to it, before returning it (batch-2 handoff §1.1,
80/// PR-4/VF-2): a crafted or corrupt repository must not be able to present content under an id it does
81/// not hash to, with brygge then preserving that lie as the source's own identifier. Used at every site
82/// that reads a commit, tree, blob, or annotated tag object — the entire object-read surface of this
83/// decoder goes through here.
84fn find_verified_object(repo: &gix::Repository, id: ObjectId) -> Result<gix::Object<'_>, Error> {
85    let object = repo.find_object(id).map_err(read_err)?;
86    let computed =
87        gix::objs::compute_hash(repo.object_hash(), object.kind, &object.data).map_err(read_err)?;
88    if computed != id {
89        return Err(Error::Read(format!(
90            "object {id} does not match its content (corrupt or crafted repository)"
91        )));
92    }
93    Ok(object)
94}
95
96/// Render `bytes` as valid UTF-8 kept verbatim and each invalid byte escaped as `\xNN` — never
97/// `to_str_lossy`'s `U+FFFD` substitution, which would silently alter the bytes a refusal message
98/// names (D-3(i), CR-03).
99fn escape_invalid_utf8(bytes: &[u8]) -> String {
100    use std::fmt::Write as _;
101    let mut out = String::with_capacity(bytes.len());
102    let mut rest = bytes;
103    loop {
104        match std::str::from_utf8(rest) {
105            Ok(valid) => {
106                out.push_str(valid);
107                break;
108            }
109            Err(e) => {
110                let valid_up_to = e.valid_up_to();
111                let valid_prefix = rest.get(..valid_up_to).unwrap_or(&[]);
112                out.push_str(std::str::from_utf8(valid_prefix).unwrap_or_default());
113                let bad_len = e.error_len().unwrap_or(rest.len() - valid_up_to).max(1);
114                let bad_end = (valid_up_to + bad_len).min(rest.len());
115                for &b in rest.get(valid_up_to..bad_end).unwrap_or(&[]) {
116                    let _ = write!(out, "\\x{b:02X}");
117                }
118                rest = rest.get(bad_end..).unwrap_or(&[]);
119                if rest.is_empty() {
120                    break;
121                }
122            }
123        }
124    }
125    out
126}
127
128/// Decode the Git repository at `path` into an [`Ir`] under `opts`.
129///
130/// # Errors
131/// [`Error::Open`] if the path is not a readable repository; [`Error::FloorRefusal`] on a refused source
132/// feature (submodule, grafts, shallow, replace ref — RFC 004 D-4); [`Error::Read`] on a malformed
133/// object; [`Error::ResourceLimit`] on a resource ceiling (RFC 010); [`Error::Ir`] if the assembled IR
134/// violates an invariant.
135pub fn decode(path: &Path, opts: &Options) -> Result<Ir, Error> {
136    decode_with(path, opts, &Limits::default())
137}
138
139pub(crate) fn decode_with(path: &Path, opts: &Options, limits: &Limits) -> Result<Ir, Error> {
140    let repo = open::open(path)?;
141    open::check_repo_floor(&repo)?;
142
143    let (refs, symbolic_ref_count, nested_tag_objects, tagger_time_counts) =
144        scan_refs(&repo, limits)?;
145
146    // CR-05: walk tips come only from carried refs (non-symbolic refs/heads/* and refs/tags/*,
147    // a tag peeled to its commit). Compute this set first — before anything is read for atoms —
148    // so a commit reachable only from a dropped namespace (refs/remotes/*, refs/notes/*,
149    // refs/stash, ...) is never read as history. RFC 010: the commit count is bounded here, during
150    // the walk, before any atom is built.
151    let carried_tips: Vec<ObjectId> = refs
152        .iter()
153        .filter(|r| matches!(r.kind, ScannedKind::Branch(_) | ScannedKind::Tag(_)))
154        .filter_map(|r| r.commit)
155        .collect();
156    let mut set: BTreeSet<ObjectId> = BTreeSet::new();
157    if !carried_tips.is_empty() {
158        for info in repo
159            .rev_walk(carried_tips.clone())
160            // batch-2 handoff §1.1 (review 011 R-1): the commit-graph is an unverified cache of parent
161            // ids. Walking from it, not from the verified commit objects, would let a crafted
162            // `objects/info/commit-graph` drop or fabricate a parent, silently altering history that
163            // object-level verification alone could never see.
164            .use_commit_graph(false)
165            .all()
166            .map_err(read_err)?
167        {
168            set.insert(info.map_err(read_err)?.id);
169            if set.len() as u64 > limits.max_commits {
170                return Err(resource_limit(
171                    "the commit count",
172                    format!("{} commits", limits.max_commits),
173                ));
174            }
175        }
176    }
177
178    // The count for the loss record only: commits reachable only from a dropped-namespace ref.
179    // `.with_hidden(carried_tips)` paints every carried-reachable commit as unwanted, so the walk
180    // visits dropped-only commits without re-walking the shared history. This is a *count*, not a
181    // requirement (RFC 004 R-2, 2026-09-23 review of this handoff): it reads commit headers only —
182    // never a tree or blob, and nothing it finds becomes an atom — and it never fails the decode. A
183    // broken commit in dropped-only history (e.g. a corrupt stash) makes the count unavailable, not
184    // the decode.
185    let dropped_tips: Vec<ObjectId> = refs
186        .iter()
187        .filter(|r| matches!(r.kind, ScannedKind::Dropped(_)))
188        .filter_map(|r| r.commit)
189        .collect();
190    let dropped_only_commits = count_dropped_only_commits(&repo, dropped_tips, carried_tips);
191
192    let parents = commit_parents(&repo, &set)?;
193    let order = parent_first_order(&set, &parents)?;
194
195    // Repo fingerprint: the smallest root-commit id (content-stable → deterministic, RFC 004 D-2).
196    let repo_id = order
197        .iter()
198        .filter(|id| parents.get(*id).is_none_or(Vec::is_empty))
199        .min()
200        .map(|id| id.as_bytes().to_vec())
201        .unwrap_or_default();
202
203    let provenance = ImportProvenance {
204        source: SourceIdentity {
205            kind: SourceKind::Git,
206            repo_id: repo_id.clone(),
207            atom_id: repo_id.clone(),
208            signatures: Vec::new(),
209            extras: Vec::new(),
210        },
211        brygge_version: decoder_version().to_string(),
212        decoder: DECODER.to_string(),
213        decoder_version: decoder_version().to_string(),
214        params: {
215            let mut params = opts.as_params();
216            params.insert("floor".to_string(), floor::joined());
217            params
218        },
219    };
220
221    let mut builder = IrBuilder::new(provenance);
222    let mut sha_to_atom: HashMap<ObjectId, AtomId> = HashMap::new();
223    // RFC 010 increment 5: know each root tree's uses up front, so a snapshot is dropped after its last one.
224    let mut snap_cache = SnapshotCache::new(count_snapshot_uses(&repo, &order, &parents));
225    let mut time_counts = ParseCounts::default();
226
227    for id in &order {
228        let commit = find_verified_object(&repo, *id)?
229            .try_into_commit()
230            .map_err(read_err)?;
231
232        let child_tree = commit.tree_id().map_err(read_err)?.detach();
233        let child_snap = snapshot(&repo, child_tree, *id, limits, &mut snap_cache)?;
234
235        let ps = parents.get(id).cloned().unwrap_or_default();
236        let mut base_tree: Option<ObjectId> = None;
237        let base_snap = match ps.first() {
238            Some(p0) => {
239                let p_commit = find_verified_object(&repo, *p0)?
240                    .try_into_commit()
241                    .map_err(read_err)?;
242                let p_tree = p_commit.tree_id().map_err(read_err)?.detach();
243                base_tree = Some(p_tree);
244                snapshot(&repo, p_tree, *p0, limits, &mut snap_cache)?
245            }
246            None => Snapshot::new(),
247        };
248
249        let parent_atoms: Vec<AtomId> = ps
250            .iter()
251            .filter_map(|p| sha_to_atom.get(p).copied())
252            .collect();
253        let (ops, copies) = diff_to_ops(
254            &repo,
255            &base_snap,
256            &child_snap,
257            opts,
258            limits,
259            &mut builder,
260            parent_atoms.first().copied(),
261        )?;
262        // This commit's uses of its two snapshots are done: drop each whose last use this was.
263        snap_cache.release(child_tree);
264        if let Some(t) = base_tree {
265            snap_cache.release(t);
266        }
267        let (metadata, counts) = build_metadata(&commit)?;
268        time_counts.unparseable_times += counts.unparseable_times;
269        time_counts.unparseable_offsets += counts.unparseable_offsets;
270        time_counts.undecodable_encodings += counts.undecodable_encodings;
271        let (signatures, extras) = signatures_and_extras(&commit, *id)?;
272
273        let atom_id = builder.add_atom(AtomDraft {
274            parents: parent_atoms,
275            ops,
276            copies,
277            metadata,
278            source: SourceIdentity {
279                kind: SourceKind::Git,
280                repo_id: repo_id.clone(),
281                atom_id: id.as_bytes().to_vec(),
282                signatures,
283                extras,
284            },
285            status: EpistemicStatus::Stated,
286        })?;
287        sha_to_atom.insert(*id, atom_id);
288    }
289
290    // Refs, the dropped-namespace loss records, and annotated-tag identity preservation (OQ-B).
291    let mut dropped_namespace_counts: BTreeMap<&'static str, u64> = BTreeMap::new();
292    let mut non_commit_refs = 0u64;
293    for r in &refs {
294        match &r.kind {
295            ScannedKind::Branch(name) => {
296                match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
297                    Some(target) => {
298                        builder.add_ref(RefRecord {
299                            name: name.clone(),
300                            kind: RefKind::Branch,
301                            target,
302                            status: EpistemicStatus::Stated,
303                            source: None,
304                            annotation: None,
305                        })?;
306                    }
307                    // CR-06: peeled to a tree or blob, not a commit — recorded, not silently skipped.
308                    None => non_commit_refs += 1,
309                }
310            }
311            ScannedKind::Tag(name) => match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
312                Some(target) => {
313                    // An annotated tag preserves its own opaque object id + signature (PR-4/SRC-G3) as
314                    // `source`, and its tagger/time/message as `annotation` (RFC 011 D-9, batch-2
315                    // handoff §1.6) — nothing about it is lost any more.
316                    let (source, annotation) = match &r.tag_identity {
317                        Some((tag_id, signatures, annotation)) => (
318                            Some(SourceIdentity {
319                                kind: SourceKind::Git,
320                                repo_id: repo_id.clone(),
321                                atom_id: tag_id.as_bytes().to_vec(),
322                                signatures: signatures.clone(),
323                                extras: Vec::new(),
324                            }),
325                            annotation.clone(),
326                        ),
327                        None => (None, None),
328                    };
329                    builder.add_ref(RefRecord {
330                        name: name.clone(),
331                        kind: RefKind::Tag,
332                        target,
333                        status: EpistemicStatus::Stated,
334                        source,
335                        annotation,
336                    })?;
337                }
338                // CR-06: peeled to a tree or blob, not a commit — recorded, not silently skipped.
339                None => non_commit_refs += 1,
340            },
341            ScannedKind::Dropped(ns) => {
342                *dropped_namespace_counts.entry(ns).or_insert(0) += 1;
343            }
344        }
345    }
346
347    time_counts.unparseable_times += tagger_time_counts.unparseable_times;
348    time_counts.unparseable_offsets += tagger_time_counts.unparseable_offsets;
349
350    builder.set_loss(loss_boundary(
351        &dropped_namespace_counts,
352        dropped_only_commits,
353        non_commit_refs,
354        symbolic_ref_count,
355        time_counts,
356        nested_tag_objects,
357    ));
358    builder.finish().map_err(Error::Ir)
359}
360
361/// The result of sizing the "commits reachable only from dropped refs" loss record (CR-05).
362enum DroppedOnlyCommits {
363    /// The exact count.
364    Counted(u64),
365    /// The walk itself failed (e.g. a corrupt or missing commit in dropped-only history); the count is
366    /// unknown rather than guessed. The record this becomes carries a **fixed** reason (batch-2 handoff
367    /// §1.2, review 011 R-4): the underlying error's own text is not carried anywhere. A decoder library
368    /// does not write to the process's stderr — that would bypass the CLI's neutralization
369    /// (`crates/brygge/src/display.rs`) — so the fixed drop record is the whole diagnostic a caller
370    /// gets; `git fsck` is how a human investigates the fault directly.
371    Unavailable,
372}
373
374/// Count commits reachable only from `dropped_tips`, never `carried_tips` (CR-05). This never fails the
375/// decode (2026-09-23 review R-2 of this handoff): any error during the walk — setup or iteration —
376/// becomes [`DroppedOnlyCommits::Unavailable`] instead of propagating, since this is a loss-record count,
377/// not a requirement for the decode to succeed. The underlying error's own text is discarded, never
378/// printed (review 011 R-4): it is not deterministic (it can include object ids, allocator state), never
379/// identity-bearing, and printing it would be this decoder's only unneutralized output.
380fn count_dropped_only_commits(
381    repo: &gix::Repository,
382    dropped_tips: Vec<ObjectId>,
383    carried_tips: Vec<ObjectId>,
384) -> DroppedOnlyCommits {
385    if dropped_tips.is_empty() {
386        return DroppedOnlyCommits::Counted(0);
387    }
388    let Ok(walk) = repo
389        .rev_walk(dropped_tips)
390        .with_hidden(carried_tips)
391        .use_commit_graph(false)
392        .all()
393    else {
394        return DroppedOnlyCommits::Unavailable;
395    };
396    let mut count = 0u64;
397    for info in walk {
398        if info.is_err() {
399            return DroppedOnlyCommits::Unavailable;
400        }
401        count += 1;
402    }
403    DroppedOnlyCommits::Counted(count)
404}
405
406/// A ref as scanned, categorised, and peeled.
407struct ScannedRef {
408    kind: ScannedKind,
409    /// The commit it (ultimately) points at, if any.
410    commit: Option<ObjectId>,
411    /// For an **annotated** tag: the tag object's own id and any signature (`PR-4`/`SRC-G3`), preserved
412    /// opaquely in the ref's `source`. `None` for branches and lightweight tags.
413    tag_identity: Option<TagIdentity>,
414}
415
416enum ScannedKind {
417    Branch(String),
418    Tag(String),
419    Dropped(&'static str),
420}
421
422const HEADS_PREFIX: &[u8] = b"refs/heads/";
423const TAGS_PREFIX: &[u8] = b"refs/tags/";
424
425/// Scan refs: refuse replace refs (RFC 004 D-4), categorise the rest, and peel each to a commit id.
426/// Returns the carried refs, a count of symbolic refs skipped (CR-16), a count of intermediate tag
427/// objects hopped through in any tag-of-a-tag chain (batch-2 handoff §1.1, review 011 R-2), and how many
428/// of any annotated tags' own tagger time/offset fields failed to parse (review 011 R-3a).
429fn scan_refs(
430    repo: &gix::Repository,
431    limits: &Limits,
432) -> Result<(Vec<ScannedRef>, u64, u64, ParseCounts), Error> {
433    let mut out = Vec::new();
434    let mut symbolic_refs = 0u64;
435    let mut nested_tag_objects = 0u64;
436    let mut tagger_time_counts = ParseCounts::default();
437    let platform = repo.references().map_err(read_err)?;
438    for r in platform.all().map_err(read_err)? {
439        let mut r = r.map_err(read_err)?;
440        let raw_name: Vec<u8> = r.name().as_bstr().to_vec();
441        let name = raw_name.to_str_lossy(); // lossy conversion is safe here: `name` is only used for the
442        // `refs/replace/` prefix check and dropped-namespace matching below, both ASCII.
443
444        if raw_name.starts_with(b"refs/replace/") {
445            return Err(Error::FloorRefusal {
446                feature: floor::REPLACE_REF.to_string(),
447                reason: format!(
448                    "{} rewrites the object graph a reader would see; refused rather than \
449                     importing the rewritten view silently",
450                    escape_invalid_utf8(&raw_name)
451                ),
452            });
453        }
454
455        // A symbolic ref (e.g. `refs/remotes/origin/HEAD`) is an alias to another ref, in any
456        // namespace; the IR has no alias concept (RFC 004 OQ-B, CR-16). `try_id()` is `None` exactly
457        // when the ref's own stored form is symbolic — including a *dangling* symbolic ref, whose
458        // target does not exist, since this reflects the ref's own shape, not whether it resolves.
459        // gix's `id()` panics on this case; `try_id()` is the fallible form. Skip it: it contributes no
460        // walk tip and is not carried as a ref. Its target, if any, is a distinct ref that `platform.all()`
461        // yields on its own and this same loop carries or drops on its own merits.
462        let Some(direct) = r.try_id().map(|id| id.detach()) else {
463            symbolic_refs += 1;
464            continue;
465        };
466
467        // CR-03/D-3(i): a carried ref's name (after its namespace prefix) must be valid UTF-8, never
468        // converted lossily. Namespace classification itself only compares the ASCII prefix bytes, so
469        // it is unaffected by what follows.
470        let carried_suffix: Option<(&[u8], bool)> = if raw_name.starts_with(HEADS_PREFIX) {
471            Some((raw_name.get(HEADS_PREFIX.len()..).unwrap_or(&[]), true))
472        } else if raw_name.starts_with(TAGS_PREFIX) {
473            Some((raw_name.get(TAGS_PREFIX.len()..).unwrap_or(&[]), false))
474        } else {
475            None
476        };
477        if let Some((suffix, _)) = carried_suffix {
478            if std::str::from_utf8(suffix).is_err() {
479                return Err(Error::FloorRefusal {
480                    feature: floor::NON_UTF8_REF_NAME.to_string(),
481                    reason: format!(
482                        "ref name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
483                        escape_invalid_utf8(&raw_name)
484                    ),
485                });
486            }
487        }
488
489        let mut tag_identity = None;
490        let (kind, commit) = if let Some((suffix, is_branch)) = carried_suffix {
491            // Checked valid UTF-8 just above.
492            let suffix_str = std::str::from_utf8(suffix).unwrap_or_default().to_string();
493            if is_branch {
494                // A branch carries no annotation, so a tag object it points at (via `update-ref`) has its
495                // tagger/message/signature dropped: every hop is counted (review 011 F-2).
496                let (commit, nested) = peel_carried(repo, direct, limits, false)?;
497                nested_tag_objects += nested;
498                (ScannedKind::Branch(suffix_str), commit)
499            } else {
500                let (identity, counts) = annotated_tag_identity(repo, direct)?;
501                tag_identity = identity;
502                tagger_time_counts.unparseable_times += counts.unparseable_times;
503                tagger_time_counts.unparseable_offsets += counts.unparseable_offsets;
504                let (commit, nested) = peel_carried(repo, direct, limits, true)?;
505                nested_tag_objects += nested;
506                (ScannedKind::Tag(suffix_str), commit)
507            }
508        } else {
509            // Dropped namespaces are peeled leniently: they contribute no atom and no hard error, only
510            // (optionally) a count of commits reachable only from them (CR-05).
511            let dropped_kind = if name.starts_with("refs/remotes/") {
512                ScannedKind::Dropped("remote-tracking")
513            } else if name.starts_with("refs/notes/") {
514                ScannedKind::Dropped("notes")
515            } else if name == "refs/stash" {
516                ScannedKind::Dropped("stash")
517            } else {
518                // HEAD and any other odd ref namespace: not authored history.
519                ScannedKind::Dropped("other")
520            };
521            let lenient_commit = r.peel_to_id().ok().map(|id| id.detach()).filter(|id| {
522                repo.find_object(*id)
523                    .is_ok_and(|o| matches!(o.kind, gix::objs::Kind::Commit))
524            });
525            (dropped_kind, lenient_commit)
526        };
527        out.push(ScannedRef {
528            kind,
529            commit,
530            tag_identity,
531        });
532    }
533    Ok((out, symbolic_refs, nested_tag_objects, tagger_time_counts))
534}
535
536/// Peel a `refs/heads/*` or `refs/tags/*` ref to its commit (CR-06), verifying **every** object on the
537/// way — including any intermediate tag in a tag-of-a-tag chain (batch-2 handoff §1.1, review 011 R-2).
538/// A ref whose target is missing entirely, or a chain longer than `limits.max_tag_chain`, is refused. A
539/// chain that ends at a tree or blob gives `None` — the caller counts it as a non-commit-target ref
540/// rather than silently skipping it. Returns the number of tag objects hopped through whose data is not
541/// carried. For a `refs/tags/*` ref (`direct_tag_is_carried`), the outer (`direct`) tag itself is carried as
542/// the ref's annotation by [`annotated_tag_identity`], so only *intermediate* tags count (an ordinary
543/// annotated tag pointing at a commit has zero). A branch carries no annotation, so for it every tag hop
544/// counts (review 011 F-2).
545fn peel_carried(
546    repo: &gix::Repository,
547    direct: ObjectId,
548    limits: &Limits,
549    direct_tag_is_carried: bool,
550) -> Result<(Option<ObjectId>, u64), Error> {
551    let mut current = direct;
552    let mut hops = 0usize;
553    let mut nested_tags = 0u64;
554    loop {
555        let object = find_verified_object(repo, current)?;
556        match object.kind {
557            gix::objs::Kind::Commit => return Ok((Some(current), nested_tags)),
558            gix::objs::Kind::Tag => {
559                hops += 1;
560                if hops > limits.max_tag_chain {
561                    return Err(resource_limit(
562                        "the tag chain",
563                        format!("{} tag(s)", limits.max_tag_chain),
564                    ));
565                }
566                if hops > 1 || !direct_tag_is_carried {
567                    nested_tags += 1;
568                }
569                let tag = object.try_into_tag().map_err(read_err)?;
570                let decoded = tag.decode().map_err(read_err)?;
571                current = decoded.target();
572            }
573            _ => return Ok((None, nested_tags)),
574        }
575    }
576}
577
578/// If `direct` is an **annotated** tag object, return its id, any GPG signature (preserved opaquely,
579/// `PR-4`/`SRC-G3` — the tag verifies nothing in any target, but is the cryptographic link back to the
580/// source), and its tagger/time/message as an [`Annotation`] (batch-2 handoff §1.6), plus how many of the
581/// tagger's time/offset fields failed to parse (review 011 R-3a — counted exactly like author/committer
582/// times, never silently dropped). Returns `None` (with zero counts) for a lightweight tag, whose direct
583/// target is the commit itself — one verified read decides which (review 011 R-5: no separate, unverified
584/// pre-check).
585fn annotated_tag_identity(
586    repo: &gix::Repository,
587    direct: ObjectId,
588) -> Result<(Option<TagIdentity>, ParseCounts), Error> {
589    let object = find_verified_object(repo, direct)?;
590    if !matches!(object.kind, gix::objs::Kind::Tag) {
591        return Ok((None, ParseCounts::default()));
592    }
593    let tag = object.try_into_tag().map_err(read_err)?;
594    let decoded = tag.decode().map_err(read_err)?;
595    let signatures = decoded
596        .signature
597        .map(|s| Signature {
598            label: "gpgsig".to_string(),
599            bytes: s.to_vec(),
600        })
601        .into_iter()
602        .collect();
603    let mut counts = ParseCounts::default();
604    let tagger_sig = decoded.tagger().map_err(read_err)?;
605    let tagger = tagger_sig.map(|sig| Identity {
606        name: Text {
607            bytes: sig.name.to_vec(),
608            encoding: None,
609        },
610        email: Some(Text {
611            bytes: sig.email.to_vec(),
612            encoding: None,
613        }),
614    });
615    let time = tagger_sig.and_then(|sig| {
616        let seconds = strict_seconds(sig.time);
617        if seconds.is_none() {
618            counts.unparseable_times += 1;
619        }
620        seconds.map(|seconds| {
621            let offset_minutes = strict_offset_minutes(sig.time);
622            if offset_minutes.is_none() {
623                counts.unparseable_offsets += 1;
624            }
625            Time {
626                seconds,
627                offset_minutes,
628            }
629        })
630    });
631    let message = Text {
632        bytes: decoded.message.to_vec(),
633        encoding: None,
634    };
635    let annotation = Annotation {
636        tagger,
637        time,
638        message: Some(message),
639    };
640    Ok((Some((direct, signatures, Some(annotation))), counts))
641}
642
643/// Map each commit to its parents, all of which must be within `set` (batch-2 handoff §1.1, review 011
644/// R-1). `set` was built by walking the *full* ancestry from the carried tips with the commit-graph
645/// disabled, so every parent a verified commit actually names must also be in `set` — a shallow
646/// repository or one using grafts is already refused before this runs (`open::check_repo_floor`). A
647/// verified parent that the walk did not reach means the walk and the commit content disagree, which a
648/// crafted or corrupt repository could otherwise use to hide or fabricate history; that is refused
649/// outright rather than silently treating the commit as a root.
650fn commit_parents(
651    repo: &gix::Repository,
652    set: &BTreeSet<ObjectId>,
653) -> Result<BTreeMap<ObjectId, Vec<ObjectId>>, Error> {
654    let mut parents = BTreeMap::new();
655    for id in set {
656        let commit = find_verified_object(repo, *id)?
657            .try_into_commit()
658            .map_err(read_err)?;
659        let mut ps = Vec::new();
660        for p in commit.parent_ids() {
661            let p = p.detach();
662            if !set.contains(&p) {
663                return Err(Error::Read(
664                    "history walk disagrees with commit content".to_string(),
665                ));
666            }
667            ps.push(p);
668        }
669        parents.insert(*id, ps);
670    }
671    Ok(parents)
672}
673
674/// Deterministic parent-first order: Kahn's algorithm with the ready set ordered by object id.
675fn parent_first_order(
676    set: &BTreeSet<ObjectId>,
677    parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
678) -> Result<Vec<ObjectId>, Error> {
679    let mut indeg: BTreeMap<ObjectId, usize> = set.iter().map(|id| (*id, 0usize)).collect();
680    let mut children: BTreeMap<ObjectId, Vec<ObjectId>> = BTreeMap::new();
681    for (id, ps) in parents {
682        for p in ps {
683            children.entry(*p).or_default().push(*id);
684            if let Some(d) = indeg.get_mut(id) {
685                *d += 1;
686            }
687        }
688    }
689    let mut ready: BTreeSet<ObjectId> = indeg
690        .iter()
691        .filter_map(|(id, d)| (*d == 0).then_some(*id))
692        .collect();
693    let mut order = Vec::with_capacity(set.len());
694    while let Some(id) = ready.iter().next().copied() {
695        ready.remove(&id);
696        order.push(id);
697        if let Some(kids) = children.get(&id) {
698            for kid in kids {
699                if let Some(d) = indeg.get_mut(kid) {
700                    *d = d.saturating_sub(1);
701                    if *d == 0 {
702                        ready.insert(*kid);
703                    }
704                }
705            }
706        }
707    }
708    if order.len() != set.len() {
709        return Err(Error::Read(
710            "commit graph contains a cycle (a Git history must be acyclic)".to_string(),
711        ));
712    }
713    Ok(order)
714}
715
716/// The snapshots of the root trees the decode still needs, each kept **only while a commit still to be
717/// processed will use it** (RFC 010 increment 5).
718///
719/// A commit's diff uses two snapshots: its own tree's and its **first** parent's tree's, nothing else reads
720/// the cache. Commits are processed parent-first, so the number of uses of each root tree is known before the
721/// loop starts ([`count_snapshot_uses`]); each use [`release`](Self::release)s the tree, and a snapshot is
722/// dropped when its last use is done. Identical trees share one entry and one count (the key is the tree id),
723/// so a tree that a later commit reverts to stays cached until that commit has been processed. The cache then
724/// holds the frontier of the parent-first order, not one snapshot per commit.
725///
726/// It only ever changes what is *kept*: a snapshot that is needed but not cached is rebuilt by the same walk,
727/// so the output cannot depend on the bookkeeping.
728struct SnapshotCache {
729    snaps: HashMap<ObjectId, Snapshot>,
730    /// The uses still to come of each tree. A tree without an entry (its use could not be counted) is never
731    /// evicted.
732    remaining: HashMap<ObjectId, usize>,
733}
734
735impl SnapshotCache {
736    fn new(uses: HashMap<ObjectId, usize>) -> Self {
737        Self {
738            snaps: HashMap::new(),
739            remaining: uses,
740        }
741    }
742
743    /// The snapshot of `tree_id`, from the cache or built by `build` (and then cached).
744    fn get_or_build(
745        &mut self,
746        tree_id: ObjectId,
747        build: impl FnOnce() -> Result<Snapshot, Error>,
748    ) -> Result<Snapshot, Error> {
749        if let Some(s) = self.snaps.get(&tree_id) {
750            return Ok(s.clone());
751        }
752        let out = build()?;
753        self.snaps.insert(tree_id, out.clone());
754        Ok(out)
755    }
756
757    /// One use of `tree_id` is done: evict its snapshot when no use remains.
758    fn release(&mut self, tree_id: ObjectId) {
759        if let Some(n) = self.remaining.get_mut(&tree_id) {
760            *n = n.saturating_sub(1);
761            if *n == 0 {
762                self.remaining.remove(&tree_id);
763                self.snaps.remove(&tree_id);
764            }
765        }
766    }
767
768    /// How many snapshots are held now.
769    #[cfg(test)]
770    fn len(&self) -> usize {
771        self.snaps.len()
772    }
773}
774
775/// Count, for every root tree, how many times the decode loop will ask for its snapshot: once per commit for
776/// the commit's own tree, and once more for its **first** parent's tree when it has one (`decode`'s loop is
777/// the only reader). Reads each commit once; a commit that cannot be read is not counted (its trees stay
778/// cached, and the loop reports the failure at that commit exactly as before, so error order is unchanged).
779fn count_snapshot_uses(
780    repo: &gix::Repository,
781    order: &[ObjectId],
782    parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
783) -> HashMap<ObjectId, usize> {
784    let mut tree_of: HashMap<ObjectId, ObjectId> = HashMap::with_capacity(order.len());
785    let mut uses: HashMap<ObjectId, usize> = HashMap::new();
786    for id in order {
787        let Some(tree) = find_verified_object(repo, *id)
788            .ok()
789            .and_then(|o| o.try_into_commit().ok())
790            .and_then(|c| c.tree_id().ok())
791            .map(gix::Id::detach)
792        else {
793            continue;
794        };
795        tree_of.insert(*id, tree);
796        *uses.entry(tree).or_insert(0) += 1;
797        if let Some(p0) = parents.get(id).and_then(|ps| ps.first()) {
798            if let Some(pt) = tree_of.get(p0) {
799                *uses.entry(*pt).or_insert(0) += 1;
800            }
801        }
802    }
803    uses
804}
805
806/// Build the full path→(oid,mode) snapshot of a tree, caching it while it is still needed. A gitlink
807/// (submodule) entry is a floor refusal (RFC 004 D-4).
808fn snapshot(
809    repo: &gix::Repository,
810    tree_id: ObjectId,
811    commit_id: ObjectId,
812    limits: &Limits,
813    cache: &mut SnapshotCache,
814) -> Result<Snapshot, Error> {
815    cache.get_or_build(tree_id, || {
816        let mut out = Snapshot::new();
817        walk_tree(repo, tree_id, commit_id, limits, &mut out)?;
818        Ok(out)
819    })
820}
821
822/// Walk a tree into a flat path→(oid,mode) snapshot, **iteratively** (RFC 010 CR-10): an explicit stack,
823/// not recursion, so an attacker-chosen tree depth cannot overflow the process stack — which no
824/// `catch_unwind` boundary (CR-16's `guard_decoder`) can contain. `max_tree_depth` and `max_path_bytes`
825/// are enforced as the stack grows; the resulting snapshot is identical to a recursive walk's (the
826/// traversal order differs, but `out` is a flat, order-independent map of full paths).
827fn walk_tree(
828    repo: &gix::Repository,
829    root_tree_id: ObjectId,
830    commit_id: ObjectId,
831    limits: &Limits,
832    out: &mut Snapshot,
833) -> Result<(), Error> {
834    // (tree id, path prefix built so far, this tree's own nesting depth; the root is depth 1).
835    let mut stack: Vec<(ObjectId, String, usize)> = vec![(root_tree_id, String::new(), 1)];
836    while let Some((tree_id, prefix, depth)) = stack.pop() {
837        let tree = find_verified_object(repo, tree_id)?
838            .try_into_tree()
839            .map_err(read_err)?;
840        for entry in tree.iter() {
841            let entry = entry.map_err(read_err)?;
842            let raw_name = entry.filename(); // &BStr; CR-03/D-3(i): checked below, never `to_str_lossy`.
843            let Ok(name) = std::str::from_utf8(raw_name) else {
844                return Err(Error::FloorRefusal {
845                    feature: floor::NON_UTF8_PATH.to_string(),
846                    reason: format!(
847                        "commit {commit_id}: path '{prefix}{}{}' is not valid UTF-8 (invalid bytes \
848                         shown as \\xNN)",
849                        if prefix.is_empty() { "" } else { "/" },
850                        escape_invalid_utf8(raw_name)
851                    ),
852                });
853            };
854            let path = if prefix.is_empty() {
855                name.to_string()
856            } else {
857                format!("{prefix}/{name}")
858            };
859            if path.len() > limits.max_path_bytes {
860                return Err(resource_limit(
861                    "a path",
862                    format!("{} bytes", limits.max_path_bytes),
863                ));
864            }
865            let mode = entry.mode();
866            let oid = entry.oid().to_owned();
867            match mode.kind() {
868                gix::objs::tree::EntryKind::Tree => {
869                    let child_depth = depth + 1;
870                    if child_depth > limits.max_tree_depth {
871                        return Err(resource_limit(
872                            "the tree nesting",
873                            format!("{} levels", limits.max_tree_depth),
874                        ));
875                    }
876                    stack.push((oid, path, child_depth));
877                }
878                gix::objs::tree::EntryKind::Commit => {
879                    return Err(Error::FloorRefusal {
880                        feature: floor::SUBMODULE.to_string(),
881                        reason: format!(
882                            "submodule (gitlink) at '{path}' points outside this repository; refused \
883                             rather than approximated"
884                        ),
885                    });
886                }
887                _ => {
888                    // CR-03 §2.3.4: valid UTF-8 paths cannot collide at this point (git trees disallow
889                    // duplicate entry names, and entry names cannot contain '/'); this is defense in
890                    // depth.
891                    if out.contains_key(&path) {
892                        return Err(Error::Read(format!(
893                            "commit {commit_id}: duplicate path '{path}' in tree snapshot"
894                        )));
895                    }
896                    out.insert(path, (oid, u32::from(mode.value())));
897                }
898            }
899        }
900    }
901    Ok(())
902}
903
904/// Diff `base` → `child` into literal path operations (all *Stated*), plus — only if
905/// `opts.infer_renames` — marked *Derived* copy records for exact-content moves, each naming
906/// `from_parent` (the atom's first parent, already added to `builder`) as `from_atom`. The literal
907/// delete+add always remain; a copy record sits beside them, never in place of them (RFC 004 D-3).
908fn diff_to_ops(
909    repo: &gix::Repository,
910    base: &Snapshot,
911    child: &Snapshot,
912    opts: &Options,
913    limits: &Limits,
914    builder: &mut IrBuilder,
915    from_parent: Option<AtomId>,
916) -> Result<(Vec<PathOp>, Vec<CopyRecord>), Error> {
917    let mut ops = Vec::new();
918    let mut added_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
919    let mut deleted_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
920
921    for (path, (oid, mode)) in child {
922        match base.get(path) {
923            None => {
924                let blob = builder.add_blob(blob_bytes(repo, *oid, limits)?);
925                ops.push(PathOp::Add {
926                    path: path.clone(),
927                    blob,
928                    mode: *mode,
929                    status: EpistemicStatus::Stated,
930                });
931                added_by_oid.entry(*oid).or_default().push(path.clone());
932            }
933            Some((base_oid, base_mode)) => {
934                if base_oid != oid || base_mode != mode {
935                    let blob = builder.add_blob(blob_bytes(repo, *oid, limits)?);
936                    ops.push(PathOp::Modify {
937                        path: path.clone(),
938                        blob,
939                        mode: *mode,
940                        status: EpistemicStatus::Stated,
941                    });
942                }
943            }
944        }
945    }
946    for (path, (oid, _)) in base {
947        if !child.contains_key(path) {
948            ops.push(PathOp::Delete {
949                path: path.clone(),
950                status: EpistemicStatus::Stated,
951            });
952            deleted_by_oid.entry(*oid).or_default().push(path.clone());
953        }
954    }
955
956    let mut copies = Vec::new();
957    if opts.infer_renames {
958        // Exact-content moves only (RFC 004 D-3, OQ-A). A copy record is emitted **only** when a blob
959        // deleted at exactly one path reappears added at exactly one path — an unambiguous 1:1 move,
960        // and only when there is a parent to name as `from_atom` (a root commit's base snapshot is
961        // always empty, so this never actually triggers for a root). An ambiguous many-to-many
962        // identical-content case (the same bytes deleted at several paths and added at several) is left
963        // unmarked: brygge does not guess which path became which. Nothing is lost by declining — the
964        // literal delete+add ops remain (D-3). Similarity-based detection above exact content is OQ-A,
965        // deferred until a consumer can give a threshold a fitness signal.
966        if let Some(from_atom) = from_parent {
967            for (oid, froms) in &deleted_by_oid {
968                let [from] = froms.as_slice() else {
969                    continue; // this blob was deleted at several paths — ambiguous, decline to guess
970                };
971                let Some([to]) = added_by_oid.get(oid).map(Vec::as_slice) else {
972                    continue; // not re-added, or re-added at several paths — decline to guess
973                };
974                copies.push(CopyRecord {
975                    from: from.clone(),
976                    from_atom,
977                    to: to.clone(),
978                    status: EpistemicStatus::Derived(Derivation {
979                        kind: DerivationKind::InferredRename,
980                        by: DECODER.to_string(),
981                        decoder_version: decoder_version().to_string(),
982                        params: opts.as_params(),
983                        confidence: Some(100),
984                    }),
985                });
986            }
987        }
988    }
989    Ok((ops, copies))
990}
991
992/// Read one blob's bytes, refusing before allocation if it exceeds `limits.max_blob_bytes` (RFC 010
993/// CR-10) — checked from the object **header** (`find_header`, which gives the size without inflating
994/// the blob), not after a full read.
995fn blob_bytes(repo: &gix::Repository, oid: ObjectId, limits: &Limits) -> Result<Vec<u8>, Error> {
996    let header = repo.find_header(oid).map_err(read_err)?;
997    if header.size() > limits.max_blob_bytes {
998        return Err(resource_limit(
999            "a blob",
1000            format!("{} bytes", limits.max_blob_bytes),
1001        ));
1002    }
1003    Ok(find_verified_object(repo, oid)?
1004        .try_into_blob()
1005        .map_err(read_err)?
1006        .data
1007        .clone())
1008}
1009
1010/// Parse the seconds field of a raw signature `time` string strictly (CR-16 R-1, handoff §3.1c amended).
1011/// The first whitespace-separated token must match `-?[0-9]+` exactly and fit `i64`, or the result is
1012/// `None`. Neither gix's `seconds()` (silently defaults to 0) nor its `time()` (via `gix_date`'s
1013/// `parse_header`, which salvages the leading digits of a token like `"1695456000abc"` and silently
1014/// defaults a malformed timezone offset) is used: both are the silent-approximation class CR-16 exists
1015/// to remove.
1016fn strict_seconds(raw: &str) -> Option<i64> {
1017    let token = raw.split_whitespace().next()?;
1018    let digits = token.strip_prefix('-').unwrap_or(token);
1019    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
1020        return None;
1021    }
1022    token.parse::<i64>().ok()
1023}
1024
1025/// Parse the timezone-offset field of a raw signature `time` string strictly (RFC 011 D-5, batch-2
1026/// handoff §1.4). The token following the seconds must be a sign followed by exactly four digits
1027/// (`+HHMM`/`-HHMM`): `offset_minutes = sign × (HH × 60 + MM)`, and the result must fit `i16` with
1028/// `MM < 60`. Anything else is `None` — never gix's own lenient parser, which silently yields `+0000`
1029/// for a malformed offset.
1030fn strict_offset_minutes(raw: &str) -> Option<i16> {
1031    let mut tokens = raw.split_whitespace();
1032    let _seconds = tokens.next()?;
1033    let tz = tokens.next()?;
1034    let sign = match tz.as_bytes().first()? {
1035        b'+' => 1i32,
1036        b'-' => -1i32,
1037        _ => return None,
1038    };
1039    let digits = tz.get(1..)?;
1040    if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
1041        return None;
1042    }
1043    let hh: i32 = digits.get(..2)?.parse().ok()?;
1044    let mm: i32 = digits.get(2..)?.parse().ok()?;
1045    if mm >= 60 {
1046        return None;
1047    }
1048    i16::try_from(sign * (hh * 60 + mm)).ok()
1049}
1050
1051/// Build message/authorship claims. Names, emails and the message are carried as [`Text`] from the raw
1052/// bytes gix already read — no lossy conversion (RFC 011 §5: the Git row). The commit's `encoding`
1053/// header, when present and valid UTF-8, becomes `Text.encoding` **on the message only** (RFC 011 D-4,
1054/// batch-2 handoff §1.3) — names and emails keep `encoding: None`, meaning "not stated", never "UTF-8".
1055/// Times are parsed strictly ([`strict_seconds`], CR-16) and their offsets strictly
1056/// ([`strict_offset_minutes`], §1.4): an unparseable time becomes an absent claim, and an unparseable
1057/// offset on an otherwise-valid time becomes `offset_minutes: None` — never fabricated or salvaged
1058/// (NG-5). Returns the claims plus how many of the two time fields
1059/// failed to parse, for the caller to fold into the loss boundary.
1060fn build_metadata(commit: &gix::Commit<'_>) -> Result<(MetadataClaims, ParseCounts), Error> {
1061    let author = commit.author().map_err(read_err)?;
1062    let committer = commit.committer().map_err(read_err)?;
1063    let decoded = commit.decode().map_err(read_err)?;
1064    let message = decoded.message;
1065
1066    let mut counts = ParseCounts::default();
1067    let message_encoding = match decoded.encoding {
1068        Some(e) => match std::str::from_utf8(e) {
1069            Ok(s) => Some(s.to_string()),
1070            Err(_) => {
1071                // Review 011 R-3b: a declared `encoding` header that is itself not valid UTF-8 is not
1072                // carried, but it is counted — never silently dropped.
1073                counts.undecodable_encodings += 1;
1074                None
1075            }
1076        },
1077        None => None,
1078    };
1079    let author_time = strict_seconds(author.time);
1080    if author_time.is_none() {
1081        counts.unparseable_times += 1;
1082    }
1083    let author_offset = strict_offset_minutes(author.time);
1084    if author_time.is_some() && author_offset.is_none() {
1085        counts.unparseable_offsets += 1;
1086    }
1087    let commit_time = strict_seconds(committer.time);
1088    if commit_time.is_none() {
1089        counts.unparseable_times += 1;
1090    }
1091    let commit_offset = strict_offset_minutes(committer.time);
1092    if commit_time.is_some() && commit_offset.is_none() {
1093        counts.unparseable_offsets += 1;
1094    }
1095    let raw_text = |bytes: &[u8]| Text {
1096        bytes: bytes.to_vec(),
1097        encoding: None,
1098    };
1099    Ok((
1100        MetadataClaims {
1101            author: Some(Identity {
1102                name: raw_text(author.name.as_ref()),
1103                email: Some(raw_text(author.email.as_ref())),
1104            }),
1105            author_time: author_time.map(|seconds| Time {
1106                seconds,
1107                offset_minutes: author_offset,
1108            }),
1109            committer: Some(Identity {
1110                name: raw_text(committer.name.as_ref()),
1111                email: Some(raw_text(committer.email.as_ref())),
1112            }),
1113            commit_time: commit_time.map(|seconds| Time {
1114                seconds,
1115                offset_minutes: commit_offset,
1116            }),
1117            message: Some(Text {
1118                bytes: message.to_vec(),
1119                encoding: message_encoding,
1120            }),
1121        },
1122        counts,
1123    ))
1124}
1125
1126/// How many author/committer/tagger times, and how many of their timezone offsets (only counted when
1127/// the time itself parsed), failed strict parsing (batch-2 handoff §1.4); and how many commits'
1128/// `encoding` header value was not valid UTF-8 and so could not be carried (review 011 R-3b).
1129#[derive(Debug, Clone, Copy, Default)]
1130struct ParseCounts {
1131    unparseable_times: u64,
1132    unparseable_offsets: u64,
1133    undecodable_encodings: u64,
1134}
1135
1136/// The commit's signatures (`gpgsig`/`gpgsig-sha256`, RFC 004 D-2/SRC-G3 — preserved opaquely, verifying
1137/// nothing in any target) and every other extra header as a labelled [`Extra`] (RFC 011 D-9, batch-2
1138/// handoff §1.5), both in header order. `mergetag` — a signed, embedded tag object — is carried as an
1139/// ordinary `Extra`, like any other header this decoder does not otherwise model; a multi-line header
1140/// value arrives already unfolded (continuation lines joined, Git's own convention) since gix's own
1141/// commit parser does this. A header **name** that is not valid UTF-8 is a floor refusal (review 011
1142/// R-3c): gix does not itself enforce that header names are ASCII, so a crafted commit can carry one,
1143/// and `Extra`/`Signature` labels are text.
1144fn signatures_and_extras(
1145    commit: &gix::Commit<'_>,
1146    id: ObjectId,
1147) -> Result<(Vec<Signature>, Vec<Extra>), Error> {
1148    let decoded = commit.decode().map_err(read_err)?;
1149    let mut signatures = Vec::new();
1150    let mut extras = Vec::new();
1151    for (name, value) in &decoded.extra_headers {
1152        let Ok(label) = std::str::from_utf8(name) else {
1153            return Err(Error::FloorRefusal {
1154                feature: floor::NON_UTF8_COMMIT_HEADER_NAME.to_string(),
1155                reason: format!(
1156                    "commit {id}: header name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
1157                    escape_invalid_utf8(name)
1158                ),
1159            });
1160        };
1161        match label {
1162            "gpgsig" | "gpgsig-sha256" => signatures.push(Signature {
1163                label: label.to_string(),
1164                bytes: value.to_vec(),
1165            }),
1166            _ => extras.push(Extra {
1167                label: label.to_string(),
1168                bytes: value.to_vec(),
1169            }),
1170        }
1171    }
1172    Ok((signatures, extras))
1173}
1174
1175/// The Git loss boundary (RFC 004 D-5): the representation-class drops, every one class-stated, plus
1176/// symbolic refs skipped (CR-16), any author/committer/tagger time or timezone offset that failed to
1177/// parse (CR-16, batch-2 handoff §1.4), any undecodable `encoding` header (review 011 R-3b), commits
1178/// reachable only from a dropped ref namespace (CR-05), refs that peel to a tree or blob rather than a
1179/// commit (CR-06), and any intermediate tag object in a tag-of-a-tag chain (batch-2 handoff §1.1, review
1180/// 011 R-2) — recorded, never silently omitted (`PR-9`). An annotated tag's own tagger/time/message is
1181/// no longer dropped (batch-2 handoff §1.6): it is carried in the ref's `annotation`.
1182fn loss_boundary(
1183    dropped_namespace_counts: &BTreeMap<&'static str, u64>,
1184    dropped_only_commits: DroppedOnlyCommits,
1185    non_commit_refs: u64,
1186    symbolic_refs: u64,
1187    time_counts: ParseCounts,
1188    nested_tag_objects: u64,
1189) -> LossBoundary {
1190    let mut dropped = vec![
1191        DropRecord {
1192            class: LossClass::Representation,
1193            what: "packfile and delta layout, physical object store".to_string(),
1194            reason: "representation not assertion; reconstructible from the objects".to_string(),
1195        },
1196        DropRecord {
1197            class: LossClass::Representation,
1198            what: "index and working tree".to_string(),
1199            reason: "local state, not history".to_string(),
1200        },
1201        DropRecord {
1202            class: LossClass::Representation,
1203            what: "reflogs".to_string(),
1204            reason: "local operation log, not history".to_string(),
1205        },
1206    ];
1207    for (ns, count) in dropped_namespace_counts {
1208        dropped.push(DropRecord {
1209            class: LossClass::Representation,
1210            what: format!("{ns} refs ({count})"),
1211            reason: "workflow/representation refs, not authored history".to_string(),
1212        });
1213    }
1214    match dropped_only_commits {
1215        DroppedOnlyCommits::Counted(0) => {}
1216        DroppedOnlyCommits::Counted(n) => {
1217            dropped.push(DropRecord {
1218                class: LossClass::Representation,
1219                what: format!("commits reachable only from dropped refs ({n})"),
1220                reason:
1221                    "workflow state (stash, notes, remote-tracking), not authored history of a \
1222                         carried ref"
1223                        .to_string(),
1224            });
1225        }
1226        DroppedOnlyCommits::Unavailable => {
1227            dropped.push(DropRecord {
1228                class: LossClass::Representation,
1229                what: "commits reachable only from dropped refs (count unavailable)".to_string(),
1230                reason: "a commit in dropped-only history could not be read".to_string(),
1231            });
1232        }
1233    }
1234    if non_commit_refs > 0 {
1235        dropped.push(DropRecord {
1236            class: LossClass::Other,
1237            what: format!("refs to non-commit objects ({non_commit_refs})"),
1238            reason: "a tag or branch naming a tree or blob; the IR's refs point at history atoms"
1239                .to_string(),
1240        });
1241    }
1242    if symbolic_refs > 0 {
1243        dropped.push(DropRecord {
1244            class: LossClass::Representation,
1245            what: format!("symbolic refs ({symbolic_refs})"),
1246            reason:
1247                "an alias to another ref; the IR has no alias concept; the target ref is carried \
1248                     on its own"
1249                    .to_string(),
1250        });
1251    }
1252    if time_counts.unparseable_times > 0 {
1253        dropped.push(DropRecord {
1254            class: LossClass::Other,
1255            what: format!(
1256                "unparseable author/committer/tagger times ({})",
1257                time_counts.unparseable_times
1258            ),
1259            reason: "the source's time field could not be parsed; the claim is absent rather than \
1260                     fabricated"
1261                .to_string(),
1262        });
1263    }
1264    if time_counts.unparseable_offsets > 0 {
1265        dropped.push(DropRecord {
1266            class: LossClass::Other,
1267            what: format!(
1268                "unparseable author/committer/tagger timezone offsets ({})",
1269                time_counts.unparseable_offsets
1270            ),
1271            reason: "the source's timezone offset could not be parsed strictly (`+HHMM`/`-HHMM`); \
1272                     the time is carried without an offset rather than a fabricated or salvaged one"
1273                .to_string(),
1274        });
1275    }
1276    if time_counts.undecodable_encodings > 0 {
1277        dropped.push(DropRecord {
1278            class: LossClass::Other,
1279            what: format!(
1280                "undecodable encoding headers ({})",
1281                time_counts.undecodable_encodings
1282            ),
1283            reason:
1284                "the commit's declared `encoding` header value was not valid UTF-8, so it is not \
1285                     carried on the message's `Text.encoding`"
1286                    .to_string(),
1287        });
1288    }
1289    if nested_tag_objects > 0 {
1290        dropped.push(DropRecord {
1291            class: LossClass::Other,
1292            what: format!("nested tag objects not carried ({nested_tag_objects})"),
1293            reason: "an intermediate tag object in a tag-of-a-tag chain; only the outer tag's \
1294                     annotation is carried"
1295                .to_string(),
1296        });
1297    }
1298    LossBoundary { dropped }
1299}
1300
1301#[cfg(test)]
1302mod tests;