Skip to main content

git_internal/internal/object/
mod.rs

1//! Object model definitions for Git blobs, trees, commits, tags, and
2//! AI workflow objects.
3//!
4//! This module is the storage-layer contract for `git-internal`.
5//! Git-native objects (`Blob`, `Tree`, `Commit`, `Tag`) model repository
6//! content, while the AI objects model immutable workflow history that
7//! Libra orchestrates on top.
8//!
9//! # How Libra should use this module
10//!
11//! Libra should treat every AI object here as an immutable record:
12//!
13//! - construct the object in memory,
14//! - populate optional fields before persistence,
15//! - persist it once,
16//! - derive current state later from object history plus Libra
17//!   projections.
18//!
19//! Libra should not store scheduler state, selected heads, active UI
20//! focus, or query caches in these objects. Those belong to Libra's own
21//! runtime and index layer.
22//!
23//! AI workflow objects are split into three layers:
24//!
25//! - **Snapshot objects** in `git-internal` answer "what was the stored
26//!   fact at this revision?"
27//! - **Event objects** in `git-internal` answer "what happened later?"
28//! - **Libra projections** answer "what is the system's current view?"
29//!
30//! # Relationship Design Standard
31//!
32//! Relationship fields follow a simple storage rule:
33//!
34//! - Store the canonical ownership edge on the child object when the
35//!   relationship is a historical fact.
36//! - Low-frequency, strongly aggregated relationships that benefit
37//!   from fast parent-to-children traversal may additionally keep a
38//!   reverse convenience link.
39//! - High-frequency, high-cardinality, event-stream relationships
40//!   should remain single-directional to avoid turning parent objects
41//!   into rewrite hotspots.
42//!
43//! # Three-Layer Design
44//!
45//! ```text
46//! +------------------------------------------------------------------+
47//! | Libra projection / runtime                                       |
48//! |------------------------------------------------------------------|
49//! | thread heads / selected_plan_id / active_run / scheduler state   |
50//! | live context window / UI focus / query indexes                   |
51//! +--------------------------------+---------------------------------+
52//!                                  |
53//!                                  v
54//! +------------------------------------------------------------------+
55//! | git-internal event objects                                        |
56//! |------------------------------------------------------------------|
57//! | IntentEvent / TaskEvent / RunEvent / PlanStepEvent / RunUsage    |
58//! | ToolInvocation / Evidence / Decision / ContextFrame              |
59//! +--------------------------------+---------------------------------+
60//!                                  |
61//!                                  v
62//! +------------------------------------------------------------------+
63//! | git-internal snapshot objects                                     |
64//! |------------------------------------------------------------------|
65//! | Intent / Plan / Task / Run / PatchSet / ContextSnapshot          |
66//! | Provenance                                                       |
67//! +------------------------------------------------------------------+
68//! ```
69//!
70//! # Main Object Relationships
71//!
72//! ```text
73//! Snapshot layer
74//! ==============
75//!
76//! Intent --parents----------------------------> Intent
77//! Intent --analysis_context_frames-----------> ContextFrame
78//! Plan   --intent-----------------------------> Intent
79//! Plan   --context_frames---------------------> ContextFrame
80//! Plan   --parents----------------------------> Plan
81//! Task   --intent?----------------------------> Intent
82//! Task   --parent?----------------------------> Task
83//! Task   --origin_step_id?-------------------> PlanStep.step_id
84//! Run    --task-------------------------------> Task
85//! Run    --plan?------------------------------> Plan
86//! Run    --snapshot?--------------------------> ContextSnapshot
87//! PatchSet   --run----------------------------> Run
88//! Provenance --run_id-------------------------> Run
89//!
90//! Event layer
91//! ===========
92//!
93//! IntentEvent   --intent_id-------------------> Intent
94//! IntentEvent   --next_intent_id?-------------> Intent
95//! ContextFrame  --intent_id?------------------> Intent
96//! TaskEvent     --task_id---------------------> Task
97//! RunEvent      --run_id----------------------> Run
98//! RunUsage      --run_id----------------------> Run
99//! PlanStepEvent --plan_id + step_id + run_id-> Plan / Run / PlanStep
100//! ToolInvocation--run_id----------------------> Run
101//! Evidence      --run_id / patchset_id?-------> Run / PatchSet
102//! Decision      --run_id / chosen_patchset_id?> Run / PatchSet
103//! ContextFrame  --run_id? / plan_id? / step_id?> Run / Plan / PlanStep
104//! ```
105//!
106//! # Libra read / write pattern
107//!
108//! A typical Libra call flow looks like this:
109//!
110//! 1. write snapshot objects when a new immutable revision is defined
111//!    (`Intent`, `Plan`, `Task`, `Run`, `PatchSet`, `ContextSnapshot`,
112//!    `Provenance`);
113//! 2. append event objects as execution progresses
114//!    (`IntentEvent`, `TaskEvent`, `RunEvent`, `PlanStepEvent`,
115//!    `RunUsage`, `ToolInvocation`, `Evidence`, `Decision`,
116//!    `ContextFrame`);
117//! 3. rebuild current state in Libra from those immutable objects plus
118//!    its own `Thread`, `Scheduler`, `UI`, and `Query Index`
119//!    projections.
120//!
121//! ## Object Relationship Summary
122//!
123//! | From | Field | To | Cardinality |
124//! |------|-------|----|-------------|
125//! | Intent | `parents` | Intent | 0..N |
126//! | Intent | `analysis_context_frames` | ContextFrame | 0..N |
127//! | Plan | `intent` | Intent | 1 canonical |
128//! | Plan | `parents` | Plan | 0..N |
129//! | Plan | `context_frames` | ContextFrame | 0..N |
130//! | Task | `parent` | Task | 0..1 |
131//! | Task | `intent` | Intent | 0..1 |
132//! | Task | `origin_step_id` | PlanStep.step_id | 0..1 |
133//! | Task | `dependencies` | Task | 0..N |
134//! | Run | `task` | Task | 1 |
135//! | Run | `plan` | Plan | 0..1 |
136//! | Run | `snapshot` | ContextSnapshot | 0..1 |
137//! | PatchSet | `run` | Run | 1 |
138//! | Provenance | `run_id` | Run | 1 |
139//! | IntentEvent | `intent_id` | Intent | 1 |
140//! | IntentEvent | `next_intent_id` | Intent | 0..1 recommended follow-up |
141//! | ContextFrame | `intent_id` | Intent | 0..1 |
142//! | TaskEvent | `task_id` | Task | 1 |
143//! | RunEvent | `run_id` | Run | 1 |
144//! | RunUsage | `run_id` | Run | 1 |
145//! | PlanStepEvent | `plan_id` | Plan | 1 |
146//! | PlanStepEvent | `step_id` | PlanStep.step_id | 1 |
147//! | PlanStepEvent | `run_id` | Run | 1 |
148//! | ToolInvocation | `run_id` | Run | 1 |
149//! | Evidence | `run_id` | Run | 1 |
150//! | Evidence | `patchset_id` | PatchSet | 0..1 |
151//! | Decision | `run_id` | Run | 1 |
152//! | Decision | `chosen_patchset_id` | PatchSet | 0..1 |
153//! | ContextFrame | `run_id` | Run | 0..1 |
154//! | ContextFrame | `plan_id` | Plan | 0..1 |
155//! | ContextFrame | `step_id` | PlanStep.step_id | 0..1 |
156//!
157pub mod blob;
158pub mod commit;
159pub mod context;
160pub mod context_frame;
161pub mod decision;
162pub mod evidence;
163pub mod integrity;
164pub mod intent;
165pub mod intent_event;
166pub mod note;
167pub mod patchset;
168pub mod plan;
169pub mod plan_step_event;
170pub mod provenance;
171pub mod run;
172pub mod run_event;
173pub mod run_usage;
174pub mod signature;
175pub mod tag;
176pub mod task;
177pub mod task_event;
178pub mod tool;
179pub mod tree;
180pub mod types;
181pub mod utils;
182
183use std::{
184    fmt::Display,
185    io::{BufRead, Read},
186};
187
188use crate::{
189    errors::GitError,
190    hash::{HashError, HashKind, ObjectHash, get_hash_kind},
191    internal::{object::types::ObjectType, zlib::stream::inflate::ReadBoxed},
192};
193
194/// **The Object Trait**
195/// Defines the common interface for all Git object types, including blobs, trees, commits, and tags.
196///
197/// # Repository hash context
198///
199/// Object IDs depend on the repository's [`HashKind`]. Every implementor
200/// (standard Git objects and AI objects alike) gets two explicit-kind entry
201/// points for free from the default methods:
202///
203/// * [`ObjectTrait::from_buf_read_with_kind`] — load an object from a
204///   [`ReadBoxed`] created for that kind and fail closed if the reader's hasher
205///   belongs to another kind;
206/// * [`ObjectTrait::object_hash_for_kind`] — compute the canonical object ID
207///   for an explicit kind.
208///
209/// The parameterless [`ObjectTrait::from_buf_read`] and
210/// [`ObjectTrait::object_hash`] keep the thread-local behaviour for the
211/// established single-repository workflow (GC-06); code that may run on a
212/// thread configured for another repository must pass the kind explicitly.
213pub trait ObjectTrait: Send + Sync + Display {
214    /// Creates a new object from a byte slice.
215    fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
216    where
217        Self: Sized;
218
219    /// Generate a new Object from a `ReadBoxed<BufRead>` whose hasher was created
220    /// for `kind` (see [`ReadBoxed::new_with_kind`]).
221    ///
222    /// `size` is only a capacity hint for the content buffer. The object ID is
223    /// finalized from the reader's own hasher; if that hasher belongs to a
224    /// different [`HashKind`] than `kind`, the call fails closed with a
225    /// [`HashError::KindMismatch`] wrapped in [`GitError::InvalidHashValue`]
226    /// instead of mislabelling the digest.
227    fn from_buf_read_with_kind<R: BufRead>(
228        read: &mut ReadBoxed<R>,
229        size: usize,
230        kind: HashKind,
231    ) -> Result<Self, GitError>
232    where
233        Self: Sized,
234    {
235        let mut content: Vec<u8> = Vec::with_capacity(size);
236        read.read_to_end(&mut content)?;
237        let hasher = read.hash.clone();
238        let actual = hasher.kind();
239        if actual != kind {
240            return Err(HashError::KindMismatch {
241                operation: "from_buf_read_with_kind",
242                expected: kind,
243                actual,
244                expected_len: kind.size(),
245                actual_len: actual.size(),
246            }
247            .into());
248        }
249        let hash = hasher.finalize_object_hash();
250        Self::from_bytes(&content, hash)
251    }
252
253    /// Generate a new Object from a `ReadBoxed<BufRead>`.
254    /// the input size,is only for new a vec with directive space allocation
255    /// the input data stream and output object should be plain base object .
256    ///
257    /// Compatibility wrapper around [`ObjectTrait::from_buf_read_with_kind`]
258    /// using the thread-local [`HashKind`]. It keeps the pre-existing contract
259    /// of this signature: any failure (I/O, parse, or a reader whose hasher
260    /// does not match the thread-local kind — formerly an "Invalid byte
261    /// length" panic) is a panic. New code should call the explicit-kind
262    /// variant and handle the error.
263    fn from_buf_read<R: BufRead>(read: &mut ReadBoxed<R>, size: usize) -> Self
264    where
265        Self: Sized,
266    {
267        Self::from_buf_read_with_kind(read, size, get_hash_kind()).unwrap()
268    }
269
270    /// Returns the type of the object.
271    fn get_type(&self) -> ObjectType;
272
273    fn get_size(&self) -> usize;
274
275    fn to_data(&self) -> Result<Vec<u8>, GitError>;
276
277    /// Canonical object ID of this object for an explicit repository `kind`.
278    ///
279    /// Does not consult the thread-local [`HashKind`].
280    fn object_hash_for_kind(&self, kind: HashKind) -> Result<ObjectHash, GitError> {
281        let data = self.to_data()?;
282        Ok(ObjectHash::from_type_and_data_for_kind(
283            kind,
284            self.get_type(),
285            &data,
286        )?)
287    }
288
289    /// Canonical object ID of this object using the thread-local [`HashKind`].
290    ///
291    /// Compatibility wrapper around [`ObjectTrait::object_hash_for_kind`].
292    fn object_hash(&self) -> Result<ObjectHash, GitError> {
293        self.object_hash_for_kind(get_hash_kind())
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use std::io::{self, Write};
300
301    use flate2::{Compression, write::ZlibEncoder};
302
303    use super::*;
304    use crate::{
305        hash::set_hash_kind_for_test,
306        internal::object::{
307            blob::Blob,
308            commit::Commit,
309            note::Note,
310            provenance::Provenance,
311            signature::{Signature, SignatureType},
312            tag::Tag,
313            tree::{Tree, TreeItem, TreeItemMode},
314            types::{ActorKind, ActorRef},
315        },
316    };
317
318    /// (kind under test, "other" thread-local kind). The SHA-256/BLAKE3 pairs share the
319    /// same 32-byte width, so they prove the kind is carried as metadata, not inferred.
320    const KINDS: [(HashKind, HashKind); 4] = [
321        (HashKind::Sha1, HashKind::Sha256),
322        (HashKind::Sha256, HashKind::Sha1),
323        (HashKind::Blake3, HashKind::Sha256),
324        (HashKind::Sha256, HashKind::Blake3),
325    ];
326    const HELLO: &[u8] = b"Hello, world!";
327    const HELLO_BLOB_SHA1: &str = "5dd01c177f5d7d1be5346a5bc18a569a7410c2ef";
328    const HELLO_BLOB_SHA256: &str =
329        "178b5fbed164aee269fee7323badf7269cca0eed0875717b0d2d4f9819164c3f";
330
331    fn zlib(data: &[u8]) -> Vec<u8> {
332        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
333        enc.write_all(data).unwrap();
334        enc.finish().unwrap()
335    }
336
337    fn signature(role: SignatureType) -> Signature {
338        Signature::new(role, "tester".to_string(), "tester@example.com".to_string())
339    }
340
341    /// `object_hash_for_kind` and `from_buf_read_with_kind` follow the explicit kind for
342    /// standard and AI objects alike, regardless of the thread-local kind.
343    #[test]
344    fn object_hash_context_explicit_kind_ignores_thread_local() {
345        for (kind, other) in KINDS {
346            let _guard = set_hash_kind_for_test(other);
347
348            // Standard object: explicit kind wins, thread-local wrapper follows `other`.
349            let blob = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
350            assert_eq!(blob.id.kind(), kind);
351            assert_eq!(blob.object_hash_for_kind(kind).unwrap(), blob.id);
352            let via_thread_local = blob.object_hash().unwrap();
353            assert_eq!(via_thread_local.kind(), other);
354            assert_ne!(via_thread_local, blob.id);
355
356            // AI object: default trait method is kind-aware too.
357            let actor = ActorRef::new(ActorKind::Agent, "agent-1").unwrap();
358            let provenance =
359                Provenance::new(actor, uuid::Uuid::now_v7(), "provider", "model").unwrap();
360            assert_eq!(provenance.object_hash_for_kind(kind).unwrap().kind(), kind);
361            assert_eq!(
362                provenance.object_hash_for_kind(other).unwrap().kind(),
363                other
364            );
365            assert_eq!(provenance.object_hash().unwrap().kind(), other);
366
367            // Loader: reader created for `kind` yields the same ID as the constructor.
368            let compressed = zlib(HELLO);
369            let mut reader = ReadBoxed::new_with_kind(
370                io::Cursor::new(&compressed),
371                ObjectType::Blob,
372                HELLO.len(),
373                kind,
374            )
375            .unwrap();
376            let loaded = Blob::from_buf_read_with_kind(&mut reader, HELLO.len(), kind).unwrap();
377            assert_eq!(loaded.id, blob.id);
378            assert_eq!(loaded.data, HELLO);
379
380            // Loader: a tree with `kind`-width entries loads under the other thread-local kind
381            // (entry slicing follows the loaded hash's kind, not the thread-local one).
382            let tree = Tree::from_tree_items_with_kind(
383                kind,
384                vec![TreeItem::new(
385                    TreeItemMode::Blob,
386                    blob.id,
387                    "hello.txt".to_string(),
388                )],
389            )
390            .unwrap();
391            let tree_bytes = tree.to_data().unwrap();
392            let mut reader = ReadBoxed::new_with_kind(
393                io::Cursor::new(zlib(&tree_bytes)),
394                ObjectType::Tree,
395                tree_bytes.len(),
396                kind,
397            )
398            .unwrap();
399            let loaded_tree =
400                Tree::from_buf_read_with_kind(&mut reader, tree_bytes.len(), kind).unwrap();
401            assert_eq!(loaded_tree.id, tree.id);
402            assert_eq!(loaded_tree.tree_items, tree.tree_items);
403            assert_eq!(loaded_tree.tree_items[0].id.kind(), kind);
404
405            // Loader: asking for a different kind than the reader's hasher fails closed.
406            let mut reader = ReadBoxed::new_with_kind(
407                io::Cursor::new(&compressed),
408                ObjectType::Blob,
409                HELLO.len(),
410                kind,
411            )
412            .unwrap();
413            let err = Blob::from_buf_read_with_kind(&mut reader, HELLO.len(), other).unwrap_err();
414            match err {
415                GitError::InvalidHashValue(msg) => {
416                    assert!(msg.contains("from_buf_read_with_kind"), "{msg}");
417                    assert!(
418                        msg.contains(kind.as_str()) && msg.contains(other.as_str()),
419                        "{msg}"
420                    );
421                }
422                other_err => panic!("unexpected error: {other_err:?}"),
423            }
424        }
425    }
426
427    /// Delta object types have no loose-object header: the explicit loader fails closed
428    /// with the full diagnostic (operation, kind, expected/actual lengths).
429    #[test]
430    fn object_hash_context_rejects_delta_reader() {
431        let _guard = set_hash_kind_for_test(HashKind::Sha1);
432        let err = ReadBoxed::new_with_kind(
433            io::Cursor::new(Vec::new()),
434            ObjectType::OffsetDelta,
435            7,
436            HashKind::Sha256,
437        )
438        .err()
439        .expect("delta type must be rejected");
440        match err {
441            GitError::InvalidHashValue(msg) => {
442                assert!(msg.contains("ReadBoxed::new_with_kind"), "{msg}");
443                assert!(
444                    msg.contains("sha256") && msg.contains("OffsetDelta"),
445                    "{msg}"
446                );
447                assert!(
448                    msg.contains("32") && msg.contains("payload 7 bytes"),
449                    "{msg}"
450                );
451            }
452            other => panic!("unexpected error: {other:?}"),
453        }
454    }
455
456    /// Blob IDs for an explicit kind match the known SHA-1/SHA-256 vectors.
457    #[test]
458    fn blob_hash_for_kind_known_vectors() {
459        for (kind, other, expected) in [
460            (HashKind::Sha1, HashKind::Sha256, HELLO_BLOB_SHA1),
461            (HashKind::Sha256, HashKind::Sha1, HELLO_BLOB_SHA256),
462        ] {
463            let _guard = set_hash_kind_for_test(other);
464            let from_bytes = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
465            let from_str = Blob::from_content_with_kind(kind, "Hello, world!").unwrap();
466            assert_eq!(from_bytes.id.to_string(), expected);
467            assert_eq!(from_str.id, from_bytes.id);
468            assert_eq!(from_bytes.id.kind(), kind);
469            {
470                let _same = set_hash_kind_for_test(kind);
471                assert_eq!(Blob::from_content_bytes(HELLO.to_vec()).id, from_bytes.id);
472            }
473        }
474    }
475
476    /// Derived-ID constructors (tree, commit, tag, note) compute IDs for the explicit kind
477    /// and agree with `ObjectHash::from_type_and_data_for_kind`.
478    #[test]
479    fn derived_id_for_kind_matches_explicit_hash() {
480        for (kind, other) in KINDS {
481            let _guard = set_hash_kind_for_test(other);
482
483            let blob = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
484            let item = TreeItem::new(TreeItemMode::Blob, blob.id, "hello.txt".to_string());
485            let mut tree = Tree::from_tree_items_with_kind(kind, vec![item]).unwrap();
486            assert_eq!(tree.id.kind(), kind);
487            assert_eq!(
488                tree.id,
489                ObjectHash::from_type_and_data_for_kind(
490                    kind,
491                    ObjectType::Tree,
492                    &tree.to_data().unwrap()
493                )
494                .unwrap()
495            );
496            let before = tree.id;
497            tree.tree_items.push(TreeItem::new(
498                TreeItemMode::Blob,
499                blob.id,
500                "again.txt".to_string(),
501            ));
502            tree.rehash_with_kind(kind).unwrap();
503            assert_ne!(tree.id, before);
504            assert_eq!(tree.id.kind(), kind);
505            assert_eq!(tree.object_hash_for_kind(kind).unwrap(), tree.id);
506
507            let commit = Commit::new_with_kind(
508                kind,
509                signature(SignatureType::Author),
510                signature(SignatureType::Committer),
511                tree.id,
512                vec![],
513                "initial",
514            )
515            .unwrap();
516            assert_eq!(commit.id.kind(), kind);
517            assert_eq!(commit.object_hash_for_kind(kind).unwrap(), commit.id);
518            let child =
519                Commit::from_tree_id_with_kind(kind, tree.id, vec![commit.id], "child").unwrap();
520            assert_eq!(child.id.kind(), kind);
521            assert_eq!(child.parent_commit_ids, vec![commit.id]);
522            assert_eq!(child.object_hash_for_kind(kind).unwrap(), child.id);
523
524            let tag = Tag::new_with_kind(
525                kind,
526                commit.id,
527                ObjectType::Commit,
528                "v1".to_string(),
529                signature(SignatureType::Tagger),
530                "release".to_string(),
531            )
532            .unwrap();
533            assert_eq!(tag.id.kind(), kind);
534            assert_eq!(tag.object_hash_for_kind(kind).unwrap(), tag.id);
535
536            let note = Note::new_with_kind(kind, commit.id, "note body".to_string()).unwrap();
537            assert_eq!(note.id.kind(), kind);
538            assert_eq!(note.target_object_id, commit.id);
539            assert_eq!(note.object_hash_for_kind(kind).unwrap(), note.id);
540            let placeholder = Note::from_content_with_kind(kind, "note body").unwrap();
541            assert_eq!(placeholder.id, note.id);
542            assert_eq!(
543                placeholder.target_object_id,
544                ObjectHash::zero_for_kind(kind)
545            );
546            assert_eq!(placeholder.target_object_id.kind(), kind);
547        }
548    }
549
550    /// Cross-kind references are rejected instead of being silently embedded — including the
551    /// same-width SHA-256/BLAKE3 pair.
552    #[test]
553    fn derived_id_for_kind_rejects_cross_kind_references() {
554        for (own, foreign) in [
555            (HashKind::Sha1, HashKind::Sha256),
556            (HashKind::Sha256, HashKind::Blake3),
557            (HashKind::Blake3, HashKind::Sha256),
558        ] {
559            reject_cross_kind_references(own, foreign);
560        }
561    }
562
563    fn reject_cross_kind_references(own: HashKind, foreign: HashKind) {
564        let _guard = set_hash_kind_for_test(own);
565        let sha1_blob = Blob::from_content_bytes_with_kind(own, HELLO.to_vec()).unwrap();
566        let sha256_blob = Blob::from_content_bytes_with_kind(foreign, HELLO.to_vec()).unwrap();
567        assert_eq!(sha1_blob.id.kind(), own);
568        assert_eq!(sha256_blob.id.kind(), foreign);
569
570        let is_kind_mismatch = |err: GitError| match err {
571            GitError::InvalidHashValue(msg) => msg.contains("hash kind mismatch"),
572            _ => false,
573        };
574
575        let item = TreeItem::new(TreeItemMode::Blob, sha256_blob.id, "x".to_string());
576        assert!(is_kind_mismatch(
577            Tree::from_tree_items_with_kind(own, vec![item]).unwrap_err()
578        ));
579        let mut tree = Tree::from_tree_items_with_kind(
580            own,
581            vec![TreeItem::new(
582                TreeItemMode::Blob,
583                sha1_blob.id,
584                "x".to_string(),
585            )],
586        )
587        .unwrap();
588        tree.tree_items[0].id = sha256_blob.id;
589        assert!(is_kind_mismatch(tree.rehash_with_kind(own).unwrap_err()));
590
591        assert!(is_kind_mismatch(
592            Commit::from_tree_id_with_kind(own, sha256_blob.id, vec![], "m").unwrap_err()
593        ));
594        assert!(is_kind_mismatch(
595            Commit::from_tree_id_with_kind(own, sha1_blob.id, vec![sha256_blob.id], "m")
596                .unwrap_err()
597        ));
598        assert!(is_kind_mismatch(
599            Tag::new_with_kind(
600                own,
601                sha256_blob.id,
602                ObjectType::Blob,
603                "t".to_string(),
604                signature(SignatureType::Tagger),
605                "m".to_string(),
606            )
607            .unwrap_err()
608        ));
609        assert!(is_kind_mismatch(
610            Note::new_with_kind(own, sha256_blob.id, "n".to_string()).unwrap_err()
611        ));
612    }
613
614    /// Commit/Tag/Note reference parsing follows the loaded object's own hash kind
615    /// (40 or 64 hex) regardless of the thread-local kind.
616    #[test]
617    fn reference_parse_context_follows_hash_kind() {
618        for (kind, other) in KINDS {
619            let _guard = set_hash_kind_for_test(other);
620
621            let blob = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
622            let tree = Tree::from_tree_items_with_kind(
623                kind,
624                vec![TreeItem::new(
625                    TreeItemMode::Blob,
626                    blob.id,
627                    "hello.txt".to_string(),
628                )],
629            )
630            .unwrap();
631            let root = Commit::from_tree_id_with_kind(kind, tree.id, vec![], "root").unwrap();
632            let child = Commit::new_with_kind(
633                kind,
634                signature(SignatureType::Author),
635                signature(SignatureType::Committer),
636                tree.id,
637                vec![root.id, root.id],
638                "child\n\nbody",
639            )
640            .unwrap();
641
642            let parsed = Commit::from_bytes(&child.to_data().unwrap(), child.id).unwrap();
643            assert_eq!(parsed.tree_id, tree.id);
644            assert_eq!(parsed.tree_id.kind(), kind);
645            assert_eq!(parsed.parent_commit_ids, vec![root.id, root.id]);
646            assert!(parsed.parent_commit_ids.iter().all(|p| p.kind() == kind));
647            assert_eq!(parsed.message, "child\n\nbody");
648            assert_eq!(parsed.to_data().unwrap(), child.to_data().unwrap());
649
650            let tag = Tag::new_with_kind(
651                kind,
652                child.id,
653                ObjectType::Commit,
654                "v1".to_string(),
655                signature(SignatureType::Tagger),
656                "release".to_string(),
657            )
658            .unwrap();
659            let parsed = Tag::from_bytes(&tag.to_data().unwrap(), tag.id).unwrap();
660            assert_eq!(parsed.object_hash, child.id);
661            assert_eq!(parsed.object_hash.kind(), kind);
662
663            let note = Note::new_with_kind(kind, child.id, "annotation".to_string()).unwrap();
664            let parsed = Note::from_bytes(&note.to_data().unwrap(), note.id).unwrap();
665            assert_eq!(parsed.target_object_id, ObjectHash::zero_for_kind(kind));
666            assert_eq!(parsed.target_object_id.kind(), kind);
667            assert_eq!(parsed.content, "annotation");
668        }
669    }
670
671    /// References of the wrong width, non-hex references and truncated bodies fail closed
672    /// (no silent SHA-1 fallback, no panic).
673    #[test]
674    fn reference_parse_context_rejects_cross_kind_and_malformed() {
675        let _guard = set_hash_kind_for_test(HashKind::Sha1);
676        let sha1_id = ObjectHash::new_for_kind(HashKind::Sha1, b"x");
677        let sha256_id = ObjectHash::new_for_kind(HashKind::Sha256, b"x");
678        let author = signature(SignatureType::Author).to_data().unwrap();
679        let committer = signature(SignatureType::Committer).to_data().unwrap();
680        let body = |tree: &str, parent: Option<&str>| {
681            let mut v = format!("tree {tree}\n").into_bytes();
682            if let Some(p) = parent {
683                v.extend(format!("parent {p}\n").into_bytes());
684            }
685            v.extend(&author);
686            v.push(b'\n');
687            v.extend(&committer);
688            v.extend(b"\nmsg");
689            v
690        };
691        let hash_msg = |err: GitError| match err {
692            GitError::InvalidHashValue(msg) => msg,
693            other => panic!("expected InvalidHashValue, got {other:?}"),
694        };
695
696        // 40-hex tree inside a SHA-256 commit: not guessed as SHA-1.
697        let msg =
698            hash_msg(Commit::from_bytes(&body(&sha1_id.to_string(), None), sha256_id).unwrap_err());
699        assert!(msg.contains("tree") && msg.contains("sha256"), "{msg}");
700        assert!(
701            msg.contains("expected 64") && msg.contains("got 40"),
702            "{msg}"
703        );
704
705        // 64-hex parent inside a SHA-1 commit: not guessed as SHA-256.
706        let msg = hash_msg(
707            Commit::from_bytes(
708                &body(&sha1_id.to_string(), Some(&sha256_id.to_string())),
709                sha1_id,
710            )
711            .unwrap_err(),
712        );
713        assert!(
714            msg.contains("parent") && msg.contains("expected 40") && msg.contains("got 64"),
715            "{msg}"
716        );
717
718        // Non-hex tree of the right length.
719        let msg = hash_msg(Commit::from_bytes(&body(&"zz".repeat(20), None), sha1_id).unwrap_err());
720        assert!(msg.contains("tree") && msg.contains("hex"), "{msg}");
721
722        // Truncated / structurally broken bodies: errors, never panics.
723        assert!(matches!(
724            Commit::from_bytes(b"tree abc", sha1_id),
725            Err(GitError::InvalidCommitObject)
726        ));
727        assert!(matches!(
728            Commit::from_bytes(format!("tree {sha1_id}\n").as_bytes(), sha1_id),
729            Err(GitError::InvalidCommitObject)
730        ));
731        assert!(matches!(
732            Commit::from_bytes(format!("blob {sha1_id}\n").as_bytes(), sha1_id),
733            Err(GitError::InvalidCommitObject)
734        ));
735        let mut no_committer = format!("tree {sha1_id}\n").into_bytes();
736        no_committer.extend(&author);
737        assert!(matches!(
738            Commit::from_bytes(&no_committer, sha1_id),
739            Err(GitError::InvalidCommitObject)
740        ));
741
742        // Malformed author/committer lines: signature parsing fails closed (no panic).
743        for bad_sig in [
744            "author",
745            "author name-without-email 1 +0000",
746            "author name <mail 1 +0000",
747            "author name <mail>",
748            "author name <mail> notanumber +0000",
749            "author name <mail> 1",
750            "author name <mail> 1 ",
751            "author name <mail>1 +0000",
752            "author name <mail>x1 +0000",
753            "author name <mail> 1 +08 00",
754            "author name<mail> 1 +0000",
755            "author name <mail> 1 garbage",
756            "author name <mail> 1 0800",
757            "author name <mail> 1 +12345",
758            "author name <mail> 1 +0a00",
759            "committer name <mail> 1 +0000",
760            "xauthor name <mail> 1 +0000",
761            "encoding utf-8",
762        ] {
763            let mut body = format!("tree {sha1_id}\n{bad_sig}\n").into_bytes();
764            body.extend(&committer);
765            body.extend(b"\nmsg");
766            match Commit::from_bytes(&body, sha1_id) {
767                Err(GitError::InvalidSignatureType(_)) | Err(GitError::InvalidCommitObject) => {}
768                Err(GitError::ConversionError(_)) => {}
769                other => panic!("expected a parse error for {bad_sig:?}, got {other:?}"),
770            }
771        }
772        // Edge cases that must parse: empty name, and a body whose author line is preceded
773        // by parents only.
774        let mut empty_name = format!("tree {sha1_id}\nauthor <mail> 1 +0000\n").into_bytes();
775        empty_name.extend(&committer);
776        empty_name.extend(b"\nmsg");
777        let parsed = Commit::from_bytes(&empty_name, sha1_id).unwrap();
778        assert_eq!(parsed.author.name, "");
779        assert_eq!(parsed.author.email, "mail");
780        assert_eq!(parsed.author.timestamp, 1);
781        assert_eq!(parsed.author.timezone, "+0000");
782        let mut negative_tz = format!("tree {sha1_id}\nauthor a b <m> 7 -0530\n").into_bytes();
783        negative_tz.extend(&committer);
784        negative_tz.extend(b"\nmsg");
785        let parsed = Commit::from_bytes(&negative_tz, sha1_id).unwrap();
786        assert_eq!(parsed.author.name, "a b");
787        assert_eq!(parsed.author.timezone, "-0530");
788        // `committer` line must follow `author` directly.
789        let mut two_authors = format!("tree {sha1_id}\n").into_bytes();
790        two_authors.extend(&author);
791        two_authors.push(b'\n');
792        two_authors.extend(&author);
793        two_authors.extend(b"\nmsg");
794        assert!(matches!(
795            Commit::from_bytes(&two_authors, sha1_id),
796            Err(GitError::InvalidCommitObject)
797        ));
798        let mut non_utf8 = format!("tree {sha1_id}\nauthor ").into_bytes();
799        non_utf8.extend_from_slice(&[0xff, 0xfe]);
800        non_utf8.extend(b" <m> 1 +0000\n");
801        non_utf8.extend(&committer);
802        non_utf8.extend(b"\nmsg");
803        assert!(matches!(
804            Commit::from_bytes(&non_utf8, sha1_id),
805            Err(GitError::InvalidSignatureType(_))
806        ));
807
808        // Tag object reference of the wrong width for the tag's kind.
809        let tag_body = format!(
810            "object {sha1_id}\ntype commit\ntag v1\n{}\n\nmsg",
811            String::from_utf8(signature(SignatureType::Tagger).to_data().unwrap()).unwrap()
812        );
813        match Tag::from_bytes(tag_body.as_bytes(), sha256_id) {
814            Err(GitError::InvalidTagObject(msg)) => {
815                assert!(
816                    msg.contains("sha256") && msg.contains("expected 64"),
817                    "{msg}"
818                )
819            }
820            other => panic!("expected InvalidTagObject, got {other:?}"),
821        }
822        // Non-UTF-8 object id: diagnostic carries kind and expected/actual lengths.
823        let mut raw_tag = b"object ".to_vec();
824        raw_tag.extend_from_slice(&[0xffu8; 40]);
825        raw_tag.extend(b"\ntype commit\ntag v1\n");
826        match Tag::from_bytes(&raw_tag, sha1_id) {
827            Err(GitError::InvalidTagObject(msg)) => {
828                assert!(
829                    msg.contains("sha1")
830                        && msg.contains("expected 40")
831                        && msg.contains("got 40 bytes"),
832                    "{msg}"
833                )
834            }
835            other => panic!("expected InvalidTagObject, got {other:?}"),
836        }
837    }
838}