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