Skip to main content

heddle_object_model/object/
state_core.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Core state type and its leaf value types (Status, StateSignature,
3//! SignatureStatus, Verification).
4
5use std::collections::BTreeMap;
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use super::{Attribution, ChangeId, ContentHash, Principal, StateId};
11
12// ── Status ──────────────────────────────────────────────────────────
13
14/// Lifecycle status of a state.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
16pub enum Status {
17    #[default]
18    Draft,
19    Published,
20}
21
22impl Status {
23    pub fn to_byte(&self) -> u8 {
24        match self {
25            Status::Draft => 0,
26            Status::Published => 1,
27        }
28    }
29
30    pub fn from_byte(b: u8) -> Option<Self> {
31        match b {
32            0 => Some(Status::Draft),
33            1 => Some(Status::Published),
34            _ => None,
35        }
36    }
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub enum ChangeLineageKind {
41    CherryPick,
42    Collapse,
43    Revert,
44    GitProjection,
45}
46
47impl ChangeLineageKind {
48    fn to_byte(self) -> u8 {
49        match self {
50            Self::CherryPick => 1,
51            Self::Collapse => 2,
52            Self::Revert => 3,
53            Self::GitProjection => 4,
54        }
55    }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
59pub struct ChangeLineage {
60    pub kind: ChangeLineageKind,
61    pub source_change: ChangeId,
62    pub source_state: StateId,
63}
64
65// ── StateSignature ──────────────────────────────────────────────────
66
67/// Signature information for a state.
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub struct StateSignature {
70    pub algorithm: String,
71    pub public_key: String,
72    pub signature: String,
73}
74
75impl StateSignature {
76    pub fn algorithm(&self) -> &str {
77        &self.algorithm
78    }
79}
80
81/// Signature verification result.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum SignatureStatus {
84    Valid,
85    Legacy,
86    Invalid,
87    Unsigned,
88}
89
90impl SignatureStatus {
91    pub fn is_valid(self) -> bool {
92        self == SignatureStatus::Valid
93    }
94
95    pub fn is_unsigned(self) -> bool {
96        self == SignatureStatus::Unsigned
97    }
98
99    pub fn is_legacy(self) -> bool {
100        self == SignatureStatus::Legacy
101    }
102}
103
104// ── Verification ────────────────────────────────────────────────────
105
106/// Verification information for a state.
107#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
108pub struct Verification {
109    pub tests_passed: Option<bool>,
110    pub tests_failed: Option<u32>,
111    pub coverage_pct: Option<f32>,
112    pub coverage_delta: Option<f32>,
113    pub lint_warnings: Option<u32>,
114    #[serde(default)]
115    pub custom: BTreeMap<String, serde_json::Value>,
116}
117
118impl Verification {
119    pub fn new() -> Self {
120        Self::default()
121    }
122
123    pub fn with_tests_passed(mut self, passed: bool) -> Self {
124        self.tests_passed = Some(passed);
125        self
126    }
127
128    pub fn with_tests_failed(mut self, failed: u32) -> Self {
129        self.tests_failed = Some(failed);
130        self
131    }
132
133    pub fn is_empty(&self) -> bool {
134        self.tests_passed.is_none()
135            && self.tests_failed.is_none()
136            && self.coverage_pct.is_none()
137            && self.coverage_delta.is_none()
138            && self.lint_warnings.is_none()
139            && self.custom.is_empty()
140    }
141
142    pub(crate) fn hash_len(&self) -> usize {
143        let mut len = 0;
144        len += 1 + self.tests_passed.map(|_| 1).unwrap_or(0);
145        len += 1 + self.tests_failed.map(|_| 4).unwrap_or(0);
146        len += 1 + self.coverage_pct.map(|_| 4).unwrap_or(0);
147        len += 1 + self.coverage_delta.map(|_| 4).unwrap_or(0);
148        len += 1 + self.lint_warnings.map(|_| 4).unwrap_or(0);
149        len += 4;
150        for (key, value) in &self.custom {
151            let value_bytes = serde_json::to_vec(value).unwrap_or_default();
152            len += 4 + key.len();
153            len += 4 + value_bytes.len();
154        }
155        len
156    }
157
158    pub(crate) fn update_hasher(&self, hasher: &mut blake3::Hasher) {
159        let tests_passed = self.tests_passed.map(u8::from);
160        write_optional_u8(hasher, tests_passed);
161        write_optional_u32(hasher, self.tests_failed);
162        write_optional_f32(hasher, self.coverage_pct);
163        write_optional_f32(hasher, self.coverage_delta);
164        write_optional_u32(hasher, self.lint_warnings);
165        let custom_len = self.custom.len() as u32;
166        hasher.update(&custom_len.to_le_bytes());
167        for (key, value) in &self.custom {
168            let key_bytes = key.as_bytes();
169            let value_bytes = serde_json::to_vec(value).unwrap_or_default();
170            hasher.update(&(key_bytes.len() as u32).to_le_bytes());
171            hasher.update(key_bytes);
172            hasher.update(&(value_bytes.len() as u32).to_le_bytes());
173            hasher.update(&value_bytes);
174        }
175    }
176}
177
178fn write_optional_u8(hasher: &mut blake3::Hasher, value: Option<u8>) {
179    match value {
180        Some(v) => {
181            hasher.update(&[1]);
182            hasher.update(&[v]);
183        }
184        None => {
185            hasher.update(&[0]);
186        }
187    }
188}
189
190fn write_optional_u32(hasher: &mut blake3::Hasher, value: Option<u32>) {
191    match value {
192        Some(v) => {
193            hasher.update(&[1]);
194            hasher.update(&v.to_le_bytes());
195        }
196        None => {
197            hasher.update(&[0]);
198        }
199    }
200}
201
202fn write_optional_f32(hasher: &mut blake3::Hasher, value: Option<f32>) {
203    match value {
204        Some(v) => {
205            hasher.update(&[1]);
206            hasher.update(&v.to_le_bytes());
207        }
208        None => {
209            hasher.update(&[0]);
210        }
211    }
212}
213
214// ── State ───────────────────────────────────────────────────────────
215
216/// Immutable source-history state. `state_id` is recomputed from every encoded
217/// field; mutable repository metadata lives in `StateAttachment` objects.
218#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
219pub struct State {
220    #[serde(skip)]
221    pub state_id: StateId,
222    pub change_id: ChangeId,
223    pub tree: ContentHash,
224    pub parents: Vec<StateId>,
225    pub attribution: Attribution,
226    pub intent: Option<String>,
227    pub confidence: Option<f32>,
228    pub created_at: DateTime<Utc>,
229    pub verification: Option<Verification>,
230    pub status: Status,
231    // --- tail-only optional fields below. Add new fields here, never above. ---
232    #[serde(default)]
233    pub provenance: Option<ContentHash>,
234    /// Authoring timestamp for this state, when distinct from
235    /// `created_at`.
236    ///
237    /// `created_at` is the *committer* time — when the state object
238    /// came into being in its current form. `authored_at` is the
239    /// *author* time — when someone actually wrote the change — which
240    /// survives `git rebase`, cherry-pick, squash-merge, and `git
241    /// commit --amend`. The ingest-backed `import git` path fills
242    /// this from the git author time; native heddle commits leave it
243    /// `None` and blame falls back to `created_at`.
244    ///
245    /// **Part of the state hash (#564 de-lossy step 1).** Author time
246    /// is part of a git commit's identity: two commits that differ
247    /// *only* by author timestamp are distinct git objects, so folding
248    /// it into the hash keeps them from dedup-colliding to one State in
249    /// the content-addressed store. `None` hashes as a single absence
250    /// byte, so native commits are unaffected beyond the format bump.
251    #[serde(default)]
252    pub authored_at: Option<DateTime<Utc>>,
253    // --- git-fidelity fields (#564 de-lossy step 1, #565) ---
254    //
255    // These preserve the parts of an imported git commit that Heddle's
256    // model used to drop, so a commit can be byte-reconstructed later
257    // (#566/#567) and the git mirror can be eliminated (#568). UNLIKE the
258    // W1 tail fields above, these ARE part of the content hash (see
259    // `update_hash`): two git-distinct commits that differ only in
260    // committer, timezone, verbatim message, gpgsig, or extra headers must
261    // hash differently so they can't dedup-collide in the content-addressed
262    // store. They are still tail-append + `#[serde(default)]` so legacy
263    // on-disk states keep deserializing.
264    /// The git committer identity, when distinct from the author
265    /// ([`Attribution::principal`]). Git records both an author (who wrote
266    /// the change) and a committer (who created this commit object); for
267    /// rebased / cherry-picked / amended commits the two differ. `None`
268    /// for native heddle commits and for legacy imports from before #565.
269    #[serde(default)]
270    pub committer: Option<Principal>,
271    /// Timezone offset (seconds east of UTC) of the *author* timestamp
272    /// ([`State::authored_at`] / `created_at` fallback). Git stores the
273    /// author's local offset (e.g. `+0000`, `-0700`); Heddle used to
274    /// discard it. `0` for native commits and legacy imports.
275    #[serde(default)]
276    pub authored_tz_offset: i32,
277    /// Timezone offset (seconds east of UTC) of the *committer* timestamp
278    /// (`created_at`). `0` for native commits and legacy imports.
279    #[serde(default)]
280    pub committer_tz_offset: i32,
281    /// The verbatim git commit message body (everything after the header
282    /// block), preserved exactly so reconstruction is byte-stable. Distinct
283    /// from `intent`, which is the trimmed first line surfaced in the UI.
284    /// `None` for native commits and legacy imports.
285    ///
286    /// Stored as raw bytes, NOT a `String`: a commit with a non-UTF8
287    /// `encoding` (latin-1, shift-jis, …) carries message bytes that are not
288    /// valid UTF-8 (e.g. `0xe9` for latin-1 `é`); a `String` could not
289    /// round-trip them byte-identically. (non-UTF8 author/committer identity
290    /// *names* are not yet byte-preserved — `Principal` is still `String`; see
291    /// #564.)
292    #[serde(default)]
293    pub raw_message: Option<Vec<u8>>,
294    /// The SINGLE canonical "this state's content is NOT byte-faithful to the
295    /// original git object" marker (#567). Set to `true` by lossy import
296    /// population paths whenever an unrepresentable tree entry was dropped or
297    /// converted during import, so the rebuilt tree (hence commit) no longer
298    /// hashes to the original SHA. The git-export fidelity guard reads this one
299    /// flag to decide whether reconstruct-from-state is safe, instead of
300    /// enumerating import surfaces. `false` for native heddle commits and for
301    /// lossless imports.
302    ///
303    /// Provenance metadata, NOT part of the content hash: a lossy import always
304    /// drops/converts tree entries, so its tree — and therefore the rest of the
305    /// hashed identity — already differs from a lossless import of the same
306    /// source; folding the flag in would add nothing but break every existing
307    /// content hash.
308    #[serde(default)]
309    pub git_lossy: bool,
310    /// Every git commit header beyond the ones Heddle models natively
311    /// (tree/parents/author/committer), in their original order. ORDER IS
312    /// LOAD-BEARING for #566 byte-exactness — this is a `Vec`, never a map.
313    /// Empty for native commits and legacy imports.
314    ///
315    /// `gpgsig` is just one of these headers and is kept INLINE at its
316    /// captured ordinal (not split into a separate field): when a commit's
317    /// extension headers are in non-canonical order — e.g. `x-custom`, then
318    /// `gpgsig`, then `mergetag` — splitting gpgsig out would lose its
319    /// position and break byte-identical reconstruction. The serialization
320    /// source of truth for the signature is its position here (spike §3).
321    ///
322    /// Both the header name and value are raw bytes (`Vec<u8>`), NOT
323    /// `String`s: extra-header VALUES (a `mergetag` payload is a full tag
324    /// object; custom headers; gpgsig armor) can be non-UTF8, so a
325    /// `String` would force a lossy `to_string()` that destroys those bytes.
326    /// Names are ASCII by git's spec but are bytes too so the whole tuple is
327    /// byte-exact and no conversion sneaks in.
328    #[serde(default)]
329    pub extra_headers: Vec<(Vec<u8>, Vec<u8>)>,
330    pub lineage: Vec<ChangeLineage>,
331}
332
333impl State {
334    pub fn new(tree: ContentHash, parents: Vec<StateId>, attribution: Attribution) -> Self {
335        Self::new_snapshot(tree, parents, attribution)
336    }
337
338    pub fn new_snapshot(
339        tree: ContentHash,
340        parents: Vec<StateId>,
341        attribution: Attribution,
342    ) -> Self {
343        Self::new_with_change_id(tree, parents, attribution, ChangeId::generate())
344    }
345
346    pub fn new_merge(tree: ContentHash, parents: Vec<StateId>, attribution: Attribution) -> Self {
347        Self::new_snapshot(tree, parents, attribution)
348    }
349
350    pub fn new_refresh_of(
351        tree: ContentHash,
352        parents: Vec<StateId>,
353        attribution: Attribution,
354        change_id: ChangeId,
355    ) -> Self {
356        Self::new_with_change_id(tree, parents, attribution, change_id)
357    }
358
359    pub fn new_fork_of(tree: ContentHash, parents: Vec<StateId>, attribution: Attribution) -> Self {
360        Self::new_snapshot(tree, parents, attribution)
361    }
362
363    pub fn new_collapse_of(
364        tree: ContentHash,
365        parents: Vec<StateId>,
366        attribution: Attribution,
367    ) -> Self {
368        Self::new_snapshot(tree, parents, attribution)
369    }
370
371    fn new_with_change_id(
372        tree: ContentHash,
373        parents: Vec<StateId>,
374        attribution: Attribution,
375        change_id: ChangeId,
376    ) -> Self {
377        let mut state = Self {
378            state_id: StateId::default(),
379            change_id,
380            tree,
381            parents,
382            attribution,
383            intent: None,
384            confidence: None,
385            created_at: Utc::now(),
386            verification: None,
387            provenance: None,
388            authored_at: None,
389            committer: None,
390            authored_tz_offset: 0,
391            committer_tz_offset: 0,
392            raw_message: None,
393            git_lossy: false,
394            extra_headers: Vec::new(),
395            lineage: Vec::new(),
396            status: Status::Draft,
397        };
398        state.refresh_state_id();
399        state
400    }
401
402    pub fn with_intent(mut self, intent: impl Into<String>) -> Self {
403        self.intent = Some(intent.into());
404        self.refresh_state_id();
405        self
406    }
407
408    pub fn with_confidence(mut self, confidence: f32) -> Self {
409        self.confidence = Some(confidence.clamp(0.0, 1.0));
410        self.refresh_state_id();
411        self
412    }
413
414    pub fn with_verification(mut self, verification: Verification) -> Self {
415        self.verification = Some(verification);
416        self.refresh_state_id();
417        self
418    }
419
420    pub fn with_provenance(mut self, provenance: ContentHash) -> Self {
421        self.provenance = Some(provenance);
422        self.refresh_state_id();
423        self
424    }
425
426    /// Record the authoring timestamp separately from `created_at`.
427    /// Used by the git-ingest importer to preserve the distinction
428    /// between "when the change was originally written" (authored)
429    /// and "when this commit object came into being" (committer time,
430    /// stored in `created_at` so re-imports stay deterministic).
431    /// Native heddle commits leave this `None`; blame display then
432    /// falls back to `created_at`.
433    ///
434    /// **Part of the state hash (#564 de-lossy step 1)** — see the
435    /// `authored_at` field docs and `update_hash`.
436    pub fn with_authored_at(mut self, timestamp: DateTime<Utc>) -> Self {
437        self.authored_at = Some(timestamp);
438        self.refresh_state_id();
439        self
440    }
441
442    /// Record the git committer identity (distinct from the author).
443    ///
444    /// **Part of the state hash** — see the `committer` field docs and
445    /// `update_hash`. #564 de-lossy step 1.
446    pub fn with_committer(mut self, committer: Principal) -> Self {
447        self.committer = Some(committer);
448        self.refresh_state_id();
449        self
450    }
451
452    /// Record the author/committer timezone offsets (seconds east of UTC).
453    /// **Part of the state hash.** #564 de-lossy step 1.
454    pub fn with_tz_offsets(mut self, authored: i32, committer: i32) -> Self {
455        self.authored_tz_offset = authored;
456        self.committer_tz_offset = committer;
457        self.refresh_state_id();
458        self
459    }
460
461    /// Record the verbatim git commit message body, as raw bytes (so a
462    /// non-UTF8 message round-trips byte-identically; see the `raw_message`
463    /// field docs). **Part of the state hash.** #564 de-lossy step 1.
464    pub fn with_raw_message(mut self, raw_message: impl AsRef<[u8]>) -> Self {
465        self.raw_message = Some(raw_message.as_ref().to_vec());
466        self.refresh_state_id();
467        self
468    }
469
470    /// Mark this state's content as NOT byte-faithful to the original git
471    /// object — set by the `--lossy` import/ingest paths when a tree entry was
472    /// dropped or converted. The git-export fidelity guard reads this single
473    /// signal to skip reconstruct-from-state (#567). Not part of the content
474    /// hash (see the `git_lossy` field docs).
475    pub fn with_git_lossy(mut self, git_lossy: bool) -> Self {
476        self.git_lossy = git_lossy;
477        self.refresh_state_id();
478        self
479    }
480
481    /// Record the ordered remaining git commit headers as raw bytes. ORDER
482    /// IS LOAD-BEARING (#566). **Part of the state hash.** #564 de-lossy
483    /// step 1.
484    pub fn with_extra_headers(mut self, extra_headers: Vec<(Vec<u8>, Vec<u8>)>) -> Self {
485        self.extra_headers = extra_headers;
486        self.refresh_state_id();
487        self
488    }
489
490    pub fn with_lineage(mut self, lineage: Vec<ChangeLineage>) -> Self {
491        self.lineage = lineage;
492        self.refresh_state_id();
493        self
494    }
495
496    pub fn with_status(mut self, status: Status) -> Self {
497        self.status = status;
498        self.refresh_state_id();
499        self
500    }
501
502    pub fn with_change_id(mut self, change_id: ChangeId) -> Self {
503        self.change_id = change_id;
504        self.refresh_state_id();
505        self
506    }
507
508    pub fn with_timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
509        self.created_at = timestamp;
510        self.refresh_state_id();
511        self
512    }
513
514    pub fn compute_hash(&self) -> ContentHash {
515        let content_len = self.hash_len();
516        ContentHash::compute_typed_with_len("state", content_len, |hasher| {
517            self.update_hash(hasher);
518        })
519    }
520
521    pub fn hash(&mut self) -> ContentHash {
522        self.refresh_state_id();
523        self.state_id.as_content_hash()
524    }
525
526    pub fn id(&self) -> StateId {
527        StateId::from_content_hash(self.compute_hash())
528    }
529
530    /// Encode the canonical named-field msgpack representation used in packs
531    /// and object transfer. Local loose storage may wrap a different encoding,
532    /// but it must not redefine the portable object body.
533    pub fn encode_current_msgpack(&self) -> crate::error::Result<Vec<u8>> {
534        Ok(rmp_serde::to_vec_named(self)?)
535    }
536
537    /// Decode the canonical named-field msgpack representation and restore the
538    /// derived in-memory id omitted from serde.
539    pub fn decode_current_msgpack(bytes: &[u8]) -> crate::error::Result<Self> {
540        let mut state: Self = rmp_serde::from_slice(bytes)?;
541        state.refresh_state_id();
542        Ok(state)
543    }
544
545    /// Format-4 identity for agent states hashed before `thought_level` and
546    /// `parent` entered the transcript. Graph edges keep this id.
547    pub fn pre_cursor_id(&self) -> StateId {
548        StateId::from_content_hash(self.compute_pre_cursor_hash())
549    }
550
551    /// Accept the current id, or a format-4 agent id that omitted unpublished
552    /// cursor fields. Published cursor fields require the current hash.
553    pub fn accepts_stored_id(&self, stored: &StateId) -> bool {
554        if self.id() == *stored {
555            return true;
556        }
557        let unpublished_cursor = self
558            .attribution
559            .agent
560            .as_ref()
561            .is_none_or(|agent| agent.thought_level.is_none() && agent.parent.is_none());
562        unpublished_cursor && self.pre_cursor_id() == *stored
563    }
564
565    /// Content hash that produced `stored` when this state accepts that id.
566    ///
567    /// Format-4 agent states keep a pre-cursor id. Verification and re-signing
568    /// must use that hash, not the current format-5 [`Self::compute_hash`].
569    pub fn hash_for_stored_id(&self, stored: &StateId) -> ContentHash {
570        if self.id() == *stored {
571            self.compute_hash()
572        } else if self.accepts_stored_id(stored) {
573            self.compute_pre_cursor_hash()
574        } else {
575            self.compute_hash()
576        }
577    }
578
579    pub fn is_root(&self) -> bool {
580        self.parents.is_empty()
581    }
582
583    pub fn is_merge(&self) -> bool {
584        self.parents.len() > 1
585    }
586
587    pub fn is_agent_authored(&self) -> bool {
588        self.attribution.agent.is_some()
589    }
590
591    pub fn first_parent(&self) -> Option<&StateId> {
592        self.parents.first()
593    }
594
595    fn hash_len(&self) -> u64 {
596        self.hash_len_core() + self.hash_len_fidelity()
597    }
598
599    fn hash_len_pre_cursor(&self) -> u64 {
600        self.hash_len_core_pre_cursor() + self.hash_len_fidelity()
601    }
602
603    /// Hashed length of the core state fields. Mirrors [`Self::update_hash_core`].
604    fn hash_len_core(&self) -> u64 {
605        self.hash_len_core_versioned(true)
606    }
607
608    fn hash_len_core_pre_cursor(&self) -> u64 {
609        self.hash_len_core_versioned(false)
610    }
611
612    fn hash_len_core_versioned(&self, include_cursor_fields: bool) -> u64 {
613        let principal = &self.attribution.principal;
614        let mut len = 0u64;
615
616        len += 16;
617
618        len += self.tree.as_bytes().len() as u64;
619        len += 4;
620        len += (self.parents.len() * 32) as u64;
621
622        len += principal.name.len() as u64 + 1;
623        len += principal.email.len() as u64 + 1;
624
625        len += 1;
626        if let Some(agent) = &self.attribution.agent {
627            len += agent.provider.len() as u64 + 1;
628            len += agent.model.len() as u64 + 1;
629
630            len += 1;
631            if let Some(session_id) = &agent.session_id {
632                len += session_id.len() as u64 + 1;
633            }
634
635            len += 1;
636            if let Some(segment_id) = &agent.segment_id {
637                len += segment_id.len() as u64 + 1;
638            }
639
640            len += 1;
641            if let Some(policy_id) = &agent.policy_id {
642                len += policy_id.len() as u64 + 1;
643            }
644
645            if include_cursor_fields {
646                len += 1;
647                if let Some(thought_level) = &agent.thought_level {
648                    len += thought_level.len() as u64 + 1;
649                }
650
651                len += 1;
652                if let Some(parent) = &agent.parent {
653                    len += parent.len() as u64 + 1;
654                }
655            }
656        }
657
658        len += 1;
659        if let Some(intent) = &self.intent {
660            len += intent.len() as u64 + 1;
661        }
662
663        len += 1;
664        if self.confidence.is_some() {
665            len += 4;
666        }
667
668        len += 8;
669
670        len += 1;
671        if let Some(verification) = &self.verification {
672            len += verification.hash_len() as u64;
673        }
674
675        len += 1;
676        if self.provenance.is_some() {
677            len += 32;
678        }
679
680        len += 1;
681
682        len
683    }
684
685    /// Hashed length of the appended git-fidelity block (#565). Mirrors
686    /// [`Self::update_hash_fidelity`] byte-for-byte. Kept separate from
687    /// [`Self::hash_len_core`] so the migration-only pre-bump hash can omit it
688    /// exactly.
689    fn hash_len_fidelity(&self) -> u64 {
690        let mut len = 0u64;
691
692        // git-fidelity fields (#564 step 1). Must mirror `update_hash`
693        // byte-for-byte. committer: 1 tag byte + (name+NUL, email+NUL).
694        len += 1;
695        if let Some(committer) = &self.committer {
696            len += committer.name.len() as u64 + 1;
697            len += committer.email.len() as u64 + 1;
698        }
699        // both tz offsets: i32 LE, always present.
700        len += 4;
701        len += 4;
702        // authored_at (author time): 1 tag byte + (i64 LE when Some).
703        len += 1;
704        if self.authored_at.is_some() {
705            len += 8;
706        }
707        // raw_message: optional-bytes framing (1 tag + u32 len + bytes) — a
708        // length prefix, not NUL-termination, since the message can contain
709        // NUL bytes (it's byte-typed for non-UTF8 fidelity).
710        len += 1;
711        if let Some(raw_message) = &self.raw_message {
712            len += 4 + raw_message.len() as u64;
713        }
714        // extra_headers (gpgsig rides inline here at its captured position):
715        // u32 count, then per pair u32 key_len+key, u32 val_len+val.
716        len += 4;
717        for (key, value) in &self.extra_headers {
718            len += 4 + key.len() as u64;
719            len += 4 + value.len() as u64;
720        }
721        len += 4 + (self.lineage.len() as u64 * 49);
722
723        len
724    }
725
726    fn update_hash(&self, hasher: &mut blake3::Hasher) {
727        self.update_hash_core(hasher);
728        self.update_hash_fidelity(hasher);
729    }
730
731    fn compute_pre_cursor_hash(&self) -> ContentHash {
732        let content_len = self.hash_len_pre_cursor();
733        ContentHash::compute_typed_with_len("state", content_len, |hasher| {
734            self.update_hash_pre_cursor(hasher);
735        })
736    }
737
738    fn update_hash_pre_cursor(&self, hasher: &mut blake3::Hasher) {
739        self.update_hash_core_pre_cursor(hasher);
740        self.update_hash_fidelity(hasher);
741    }
742
743    /// Hash the pre-#565 fields (everything through the status byte). Mirrors
744    /// [`Self::hash_len_core`]. The migration-only pre-bump hash is exactly
745    /// this with no fidelity block appended.
746    fn update_hash_core(&self, hasher: &mut blake3::Hasher) {
747        self.update_hash_core_versioned(hasher, true);
748    }
749
750    fn update_hash_core_pre_cursor(&self, hasher: &mut blake3::Hasher) {
751        self.update_hash_core_versioned(hasher, false);
752    }
753
754    fn update_hash_core_versioned(&self, hasher: &mut blake3::Hasher, include_cursor_fields: bool) {
755        let principal = &self.attribution.principal;
756
757        hasher.update(self.change_id.as_bytes());
758
759        hasher.update(self.tree.as_bytes());
760        hasher.update(&(self.parents.len() as u32).to_le_bytes());
761        for parent in &self.parents {
762            hasher.update(parent.as_bytes());
763        }
764
765        hasher.update(&principal.name);
766        hasher.update(&[0]);
767        hasher.update(&principal.email);
768        hasher.update(&[0]);
769
770        if let Some(agent) = &self.attribution.agent {
771            hasher.update(&[1]);
772            hasher.update(agent.provider.as_bytes());
773            hasher.update(&[0]);
774            hasher.update(agent.model.as_bytes());
775            hasher.update(&[0]);
776            write_optional_string(hasher, &agent.session_id);
777            write_optional_string(hasher, &agent.segment_id);
778            write_optional_string(hasher, &agent.policy_id);
779            if include_cursor_fields {
780                write_optional_string(hasher, &agent.thought_level);
781                write_optional_string(hasher, &agent.parent);
782            }
783        } else {
784            hasher.update(&[0]);
785        }
786
787        write_optional_string(hasher, &self.intent);
788
789        if let Some(confidence) = self.confidence {
790            hasher.update(&[1]);
791            hasher.update(&confidence.to_le_bytes());
792        } else {
793            hasher.update(&[0]);
794        }
795
796        hasher.update(&self.created_at.timestamp().to_le_bytes());
797
798        if let Some(verification) = &self.verification {
799            hasher.update(&[1]);
800            verification.update_hasher(hasher);
801        } else {
802            hasher.update(&[0]);
803        }
804
805        if let Some(provenance) = self.provenance {
806            hasher.update(&[1]);
807            hasher.update(provenance.as_bytes());
808        } else {
809            hasher.update(&[0]);
810        }
811
812        hasher.update(&[self.status.to_byte()]);
813    }
814
815    /// Hash the appended git-fidelity block (#565). Mirrors
816    /// [`Self::hash_len_fidelity`]. Kept separate from
817    /// [`Self::update_hash_core`] so the migration-only pre-bump hash can omit
818    /// it exactly.
819    ///
820    /// git-fidelity fields (#564 de-lossy step 1, #565) are DELIBERATELY part
821    /// of the content hash — the opposite of the W1 tail fields. Two git
822    /// commits that differ only in committer, author/committer time, timezone,
823    /// verbatim message, or extra headers (gpgsig included) are distinct git
824    /// objects; folding these into identity prevents them from dedup-colliding
825    /// to one State in the content-addressed store. This re-hashes every
826    /// pre-#565 state (a real format bump; acceptable pre-0.3). Keep this in
827    /// sync with `hash_len_fidelity`.
828    fn update_hash_fidelity(&self, hasher: &mut blake3::Hasher) {
829        if let Some(committer) = &self.committer {
830            hasher.update(&[1]);
831            hasher.update(&committer.name);
832            hasher.update(&[0]);
833            hasher.update(&committer.email);
834            hasher.update(&[0]);
835        } else {
836            hasher.update(&[0]);
837        }
838
839        hasher.update(&self.authored_tz_offset.to_le_bytes());
840        hasher.update(&self.committer_tz_offset.to_le_bytes());
841
842        // Author time (#564): committer time is hashed above as created_at;
843        // author time is the other half of a git commit's temporal identity.
844        if let Some(authored_at) = self.authored_at {
845            hasher.update(&[1]);
846            hasher.update(&authored_at.timestamp().to_le_bytes());
847        } else {
848            hasher.update(&[0]);
849        }
850
851        write_optional_bytes(hasher, &self.raw_message);
852
853        // extra_headers (gpgsig is one of these, kept inline at its position).
854        hasher.update(&(self.extra_headers.len() as u32).to_le_bytes());
855        for (key, value) in &self.extra_headers {
856            hasher.update(&(key.len() as u32).to_le_bytes());
857            hasher.update(key);
858            hasher.update(&(value.len() as u32).to_le_bytes());
859            hasher.update(value);
860        }
861        hasher.update(&(self.lineage.len() as u32).to_le_bytes());
862        for lineage in &self.lineage {
863            hasher.update(&[lineage.kind.to_byte()]);
864            hasher.update(lineage.source_change.as_bytes());
865            hasher.update(lineage.source_state.as_bytes());
866        }
867    }
868
869    fn refresh_state_id(&mut self) {
870        self.state_id = StateId::from_content_hash(self.compute_hash());
871    }
872}
873
874/// Length-prefixed optional-bytes framing for the hash: `[1] + u32-LE len +
875/// bytes` when `Some`, a single `[0]` when `None`. Unlike
876/// [`write_optional_string`]'s NUL-terminated framing this is binary-safe —
877/// `raw_message` can contain NUL bytes, so a length prefix (not a terminator)
878/// is required to keep the hash unambiguous.
879fn write_optional_bytes(hasher: &mut blake3::Hasher, value: &Option<Vec<u8>>) {
880    match value {
881        Some(bytes) => {
882            hasher.update(&[1]);
883            hasher.update(&(bytes.len() as u32).to_le_bytes());
884            hasher.update(bytes);
885        }
886        None => {
887            hasher.update(&[0]);
888        }
889    }
890}
891
892fn write_optional_string(hasher: &mut blake3::Hasher, value: &Option<String>) {
893    match value {
894        Some(value) => {
895            hasher.update(&[1]);
896            hasher.update(value.as_bytes());
897            hasher.update(&[0]);
898        }
899        None => {
900            hasher.update(&[0]);
901        }
902    }
903}
904
905/// Parse the *extension* headers from a raw git commit object's content bytes
906/// (the bytes `git cat-file commit <sha>` prints — i.e. gix's `Commit::data`),
907/// in their exact on-the-wire order, ready to store in [`State::extra_headers`].
908///
909/// A commit's header block runs from the start of the content up to the first
910/// blank line (the header/body separator). Its leading headers are always, in
911/// fixed order, `tree`, zero-or-more `parent`, `author`, `committer`; Heddle
912/// models those natively. Every header **after** `committer` is an extension
913/// header (`encoding`, `gpgsig`, `mergetag`, or any unknown/future name) and is
914/// returned here as a `(name, value)` byte pair at its real position.
915///
916/// **This is the single source of truth for extension-header order and bytes.**
917/// Both git import paths (the CLI bridge and the ingest walker) build
918/// `extra_headers` from it. The alternative — stitching the vec back together
919/// from a decoder's *typed* accessors (gix surfaces `encoding`, and historically
920/// `gpgsig`, as fields *outside* its `extra_headers`) — silently reorders the
921/// headers git happens to model as typed fields, which breaks #566 byte-exact
922/// reconstruction. So we never consult those typed accessors for position; the
923/// raw header block is authoritative. (#564 de-lossy step 1 — close-the-class.)
924///
925/// Folded continuation lines (a value line beginning with a single space
926/// `0x20`, used by `gpgsig`/`mergetag`) are **unfolded**: each continuation
927/// contributes a `\n` plus the line with exactly one leading space stripped, so
928/// the stored value holds the value's real internal newlines with no trailing
929/// newline. The serializer (#566) re-folds by mapping every `\n` back to `\n `
930/// (spike §2). A "blank" line inside an armored value is ` \n` on the wire (one
931/// space), so it unfolds to an empty segment — never confused with the
932/// header/body separator, which is a truly empty line.
933pub fn parse_commit_extension_headers(commit_content: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
934    // The header block ends at the first *empty* line. Folded "blank" lines
935    // inside an armored value are ` \n` (a single space), never empty, so the
936    // first `\n\n` reliably marks the header/body boundary.
937    let header_block = match find_subslice(commit_content, b"\n\n") {
938        Some(idx) => &commit_content[..idx],
939        // No separator (malformed / header-only) — treat all of it as headers.
940        None => commit_content,
941    };
942
943    // Collect every logical header (name, unfolded value) in order; the
944    // extension headers are the ones after the `committer` line.
945    let mut headers: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
946    for line in header_block.split(|&b| b == b'\n') {
947        if line.first() == Some(&b' ') {
948            // Continuation of the current header value: restore the newline
949            // that folding replaced and strip exactly one leading space.
950            if let Some((_, value)) = headers.last_mut() {
951                value.push(b'\n');
952                value.extend_from_slice(&line[1..]);
953            }
954            // A continuation with no preceding header is malformed git; skip it
955            // rather than panic.
956            continue;
957        }
958        // New header: `name<SP>value`. A header line with no space is degenerate
959        // (git never emits one in this region) — record it with an empty value
960        // so no bytes are silently dropped.
961        let (name, value) = match line.iter().position(|&b| b == b' ') {
962            Some(sp) => (line[..sp].to_vec(), line[sp + 1..].to_vec()),
963            None => (line.to_vec(), Vec::new()),
964        };
965        headers.push((name, value));
966    }
967
968    // Extension headers are everything strictly after `committer`. git always
969    // emits exactly one committer line ahead of the extension headers; if it is
970    // somehow absent, fall back to excluding the four core names so nothing is
971    // silently dropped or mis-captured.
972    match headers.iter().position(|(name, _)| name == b"committer") {
973        Some(idx) => headers.split_off(idx + 1),
974        None => headers
975            .into_iter()
976            .filter(|(name, _)| {
977                !matches!(
978                    name.as_slice(),
979                    b"tree" | b"parent" | b"author" | b"committer"
980                )
981            })
982            .collect(),
983    }
984}
985
986/// Index of the first occurrence of `needle` in `haystack`, or `None`.
987fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
988    if needle.is_empty() || needle.len() > haystack.len() {
989        return None;
990    }
991    haystack.windows(needle.len()).position(|w| w == needle)
992}
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997    use crate::object::Principal;
998
999    fn sample_attribution() -> Attribution {
1000        Attribution::human(Principal::new("Alice", "alice@example.com"))
1001    }
1002
1003    #[test]
1004    fn format4_agent_states_keep_pre_cursor_id_when_cursor_fields_are_unpublished() {
1005        use crate::object::Agent;
1006
1007        let created_at = DateTime::from_timestamp(1_700_000_000, 0).expect("fixed test timestamp");
1008        let tree = ContentHash::from_bytes([11; 32]);
1009        let mut agent_state = State::new(
1010            tree,
1011            Vec::new(),
1012            Attribution::with_agent(
1013                Principal::new("Author", "author@example.com"),
1014                Agent::new("anthropic", "opus"),
1015            ),
1016        );
1017        agent_state.created_at = created_at;
1018        agent_state.state_id = agent_state.id();
1019        assert_ne!(
1020            agent_state.id(),
1021            agent_state.pre_cursor_id(),
1022            "None cursor tags must change the current id of every agent state"
1023        );
1024        assert!(
1025            agent_state.accepts_stored_id(&agent_state.pre_cursor_id()),
1026            "format-4 agent ids must still validate after the cursor hash bump"
1027        );
1028        assert!(agent_state.accepts_stored_id(&agent_state.id()));
1029
1030        let mut published = agent_state.clone();
1031        published.attribution.agent = Some(
1032            Agent::new("anthropic", "opus")
1033                .with_thought_level("high")
1034                .with_parent("agent-1"),
1035        );
1036        published.state_id = published.id();
1037        assert!(
1038            !published.accepts_stored_id(&agent_state.pre_cursor_id()),
1039            "published cursor fields must not validate against a format-4 id"
1040        );
1041        assert_ne!(published.id(), agent_state.id());
1042
1043        let mut human = State::new(
1044            tree,
1045            Vec::new(),
1046            Attribution::human(Principal::new("Author", "author@example.com")),
1047        );
1048        human.created_at = created_at;
1049        assert_eq!(
1050            human.id(),
1051            human.pre_cursor_id(),
1052            "human states never hashed the agent cursor tags"
1053        );
1054        assert_eq!(
1055            agent_state.hash_for_stored_id(&agent_state.pre_cursor_id()),
1056            agent_state.compute_pre_cursor_hash(),
1057            "accepted format-4 ids must verify against the preserved hash"
1058        );
1059        assert_eq!(
1060            agent_state.hash_for_stored_id(&agent_state.id()),
1061            agent_state.compute_hash()
1062        );
1063    }
1064
1065    #[test]
1066    fn new_snapshot_sets_fresh_logical_identity() {
1067        let state =
1068            State::new_snapshot(ContentHash::compute(b"tree"), vec![], sample_attribution());
1069        assert!(!state.change_id.is_zero());
1070        assert_eq!(state.state_id, state.id());
1071    }
1072
1073    #[test]
1074    fn new_refresh_preserves_explicit_logical_identity() {
1075        let logical_change_id = ChangeId::from_bytes([7; 16]);
1076        let state = State::new_refresh_of(
1077            ContentHash::compute(b"tree"),
1078            vec![],
1079            sample_attribution(),
1080            logical_change_id,
1081        );
1082        assert_eq!(state.change_id, logical_change_id);
1083    }
1084
1085    #[test]
1086    fn new_merge_uses_fresh_logical_identity() {
1087        let state = State::new_merge(
1088            ContentHash::compute(b"tree"),
1089            vec![StateId::from_bytes([1; 32]), StateId::from_bytes([2; 32])],
1090            sample_attribution(),
1091        );
1092        assert!(!state.change_id.is_zero());
1093        assert!(state.is_merge());
1094    }
1095
1096    #[test]
1097    fn with_change_id_invalidates_cached_hash_when_logical_identity_changes() {
1098        let mut state =
1099            State::new_snapshot(ContentHash::compute(b"tree"), vec![], sample_attribution());
1100        let original_hash = state.hash();
1101        let replacement = ChangeId::from_bytes([9; 16]);
1102
1103        let mut updated = state.with_change_id(replacement);
1104
1105        assert_eq!(updated.change_id, replacement);
1106        assert_ne!(updated.hash(), original_hash);
1107        assert_eq!(updated.hash(), updated.compute_hash());
1108    }
1109
1110    #[test]
1111    fn agent_segment_is_part_of_state_hash() {
1112        let principal = Principal::new("Alice", "alice@example.com");
1113        let attribution_a = Attribution::with_agent(
1114            principal.clone(),
1115            crate::object::Agent::new("openai", "gpt-5").with_session("sess-1", "seg-1"),
1116        );
1117        let attribution_b = Attribution::with_agent(
1118            principal,
1119            crate::object::Agent::new("openai", "gpt-5").with_session("sess-1", "seg-2"),
1120        );
1121        let tree = ContentHash::compute(b"tree");
1122        let timestamp = Utc::now();
1123        let logical_change_id = ChangeId::from_bytes([3; 16]);
1124        let state_a = State::new_snapshot(tree, vec![], attribution_a)
1125            .with_change_id(logical_change_id)
1126            .with_timestamp(timestamp);
1127        let state_b = State::new_snapshot(tree, vec![], attribution_b)
1128            .with_change_id(logical_change_id)
1129            .with_timestamp(timestamp);
1130
1131        assert_ne!(state_a.compute_hash(), state_b.compute_hash());
1132    }
1133
1134    #[test]
1135    fn agent_segment_is_included_in_state_hash_length_prefix() {
1136        let state = State::new_snapshot(
1137            ContentHash::compute(b"tree"),
1138            vec![],
1139            Attribution::with_agent(
1140                Principal::new("Alice", "alice@example.com"),
1141                crate::object::Agent::new("openai", "gpt-5").with_session("sess-1", "segment-1"),
1142            ),
1143        );
1144        let segment_len = "segment-1".len() as u64 + 2;
1145        let missing_segment_len_hash = ContentHash::compute_typed_with_len(
1146            "state",
1147            state.hash_len() - segment_len,
1148            |hasher| state.update_hash(hasher),
1149        );
1150
1151        assert_ne!(
1152            state.compute_hash(),
1153            missing_segment_len_hash,
1154            "segment_id's option tag, bytes, and terminator must affect the typed length prefix",
1155        );
1156    }
1157
1158    fn sample_state() -> State {
1159        State::new_snapshot(ContentHash::compute(b"tree"), vec![], sample_attribution())
1160    }
1161
1162    fn assert_mutator_invalidates_cached_hash(
1163        mut state: State,
1164        mutate: impl FnOnce(State) -> State,
1165    ) {
1166        let original_hash = state.hash();
1167        let mut updated = mutate(state);
1168        assert_ne!(updated.hash(), original_hash);
1169        assert_eq!(updated.hash(), updated.compute_hash());
1170    }
1171
1172    #[test]
1173    fn with_intent_invalidates_cached_hash() {
1174        assert_mutator_invalidates_cached_hash(sample_state(), |state| {
1175            state.with_intent("capture intent")
1176        });
1177    }
1178
1179    #[test]
1180    fn with_confidence_invalidates_cached_hash() {
1181        assert_mutator_invalidates_cached_hash(sample_state(), |state| state.with_confidence(0.9));
1182    }
1183
1184    #[test]
1185    fn with_verification_invalidates_cached_hash() {
1186        assert_mutator_invalidates_cached_hash(sample_state(), |state| {
1187            state.with_verification(Verification::new().with_tests_passed(true))
1188        });
1189    }
1190
1191    #[test]
1192    fn with_status_invalidates_cached_hash() {
1193        assert_mutator_invalidates_cached_hash(sample_state(), |state| {
1194            state.with_status(Status::Published)
1195        });
1196    }
1197
1198    #[test]
1199    fn with_timestamp_invalidates_cached_hash() {
1200        assert_mutator_invalidates_cached_hash(sample_state(), |state| {
1201            state.with_timestamp(Utc::now() + chrono::Duration::seconds(1))
1202        });
1203    }
1204
1205    /// The git-fidelity fields (#564 step 1) MUST be part of the hash so two
1206    /// git-distinct commits can't dedup-collide. Each field, set in
1207    /// isolation, must move the hash.
1208    #[test]
1209    fn fidelity_fields_are_part_of_state_hash() {
1210        let base = sample_state();
1211        let base_hash = base.compute_hash();
1212
1213        let with_committer = sample_state().with_change_id(base.change_id);
1214        let mut with_committer =
1215            with_committer.with_committer(Principal::new("Carol", "carol@example.com"));
1216        with_committer.created_at = base.created_at;
1217        assert_ne!(
1218            with_committer.hash(),
1219            base_hash,
1220            "committer must affect the state hash"
1221        );
1222
1223        for mutate in [
1224            |s: State| s.with_tz_offsets(3600, -7200),
1225            |s: State| s.with_authored_at(Utc::now() + chrono::Duration::seconds(1)),
1226            |s: State| s.with_raw_message("verbatim body\n"),
1227            // gpgsig now rides inline in extra_headers at its captured position.
1228            |s: State| {
1229                s.with_extra_headers(vec![(
1230                    b"gpgsig".to_vec(),
1231                    b"-----BEGIN PGP SIGNATURE-----\n".to_vec(),
1232                )])
1233            },
1234            |s: State| s.with_extra_headers(vec![(b"mergetag".to_vec(), b"x".to_vec())]),
1235        ] {
1236            let seeded = sample_state().with_change_id(base.change_id);
1237            let mut decorated = mutate(seeded);
1238            decorated.created_at = base.created_at;
1239            assert_ne!(
1240                decorated.hash(),
1241                base_hash,
1242                "fidelity field must affect the state hash"
1243            );
1244        }
1245    }
1246
1247    /// extra_headers order is load-bearing (#566): the same pairs in a
1248    /// different order must hash differently.
1249    #[test]
1250    fn extra_headers_order_affects_hash() {
1251        let base = sample_state();
1252        let one = sample_state().with_change_id(base.change_id);
1253        let mut one = one.with_extra_headers(vec![
1254            (b"a".to_vec(), b"1".to_vec()),
1255            (b"b".to_vec(), b"2".to_vec()),
1256        ]);
1257        one.created_at = base.created_at;
1258
1259        let two = sample_state().with_change_id(base.change_id);
1260        let mut two = two.with_extra_headers(vec![
1261            (b"b".to_vec(), b"2".to_vec()),
1262            (b"a".to_vec(), b"1".to_vec()),
1263        ]);
1264        two.created_at = base.created_at;
1265
1266        assert_ne!(one.hash(), two.hash());
1267    }
1268
1269    /// The fidelity fields set together produce a stable, recomputable
1270    /// hash (guards against a `hash_len`/`update_hash` divergence making
1271    /// the cached hash differ from a fresh `compute_hash`).
1272    #[test]
1273    fn fidelity_fields_hash_is_stable() {
1274        let mut state = sample_state()
1275            .with_committer(Principal::new("Dave", "dave@example.com"))
1276            .with_tz_offsets(3600, 0)
1277            .with_authored_at(Utc::now())
1278            .with_raw_message("body\n")
1279            .with_extra_headers(vec![
1280                (b"gpgsig".to_vec(), b"sig".to_vec()),
1281                (b"k".to_vec(), b"v".to_vec()),
1282            ]);
1283        assert_eq!(state.hash(), state.compute_hash());
1284    }
1285
1286    /// A non-UTF8 git message body (latin-1 `café` = `caf\xe9`) must be
1287    /// stored byte-identically. `raw_message` is `Vec<u8>`, not `String`,
1288    /// precisely so these bytes survive; the hash stays stable/recomputable
1289    /// over the raw bytes (length-prefixed framing, NUL-safe). #564 step 1.
1290    #[test]
1291    fn non_utf8_raw_message_is_byte_preserved() {
1292        let raw = b"caf\xe9\n".to_vec();
1293        assert!(
1294            String::from_utf8(raw.clone()).is_err(),
1295            "test fixture must be invalid UTF-8 to be meaningful"
1296        );
1297        let mut state = sample_state().with_raw_message(&raw);
1298        assert_eq!(
1299            state.raw_message.as_deref(),
1300            Some(raw.as_slice()),
1301            "raw bytes preserved verbatim"
1302        );
1303        // rmp serialize → deserialize (the store's on-disk codec) keeps the
1304        // bytes intact, and the hash recomputes identically afterwards.
1305        let bytes = rmp_serde::to_vec(&state).expect("serialize state");
1306        let back: State = rmp_serde::from_slice(&bytes).expect("deserialize state");
1307        assert_eq!(back.raw_message.as_deref(), Some(raw.as_slice()));
1308        let mut back = back;
1309        assert_eq!(state.hash(), back.hash());
1310        assert_eq!(back.hash(), back.compute_hash());
1311    }
1312
1313    /// A NUL byte inside the message must not be swallowed/truncated by the
1314    /// hash framing — length-prefixed `raw_message` is what makes this safe,
1315    /// where the old NUL-terminated string framing would have been ambiguous.
1316    #[test]
1317    fn raw_message_with_nul_byte_changes_hash() {
1318        let base = sample_state();
1319        let with_nul = sample_state().with_change_id(base.change_id);
1320        let mut a = with_nul.with_raw_message(b"a\x00b");
1321        a.created_at = base.created_at;
1322
1323        let other = sample_state().with_change_id(base.change_id);
1324        let mut b = other.with_raw_message(b"a\x00c");
1325        b.created_at = base.created_at;
1326
1327        assert_ne!(a.hash(), b.hash());
1328    }
1329
1330    /// Close-the-class conformance: extension headers are captured from the
1331    /// raw commit header block in their EXACT on-the-wire order, regardless of
1332    /// which ones a decoder would surface as typed fields. A commit whose
1333    /// optional headers are in non-canonical order — `x-custom`, then a folded
1334    /// `gpgsig`, then `encoding`, then a folded `mergetag` — must reproduce that
1335    /// exact ordered `(name, value)` byte sequence. This fails if any header is
1336    /// reordered, prepended, appended, or dropped. #564 de-lossy step 1.
1337    #[test]
1338    fn parse_extension_headers_preserves_noncanonical_wire_order() {
1339        // A folded `mergetag` value carries a full tag object, which itself has
1340        // an internal blank line between the tag headers and the tag message —
1341        // on the wire that blank line is folded to a single space (` `), NEVER
1342        // an empty line, so it must not be mistaken for the header/body split.
1343        // Built line-by-line (NOT a `\`-continued literal, which would eat the
1344        // load-bearing leading space on each folded continuation line).
1345        let lines: &[&[u8]] = &[
1346            b"tree 1111111111111111111111111111111111111111",
1347            b"parent 2222222222222222222222222222222222222222",
1348            b"author Alice <alice@example.com> 1700000000 +0000",
1349            b"committer Bob <bob@example.com> 1700000100 +0000",
1350            b"x-custom custom value",
1351            b"gpgsig -----BEGIN PGP SIGNATURE-----",
1352            b" sig-line-1",
1353            b" -----END PGP SIGNATURE-----",
1354            b"encoding ISO-8859-1",
1355            b"mergetag object 3333333333333333333333333333333333333333",
1356            b" type commit",
1357            b" tag sidetag",
1358            b" tagger Carol <carol@example.com> 1700000050 +0000",
1359            b" ", // folded blank line inside the tag object (one space)
1360            b" signed side tag",
1361            b"", // the real header/body separator (empty line)
1362            b"the commit message",
1363            b"",
1364        ];
1365        let content = lines.join(&b'\n');
1366
1367        let headers = parse_commit_extension_headers(&content);
1368
1369        let expected: Vec<(Vec<u8>, Vec<u8>)> = vec![
1370            (b"x-custom".to_vec(), b"custom value".to_vec()),
1371            (
1372                b"gpgsig".to_vec(),
1373                // Unfolded: internal newlines restored, NO trailing newline (the
1374                // serializer re-folds each `\n` to `\n `, spike §2).
1375                b"-----BEGIN PGP SIGNATURE-----\nsig-line-1\n-----END PGP SIGNATURE-----"
1376                    .to_vec(),
1377            ),
1378            (b"encoding".to_vec(), b"ISO-8859-1".to_vec()),
1379            (
1380                b"mergetag".to_vec(),
1381                // The folded ` \n` blank line unfolds to an empty segment, so the
1382                // tag object's header/message split survives as a real `\n\n`.
1383                b"object 3333333333333333333333333333333333333333\ntype commit\ntag sidetag\ntagger Carol <carol@example.com> 1700000050 +0000\n\nsigned side tag".to_vec(),
1384            ),
1385        ];
1386
1387        assert_eq!(headers, expected);
1388    }
1389
1390    /// A commit with no extension headers (the common case) yields an empty
1391    /// vec — `tree`/`parent`/`author`/`committer` are modelled natively and
1392    /// never leak into `extra_headers`.
1393    #[test]
1394    fn parse_extension_headers_empty_when_only_core_headers() {
1395        let content: &[u8] = b"\
1396tree 1111111111111111111111111111111111111111\n\
1397author Alice <alice@example.com> 1700000000 +0000\n\
1398committer Bob <bob@example.com> 1700000100 +0000\n\
1399\n\
1400just a message\n";
1401        assert!(parse_commit_extension_headers(content).is_empty());
1402    }
1403}